repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
TiffSequence._parse
def _parse(self): """Get axes and shape from file names.""" if not self.pattern: raise TiffSequence.ParseError('invalid pattern') pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE) matches = pattern.findall(os.path.split(self.files[0])[-1]) if not matches: raise TiffSequence.ParseError('pattern does not match file names') matches = matches[-1] if len(matches) % 2: raise TiffSequence.ParseError( 'pattern does not match axis name and index') axes = ''.join(m for m in matches[::2] if m) if not axes: raise TiffSequence.ParseError('pattern does not match file names') indices = [] for fname in self.files: fname = os.path.split(fname)[-1] matches = pattern.findall(fname)[-1] if axes != ''.join(m for m in matches[::2] if m): raise ValueError('axes do not match within image sequence') indices.append([int(m) for m in matches[1::2] if m]) shape = tuple(numpy.max(indices, axis=0)) startindex = tuple(numpy.min(indices, axis=0)) shape = tuple(i-j+1 for i, j in zip(shape, startindex)) if product(shape) != len(self.files): log.warning( 'TiffSequence: files are missing. Missing data are zeroed') self.axes = axes.upper() self.shape = shape self._indices = indices self._startindex = startindex
python
def _parse(self): """Get axes and shape from file names.""" if not self.pattern: raise TiffSequence.ParseError('invalid pattern') pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE) matches = pattern.findall(os.path.split(self.files[0])[-1]) if not matches: raise TiffSequence.ParseError('pattern does not match file names') matches = matches[-1] if len(matches) % 2: raise TiffSequence.ParseError( 'pattern does not match axis name and index') axes = ''.join(m for m in matches[::2] if m) if not axes: raise TiffSequence.ParseError('pattern does not match file names') indices = [] for fname in self.files: fname = os.path.split(fname)[-1] matches = pattern.findall(fname)[-1] if axes != ''.join(m for m in matches[::2] if m): raise ValueError('axes do not match within image sequence') indices.append([int(m) for m in matches[1::2] if m]) shape = tuple(numpy.max(indices, axis=0)) startindex = tuple(numpy.min(indices, axis=0)) shape = tuple(i-j+1 for i, j in zip(shape, startindex)) if product(shape) != len(self.files): log.warning( 'TiffSequence: files are missing. Missing data are zeroed') self.axes = axes.upper() self.shape = shape self._indices = indices self._startindex = startindex
[ "def", "_parse", "(", "self", ")", ":", "if", "not", "self", ".", "pattern", ":", "raise", "TiffSequence", ".", "ParseError", "(", "'invalid pattern'", ")", "pattern", "=", "re", ".", "compile", "(", "self", ".", "pattern", ",", "re", ".", "IGNORECASE", "|", "re", ".", "VERBOSE", ")", "matches", "=", "pattern", ".", "findall", "(", "os", ".", "path", ".", "split", "(", "self", ".", "files", "[", "0", "]", ")", "[", "-", "1", "]", ")", "if", "not", "matches", ":", "raise", "TiffSequence", ".", "ParseError", "(", "'pattern does not match file names'", ")", "matches", "=", "matches", "[", "-", "1", "]", "if", "len", "(", "matches", ")", "%", "2", ":", "raise", "TiffSequence", ".", "ParseError", "(", "'pattern does not match axis name and index'", ")", "axes", "=", "''", ".", "join", "(", "m", "for", "m", "in", "matches", "[", ":", ":", "2", "]", "if", "m", ")", "if", "not", "axes", ":", "raise", "TiffSequence", ".", "ParseError", "(", "'pattern does not match file names'", ")", "indices", "=", "[", "]", "for", "fname", "in", "self", ".", "files", ":", "fname", "=", "os", ".", "path", ".", "split", "(", "fname", ")", "[", "-", "1", "]", "matches", "=", "pattern", ".", "findall", "(", "fname", ")", "[", "-", "1", "]", "if", "axes", "!=", "''", ".", "join", "(", "m", "for", "m", "in", "matches", "[", ":", ":", "2", "]", "if", "m", ")", ":", "raise", "ValueError", "(", "'axes do not match within image sequence'", ")", "indices", ".", "append", "(", "[", "int", "(", "m", ")", "for", "m", "in", "matches", "[", "1", ":", ":", "2", "]", "if", "m", "]", ")", "shape", "=", "tuple", "(", "numpy", ".", "max", "(", "indices", ",", "axis", "=", "0", ")", ")", "startindex", "=", "tuple", "(", "numpy", ".", "min", "(", "indices", ",", "axis", "=", "0", ")", ")", "shape", "=", "tuple", "(", "i", "-", "j", "+", "1", "for", "i", ",", "j", "in", "zip", "(", "shape", ",", "startindex", ")", ")", "if", "product", "(", "shape", ")", "!=", "len", "(", "self", ".", "files", ")", ":", "log", ".", "warning", "(", "'TiffSequence: files are missing. Missing data are zeroed'", ")", "self", ".", "axes", "=", "axes", ".", "upper", "(", ")", "self", ".", "shape", "=", "shape", "self", ".", "_indices", "=", "indices", "self", ".", "_startindex", "=", "startindex" ]
Get axes and shape from file names.
[ "Get", "axes", "and", "shape", "from", "file", "names", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5402-L5435
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.open
def open(self): """Open or re-open file.""" if self._fh: return # file is open if isinstance(self._file, pathlib.Path): self._file = str(self._file) if isinstance(self._file, basestring): # file name self._file = os.path.realpath(self._file) self._dir, self._name = os.path.split(self._file) self._fh = open(self._file, self._mode) self._close = True if self._offset is None: self._offset = 0 elif isinstance(self._file, FileHandle): # FileHandle self._fh = self._file._fh if self._offset is None: self._offset = 0 self._offset += self._file._offset self._close = False if not self._name: if self._offset: name, ext = os.path.splitext(self._file._name) self._name = '%s@%i%s' % (name, self._offset, ext) else: self._name = self._file._name if self._mode and self._mode != self._file._mode: raise ValueError('FileHandle has wrong mode') self._mode = self._file._mode self._dir = self._file._dir elif hasattr(self._file, 'seek'): # binary stream: open file, BytesIO try: self._file.tell() except Exception: raise ValueError('binary stream is not seekable') self._fh = self._file if self._offset is None: self._offset = self._file.tell() self._close = False if not self._name: try: self._dir, self._name = os.path.split(self._fh.name) except AttributeError: self._name = 'Unnamed binary stream' try: self._mode = self._fh.mode except AttributeError: pass else: raise ValueError('The first parameter must be a file name, ' 'seekable binary stream, or FileHandle') if self._offset: self._fh.seek(self._offset) if self._size is None: pos = self._fh.tell() self._fh.seek(self._offset, 2) self._size = self._fh.tell() self._fh.seek(pos) try: self._fh.fileno() self.is_file = True except Exception: self.is_file = False
python
def open(self): """Open or re-open file.""" if self._fh: return # file is open if isinstance(self._file, pathlib.Path): self._file = str(self._file) if isinstance(self._file, basestring): # file name self._file = os.path.realpath(self._file) self._dir, self._name = os.path.split(self._file) self._fh = open(self._file, self._mode) self._close = True if self._offset is None: self._offset = 0 elif isinstance(self._file, FileHandle): # FileHandle self._fh = self._file._fh if self._offset is None: self._offset = 0 self._offset += self._file._offset self._close = False if not self._name: if self._offset: name, ext = os.path.splitext(self._file._name) self._name = '%s@%i%s' % (name, self._offset, ext) else: self._name = self._file._name if self._mode and self._mode != self._file._mode: raise ValueError('FileHandle has wrong mode') self._mode = self._file._mode self._dir = self._file._dir elif hasattr(self._file, 'seek'): # binary stream: open file, BytesIO try: self._file.tell() except Exception: raise ValueError('binary stream is not seekable') self._fh = self._file if self._offset is None: self._offset = self._file.tell() self._close = False if not self._name: try: self._dir, self._name = os.path.split(self._fh.name) except AttributeError: self._name = 'Unnamed binary stream' try: self._mode = self._fh.mode except AttributeError: pass else: raise ValueError('The first parameter must be a file name, ' 'seekable binary stream, or FileHandle') if self._offset: self._fh.seek(self._offset) if self._size is None: pos = self._fh.tell() self._fh.seek(self._offset, 2) self._size = self._fh.tell() self._fh.seek(pos) try: self._fh.fileno() self.is_file = True except Exception: self.is_file = False
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "_fh", ":", "return", "# file is open", "if", "isinstance", "(", "self", ".", "_file", ",", "pathlib", ".", "Path", ")", ":", "self", ".", "_file", "=", "str", "(", "self", ".", "_file", ")", "if", "isinstance", "(", "self", ".", "_file", ",", "basestring", ")", ":", "# file name", "self", ".", "_file", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "_file", ")", "self", ".", "_dir", ",", "self", ".", "_name", "=", "os", ".", "path", ".", "split", "(", "self", ".", "_file", ")", "self", ".", "_fh", "=", "open", "(", "self", ".", "_file", ",", "self", ".", "_mode", ")", "self", ".", "_close", "=", "True", "if", "self", ".", "_offset", "is", "None", ":", "self", ".", "_offset", "=", "0", "elif", "isinstance", "(", "self", ".", "_file", ",", "FileHandle", ")", ":", "# FileHandle", "self", ".", "_fh", "=", "self", ".", "_file", ".", "_fh", "if", "self", ".", "_offset", "is", "None", ":", "self", ".", "_offset", "=", "0", "self", ".", "_offset", "+=", "self", ".", "_file", ".", "_offset", "self", ".", "_close", "=", "False", "if", "not", "self", ".", "_name", ":", "if", "self", ".", "_offset", ":", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "_file", ".", "_name", ")", "self", ".", "_name", "=", "'%s@%i%s'", "%", "(", "name", ",", "self", ".", "_offset", ",", "ext", ")", "else", ":", "self", ".", "_name", "=", "self", ".", "_file", ".", "_name", "if", "self", ".", "_mode", "and", "self", ".", "_mode", "!=", "self", ".", "_file", ".", "_mode", ":", "raise", "ValueError", "(", "'FileHandle has wrong mode'", ")", "self", ".", "_mode", "=", "self", ".", "_file", ".", "_mode", "self", ".", "_dir", "=", "self", ".", "_file", ".", "_dir", "elif", "hasattr", "(", "self", ".", "_file", ",", "'seek'", ")", ":", "# binary stream: open file, BytesIO", "try", ":", "self", ".", "_file", ".", "tell", "(", ")", "except", "Exception", ":", "raise", "ValueError", "(", "'binary stream is not seekable'", ")", "self", ".", "_fh", "=", "self", ".", "_file", "if", "self", ".", "_offset", "is", "None", ":", "self", ".", "_offset", "=", "self", ".", "_file", ".", "tell", "(", ")", "self", ".", "_close", "=", "False", "if", "not", "self", ".", "_name", ":", "try", ":", "self", ".", "_dir", ",", "self", ".", "_name", "=", "os", ".", "path", ".", "split", "(", "self", ".", "_fh", ".", "name", ")", "except", "AttributeError", ":", "self", ".", "_name", "=", "'Unnamed binary stream'", "try", ":", "self", ".", "_mode", "=", "self", ".", "_fh", ".", "mode", "except", "AttributeError", ":", "pass", "else", ":", "raise", "ValueError", "(", "'The first parameter must be a file name, '", "'seekable binary stream, or FileHandle'", ")", "if", "self", ".", "_offset", ":", "self", ".", "_fh", ".", "seek", "(", "self", ".", "_offset", ")", "if", "self", ".", "_size", "is", "None", ":", "pos", "=", "self", ".", "_fh", ".", "tell", "(", ")", "self", ".", "_fh", ".", "seek", "(", "self", ".", "_offset", ",", "2", ")", "self", ".", "_size", "=", "self", ".", "_fh", ".", "tell", "(", ")", "self", ".", "_fh", ".", "seek", "(", "pos", ")", "try", ":", "self", ".", "_fh", ".", "fileno", "(", ")", "self", ".", "is_file", "=", "True", "except", "Exception", ":", "self", ".", "is_file", "=", "False" ]
Open or re-open file.
[ "Open", "or", "re", "-", "open", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5502-L5570
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.read
def read(self, size=-1): """Read 'size' bytes from file, or until EOF is reached.""" if size < 0 and self._offset: size = self._size return self._fh.read(size)
python
def read(self, size=-1): """Read 'size' bytes from file, or until EOF is reached.""" if size < 0 and self._offset: size = self._size return self._fh.read(size)
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "<", "0", "and", "self", ".", "_offset", ":", "size", "=", "self", ".", "_size", "return", "self", ".", "_fh", ".", "read", "(", "size", ")" ]
Read 'size' bytes from file, or until EOF is reached.
[ "Read", "size", "bytes", "from", "file", "or", "until", "EOF", "is", "reached", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5572-L5576
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.memmap_array
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): """Return numpy.memmap of data stored in file.""" if not self.is_file: raise ValueError('Cannot memory-map file without fileno') return numpy.memmap(self._fh, dtype=dtype, mode=mode, offset=self._offset + offset, shape=shape, order=order)
python
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): """Return numpy.memmap of data stored in file.""" if not self.is_file: raise ValueError('Cannot memory-map file without fileno') return numpy.memmap(self._fh, dtype=dtype, mode=mode, offset=self._offset + offset, shape=shape, order=order)
[ "def", "memmap_array", "(", "self", ",", "dtype", ",", "shape", ",", "offset", "=", "0", ",", "mode", "=", "'r'", ",", "order", "=", "'C'", ")", ":", "if", "not", "self", ".", "is_file", ":", "raise", "ValueError", "(", "'Cannot memory-map file without fileno'", ")", "return", "numpy", ".", "memmap", "(", "self", ".", "_fh", ",", "dtype", "=", "dtype", ",", "mode", "=", "mode", ",", "offset", "=", "self", ".", "_offset", "+", "offset", ",", "shape", "=", "shape", ",", "order", "=", "order", ")" ]
Return numpy.memmap of data stored in file.
[ "Return", "numpy", ".", "memmap", "of", "data", "stored", "in", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5590-L5596
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.read_array
def read_array(self, dtype, count=-1, out=None): """Return numpy array from file in native byte order.""" fh = self._fh dtype = numpy.dtype(dtype) if count < 0: size = self._size if out is None else out.nbytes count = size // dtype.itemsize else: size = count * dtype.itemsize result = numpy.empty(count, dtype) if out is None else out if result.nbytes != size: raise ValueError('size mismatch') n = fh.readinto(result) if n != size: raise ValueError('failed to read %i bytes' % size) if not result.dtype.isnative: if not dtype.isnative: result.byteswap(True) result = result.newbyteorder() elif result.dtype.isnative != dtype.isnative: result.byteswap(True) if out is not None: if hasattr(out, 'flush'): out.flush() return result
python
def read_array(self, dtype, count=-1, out=None): """Return numpy array from file in native byte order.""" fh = self._fh dtype = numpy.dtype(dtype) if count < 0: size = self._size if out is None else out.nbytes count = size // dtype.itemsize else: size = count * dtype.itemsize result = numpy.empty(count, dtype) if out is None else out if result.nbytes != size: raise ValueError('size mismatch') n = fh.readinto(result) if n != size: raise ValueError('failed to read %i bytes' % size) if not result.dtype.isnative: if not dtype.isnative: result.byteswap(True) result = result.newbyteorder() elif result.dtype.isnative != dtype.isnative: result.byteswap(True) if out is not None: if hasattr(out, 'flush'): out.flush() return result
[ "def", "read_array", "(", "self", ",", "dtype", ",", "count", "=", "-", "1", ",", "out", "=", "None", ")", ":", "fh", "=", "self", ".", "_fh", "dtype", "=", "numpy", ".", "dtype", "(", "dtype", ")", "if", "count", "<", "0", ":", "size", "=", "self", ".", "_size", "if", "out", "is", "None", "else", "out", ".", "nbytes", "count", "=", "size", "//", "dtype", ".", "itemsize", "else", ":", "size", "=", "count", "*", "dtype", ".", "itemsize", "result", "=", "numpy", ".", "empty", "(", "count", ",", "dtype", ")", "if", "out", "is", "None", "else", "out", "if", "result", ".", "nbytes", "!=", "size", ":", "raise", "ValueError", "(", "'size mismatch'", ")", "n", "=", "fh", ".", "readinto", "(", "result", ")", "if", "n", "!=", "size", ":", "raise", "ValueError", "(", "'failed to read %i bytes'", "%", "size", ")", "if", "not", "result", ".", "dtype", ".", "isnative", ":", "if", "not", "dtype", ".", "isnative", ":", "result", ".", "byteswap", "(", "True", ")", "result", "=", "result", ".", "newbyteorder", "(", ")", "elif", "result", ".", "dtype", ".", "isnative", "!=", "dtype", ".", "isnative", ":", "result", ".", "byteswap", "(", "True", ")", "if", "out", "is", "not", "None", ":", "if", "hasattr", "(", "out", ",", "'flush'", ")", ":", "out", ".", "flush", "(", ")", "return", "result" ]
Return numpy array from file in native byte order.
[ "Return", "numpy", "array", "from", "file", "in", "native", "byte", "order", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5598-L5629
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.read_record
def read_record(self, dtype, shape=1, byteorder=None): """Return numpy record from file.""" rec = numpy.rec try: record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder) except Exception: dtype = numpy.dtype(dtype) if shape is None: shape = self._size // dtype.itemsize size = product(sequence(shape)) * dtype.itemsize data = self._fh.read(size) record = rec.fromstring(data, dtype, shape, byteorder=byteorder) return record[0] if shape == 1 else record
python
def read_record(self, dtype, shape=1, byteorder=None): """Return numpy record from file.""" rec = numpy.rec try: record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder) except Exception: dtype = numpy.dtype(dtype) if shape is None: shape = self._size // dtype.itemsize size = product(sequence(shape)) * dtype.itemsize data = self._fh.read(size) record = rec.fromstring(data, dtype, shape, byteorder=byteorder) return record[0] if shape == 1 else record
[ "def", "read_record", "(", "self", ",", "dtype", ",", "shape", "=", "1", ",", "byteorder", "=", "None", ")", ":", "rec", "=", "numpy", ".", "rec", "try", ":", "record", "=", "rec", ".", "fromfile", "(", "self", ".", "_fh", ",", "dtype", ",", "shape", ",", "byteorder", "=", "byteorder", ")", "except", "Exception", ":", "dtype", "=", "numpy", ".", "dtype", "(", "dtype", ")", "if", "shape", "is", "None", ":", "shape", "=", "self", ".", "_size", "//", "dtype", ".", "itemsize", "size", "=", "product", "(", "sequence", "(", "shape", ")", ")", "*", "dtype", ".", "itemsize", "data", "=", "self", ".", "_fh", ".", "read", "(", "size", ")", "record", "=", "rec", ".", "fromstring", "(", "data", ",", "dtype", ",", "shape", ",", "byteorder", "=", "byteorder", ")", "return", "record", "[", "0", "]", "if", "shape", "==", "1", "else", "record" ]
Return numpy record from file.
[ "Return", "numpy", "record", "from", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5631-L5643
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.write_empty
def write_empty(self, size): """Append size bytes to file. Position must be at end of file.""" if size < 1: return self._fh.seek(size-1, 1) self._fh.write(b'\x00')
python
def write_empty(self, size): """Append size bytes to file. Position must be at end of file.""" if size < 1: return self._fh.seek(size-1, 1) self._fh.write(b'\x00')
[ "def", "write_empty", "(", "self", ",", "size", ")", ":", "if", "size", "<", "1", ":", "return", "self", ".", "_fh", ".", "seek", "(", "size", "-", "1", ",", "1", ")", "self", ".", "_fh", ".", "write", "(", "b'\\x00'", ")" ]
Append size bytes to file. Position must be at end of file.
[ "Append", "size", "bytes", "to", "file", ".", "Position", "must", "be", "at", "end", "of", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5645-L5650
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.write_array
def write_array(self, data): """Write numpy array to binary file.""" try: data.tofile(self._fh) except Exception: # BytesIO self._fh.write(data.tostring())
python
def write_array(self, data): """Write numpy array to binary file.""" try: data.tofile(self._fh) except Exception: # BytesIO self._fh.write(data.tostring())
[ "def", "write_array", "(", "self", ",", "data", ")", ":", "try", ":", "data", ".", "tofile", "(", "self", ".", "_fh", ")", "except", "Exception", ":", "# BytesIO", "self", ".", "_fh", ".", "write", "(", "data", ".", "tostring", "(", ")", ")" ]
Write numpy array to binary file.
[ "Write", "numpy", "array", "to", "binary", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5652-L5658
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.seek
def seek(self, offset, whence=0): """Set file's current position.""" if self._offset: if whence == 0: self._fh.seek(self._offset + offset, whence) return if whence == 2 and self._size > 0: self._fh.seek(self._offset + self._size + offset, 0) return self._fh.seek(offset, whence)
python
def seek(self, offset, whence=0): """Set file's current position.""" if self._offset: if whence == 0: self._fh.seek(self._offset + offset, whence) return if whence == 2 and self._size > 0: self._fh.seek(self._offset + self._size + offset, 0) return self._fh.seek(offset, whence)
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "if", "self", ".", "_offset", ":", "if", "whence", "==", "0", ":", "self", ".", "_fh", ".", "seek", "(", "self", ".", "_offset", "+", "offset", ",", "whence", ")", "return", "if", "whence", "==", "2", "and", "self", ".", "_size", ">", "0", ":", "self", ".", "_fh", ".", "seek", "(", "self", ".", "_offset", "+", "self", ".", "_size", "+", "offset", ",", "0", ")", "return", "self", ".", "_fh", ".", "seek", "(", "offset", ",", "whence", ")" ]
Set file's current position.
[ "Set", "file", "s", "current", "position", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5664-L5673
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.close
def close(self): """Close file.""" if self._close and self._fh: self._fh.close() self._fh = None
python
def close(self): """Close file.""" if self._close and self._fh: self._fh.close() self._fh = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_close", "and", "self", ".", "_fh", ":", "self", ".", "_fh", ".", "close", "(", ")", "self", ".", "_fh", "=", "None" ]
Close file.
[ "Close", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5675-L5679
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
OpenFileCache.open
def open(self, filehandle): """Re-open file if necessary.""" with self.lock: if filehandle in self.files: self.files[filehandle] += 1 elif filehandle.closed: filehandle.open() self.files[filehandle] = 1 self.past.append(filehandle)
python
def open(self, filehandle): """Re-open file if necessary.""" with self.lock: if filehandle in self.files: self.files[filehandle] += 1 elif filehandle.closed: filehandle.open() self.files[filehandle] = 1 self.past.append(filehandle)
[ "def", "open", "(", "self", ",", "filehandle", ")", ":", "with", "self", ".", "lock", ":", "if", "filehandle", "in", "self", ".", "files", ":", "self", ".", "files", "[", "filehandle", "]", "+=", "1", "elif", "filehandle", ".", "closed", ":", "filehandle", ".", "open", "(", ")", "self", ".", "files", "[", "filehandle", "]", "=", "1", "self", ".", "past", ".", "append", "(", "filehandle", ")" ]
Re-open file if necessary.
[ "Re", "-", "open", "file", "if", "necessary", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5749-L5757
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
OpenFileCache.close
def close(self, filehandle): """Close openend file if no longer used.""" with self.lock: if filehandle in self.files: self.files[filehandle] -= 1 # trim the file cache index = 0 size = len(self.past) while size > self.size and index < size: filehandle = self.past[index] if self.files[filehandle] == 0: filehandle.close() del self.files[filehandle] del self.past[index] size -= 1 else: index += 1
python
def close(self, filehandle): """Close openend file if no longer used.""" with self.lock: if filehandle in self.files: self.files[filehandle] -= 1 # trim the file cache index = 0 size = len(self.past) while size > self.size and index < size: filehandle = self.past[index] if self.files[filehandle] == 0: filehandle.close() del self.files[filehandle] del self.past[index] size -= 1 else: index += 1
[ "def", "close", "(", "self", ",", "filehandle", ")", ":", "with", "self", ".", "lock", ":", "if", "filehandle", "in", "self", ".", "files", ":", "self", ".", "files", "[", "filehandle", "]", "-=", "1", "# trim the file cache", "index", "=", "0", "size", "=", "len", "(", "self", ".", "past", ")", "while", "size", ">", "self", ".", "size", "and", "index", "<", "size", ":", "filehandle", "=", "self", ".", "past", "[", "index", "]", "if", "self", ".", "files", "[", "filehandle", "]", "==", "0", ":", "filehandle", ".", "close", "(", ")", "del", "self", ".", "files", "[", "filehandle", "]", "del", "self", ".", "past", "[", "index", "]", "size", "-=", "1", "else", ":", "index", "+=", "1" ]
Close openend file if no longer used.
[ "Close", "openend", "file", "if", "no", "longer", "used", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5759-L5775
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
OpenFileCache.clear
def clear(self): """Close all opened files if not in use.""" with self.lock: for filehandle, refcount in list(self.files.items()): if refcount == 0: filehandle.close() del self.files[filehandle] del self.past[self.past.index(filehandle)]
python
def clear(self): """Close all opened files if not in use.""" with self.lock: for filehandle, refcount in list(self.files.items()): if refcount == 0: filehandle.close() del self.files[filehandle] del self.past[self.past.index(filehandle)]
[ "def", "clear", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "for", "filehandle", ",", "refcount", "in", "list", "(", "self", ".", "files", ".", "items", "(", ")", ")", ":", "if", "refcount", "==", "0", ":", "filehandle", ".", "close", "(", ")", "del", "self", ".", "files", "[", "filehandle", "]", "del", "self", ".", "past", "[", "self", ".", "past", ".", "index", "(", "filehandle", ")", "]" ]
Close all opened files if not in use.
[ "Close", "all", "opened", "files", "if", "not", "in", "use", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5777-L5784
noahmorrison/chevron
chevron/tokenizer.py
grab_literal
def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += literal.count('\n') return (literal, template) # There are no more tags in the template? except ValueError: # Then the rest of the template is a literal return (template, '')
python
def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += literal.count('\n') return (literal, template) # There are no more tags in the template? except ValueError: # Then the rest of the template is a literal return (template, '')
[ "def", "grab_literal", "(", "template", ",", "l_del", ")", ":", "global", "_CURRENT_LINE", "try", ":", "# Look for the next tag and move the template to it", "literal", ",", "template", "=", "template", ".", "split", "(", "l_del", ",", "1", ")", "_CURRENT_LINE", "+=", "literal", ".", "count", "(", "'\\n'", ")", "return", "(", "literal", ",", "template", ")", "# There are no more tags in the template?", "except", "ValueError", ":", "# Then the rest of the template is a literal", "return", "(", "template", ",", "''", ")" ]
Parse a literal from the template
[ "Parse", "a", "literal", "from", "the", "template" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L14-L28
noahmorrison/chevron
chevron/tokenizer.py
l_sa_check
def l_sa_check(template, literal, is_standalone): """Do a preliminary check to see if a tag could be a standalone""" # If there is a newline, or the previous tag was a standalone if literal.find('\n') != -1 or is_standalone: padding = literal.split('\n')[-1] # If all the characters since the last newline are spaces if padding.isspace() or padding == '': # Then the next tag could be a standalone return True else: # Otherwise it can't be return False
python
def l_sa_check(template, literal, is_standalone): """Do a preliminary check to see if a tag could be a standalone""" # If there is a newline, or the previous tag was a standalone if literal.find('\n') != -1 or is_standalone: padding = literal.split('\n')[-1] # If all the characters since the last newline are spaces if padding.isspace() or padding == '': # Then the next tag could be a standalone return True else: # Otherwise it can't be return False
[ "def", "l_sa_check", "(", "template", ",", "literal", ",", "is_standalone", ")", ":", "# If there is a newline, or the previous tag was a standalone", "if", "literal", ".", "find", "(", "'\\n'", ")", "!=", "-", "1", "or", "is_standalone", ":", "padding", "=", "literal", ".", "split", "(", "'\\n'", ")", "[", "-", "1", "]", "# If all the characters since the last newline are spaces", "if", "padding", ".", "isspace", "(", ")", "or", "padding", "==", "''", ":", "# Then the next tag could be a standalone", "return", "True", "else", ":", "# Otherwise it can't be", "return", "False" ]
Do a preliminary check to see if a tag could be a standalone
[ "Do", "a", "preliminary", "check", "to", "see", "if", "a", "tag", "could", "be", "a", "standalone" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L31-L44
noahmorrison/chevron
chevron/tokenizer.py
r_sa_check
def r_sa_check(template, tag_type, is_standalone): """Do a final checkto see if a tag could be a standalone""" # Check right side if we might be a standalone if is_standalone and tag_type not in ['variable', 'no escape']: on_newline = template.split('\n', 1) # If the stuff to the right of us are spaces we're a standalone if on_newline[0].isspace() or not on_newline[0]: return True else: return False # If we're a tag can't be a standalone else: return False
python
def r_sa_check(template, tag_type, is_standalone): """Do a final checkto see if a tag could be a standalone""" # Check right side if we might be a standalone if is_standalone and tag_type not in ['variable', 'no escape']: on_newline = template.split('\n', 1) # If the stuff to the right of us are spaces we're a standalone if on_newline[0].isspace() or not on_newline[0]: return True else: return False # If we're a tag can't be a standalone else: return False
[ "def", "r_sa_check", "(", "template", ",", "tag_type", ",", "is_standalone", ")", ":", "# Check right side if we might be a standalone", "if", "is_standalone", "and", "tag_type", "not", "in", "[", "'variable'", ",", "'no escape'", "]", ":", "on_newline", "=", "template", ".", "split", "(", "'\\n'", ",", "1", ")", "# If the stuff to the right of us are spaces we're a standalone", "if", "on_newline", "[", "0", "]", ".", "isspace", "(", ")", "or", "not", "on_newline", "[", "0", "]", ":", "return", "True", "else", ":", "return", "False", "# If we're a tag can't be a standalone", "else", ":", "return", "False" ]
Do a final checkto see if a tag could be a standalone
[ "Do", "a", "final", "checkto", "see", "if", "a", "tag", "could", "be", "a", "standalone" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L47-L62
noahmorrison/chevron
chevron/tokenizer.py
parse_tag
def parse_tag(template, l_del, r_del): """Parse a tag from a template""" global _CURRENT_LINE global _LAST_TAG_LINE tag_types = { '!': 'comment', '#': 'section', '^': 'inverted section', '/': 'end', '>': 'partial', '=': 'set delimiter?', '{': 'no escape?', '&': 'no escape' } # Get the tag try: tag, template = template.split(r_del, 1) except ValueError: raise ChevronError('unclosed tag ' 'at line {0}'.format(_CURRENT_LINE)) # Find the type meaning of the first character tag_type = tag_types.get(tag[0], 'variable') # If the type is not a variable if tag_type != 'variable': # Then that first character is not needed tag = tag[1:] # If we might be a set delimiter tag if tag_type == 'set delimiter?': # Double check to make sure we are if tag.endswith('='): tag_type = 'set delimiter' # Remove the equal sign tag = tag[:-1] # Otherwise we should complain else: raise ChevronError('unclosed set delimiter tag\n' 'at line {0}'.format(_CURRENT_LINE)) # If we might be a no html escape tag elif tag_type == 'no escape?': # And we have a third curly brace # (And are using curly braces as delimiters) if l_del == '{{' and r_del == '}}' and template.startswith('}'): # Then we are a no html escape tag template = template[1:] tag_type = 'no escape' # Strip the whitespace off the key and return return ((tag_type, tag.strip()), template)
python
def parse_tag(template, l_del, r_del): """Parse a tag from a template""" global _CURRENT_LINE global _LAST_TAG_LINE tag_types = { '!': 'comment', '#': 'section', '^': 'inverted section', '/': 'end', '>': 'partial', '=': 'set delimiter?', '{': 'no escape?', '&': 'no escape' } # Get the tag try: tag, template = template.split(r_del, 1) except ValueError: raise ChevronError('unclosed tag ' 'at line {0}'.format(_CURRENT_LINE)) # Find the type meaning of the first character tag_type = tag_types.get(tag[0], 'variable') # If the type is not a variable if tag_type != 'variable': # Then that first character is not needed tag = tag[1:] # If we might be a set delimiter tag if tag_type == 'set delimiter?': # Double check to make sure we are if tag.endswith('='): tag_type = 'set delimiter' # Remove the equal sign tag = tag[:-1] # Otherwise we should complain else: raise ChevronError('unclosed set delimiter tag\n' 'at line {0}'.format(_CURRENT_LINE)) # If we might be a no html escape tag elif tag_type == 'no escape?': # And we have a third curly brace # (And are using curly braces as delimiters) if l_del == '{{' and r_del == '}}' and template.startswith('}'): # Then we are a no html escape tag template = template[1:] tag_type = 'no escape' # Strip the whitespace off the key and return return ((tag_type, tag.strip()), template)
[ "def", "parse_tag", "(", "template", ",", "l_del", ",", "r_del", ")", ":", "global", "_CURRENT_LINE", "global", "_LAST_TAG_LINE", "tag_types", "=", "{", "'!'", ":", "'comment'", ",", "'#'", ":", "'section'", ",", "'^'", ":", "'inverted section'", ",", "'/'", ":", "'end'", ",", "'>'", ":", "'partial'", ",", "'='", ":", "'set delimiter?'", ",", "'{'", ":", "'no escape?'", ",", "'&'", ":", "'no escape'", "}", "# Get the tag", "try", ":", "tag", ",", "template", "=", "template", ".", "split", "(", "r_del", ",", "1", ")", "except", "ValueError", ":", "raise", "ChevronError", "(", "'unclosed tag '", "'at line {0}'", ".", "format", "(", "_CURRENT_LINE", ")", ")", "# Find the type meaning of the first character", "tag_type", "=", "tag_types", ".", "get", "(", "tag", "[", "0", "]", ",", "'variable'", ")", "# If the type is not a variable", "if", "tag_type", "!=", "'variable'", ":", "# Then that first character is not needed", "tag", "=", "tag", "[", "1", ":", "]", "# If we might be a set delimiter tag", "if", "tag_type", "==", "'set delimiter?'", ":", "# Double check to make sure we are", "if", "tag", ".", "endswith", "(", "'='", ")", ":", "tag_type", "=", "'set delimiter'", "# Remove the equal sign", "tag", "=", "tag", "[", ":", "-", "1", "]", "# Otherwise we should complain", "else", ":", "raise", "ChevronError", "(", "'unclosed set delimiter tag\\n'", "'at line {0}'", ".", "format", "(", "_CURRENT_LINE", ")", ")", "# If we might be a no html escape tag", "elif", "tag_type", "==", "'no escape?'", ":", "# And we have a third curly brace", "# (And are using curly braces as delimiters)", "if", "l_del", "==", "'{{'", "and", "r_del", "==", "'}}'", "and", "template", ".", "startswith", "(", "'}'", ")", ":", "# Then we are a no html escape tag", "template", "=", "template", "[", "1", ":", "]", "tag_type", "=", "'no escape'", "# Strip the whitespace off the key and return", "return", "(", "(", "tag_type", ",", "tag", ".", "strip", "(", ")", ")", ",", "template", ")" ]
Parse a tag from a template
[ "Parse", "a", "tag", "from", "a", "template" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L65-L119
noahmorrison/chevron
chevron/tokenizer.py
tokenize
def tokenize(template, def_ldel='{{', def_rdel='}}'): """Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template def_ldel -- The default left delimiter ("{{" by default, as in spec compliant mustache) def_rdel -- The default right delimiter ("}}" by default, as in spec compliant mustache) Returns: A generator of mustache tags in the form of a tuple -- (tag_type, tag_key) Where tag_type is one of: * literal * section * inverted section * end * partial * no escape And tag_key is either the key or in the case of a literal tag, the literal itself. """ global _CURRENT_LINE, _LAST_TAG_LINE _CURRENT_LINE = 1 _LAST_TAG_LINE = None # If the template is a file-like object then read it try: template = template.read() except AttributeError: pass is_standalone = True open_sections = [] l_del = def_ldel r_del = def_rdel while template: literal, template = grab_literal(template, l_del) # If the template is completed if not template: # Then yield the literal and leave yield ('literal', literal) break # Do the first check to see if we could be a standalone is_standalone = l_sa_check(template, literal, is_standalone) # Parse the tag tag, template = parse_tag(template, l_del, r_del) tag_type, tag_key = tag # Special tag logic # If we are a set delimiter tag if tag_type == 'set delimiter': # Then get and set the delimiters dels = tag_key.strip().split(' ') l_del, r_del = dels[0], dels[-1] # If we are a section tag elif tag_type in ['section', 'inverted section']: # Then open a new section open_sections.append(tag_key) _LAST_TAG_LINE = _CURRENT_LINE # If we are an end tag elif tag_type == 'end': # Then check to see if the last opened section # is the same as us try: last_section = open_sections.pop() except IndexError: raise ChevronError('Trying to close tag "{0}"\n' 'Looks like it was not opened.\n' 'line {1}' .format(tag_key, _CURRENT_LINE + 1)) if tag_key != last_section: # Otherwise we need to complain raise ChevronError('Trying to close tag "{0}"\n' 'last open tag is "{1}"\n' 'line {2}' .format(tag_key, last_section, _CURRENT_LINE + 1)) # Do the second check to see if we're a standalone is_standalone = r_sa_check(template, tag_type, is_standalone) # Which if we are if is_standalone: # Remove the stuff before the newline template = template.split('\n', 1)[-1] # Partials need to keep the spaces on their left if tag_type != 'partial': # But other tags don't literal = literal.rstrip(' ') # Start yielding # Ignore literals that are empty if literal != '': yield ('literal', literal) # Ignore comments and set delimiters if tag_type not in ['comment', 'set delimiter?']: yield (tag_type, tag_key) # If there are any open sections when we're done if open_sections: # Then we need to complain raise ChevronError('Unexpected EOF\n' 'the tag "{0}" was never closed\n' 'was opened at line {1}' .format(open_sections[-1], _LAST_TAG_LINE))
python
def tokenize(template, def_ldel='{{', def_rdel='}}'): """Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template def_ldel -- The default left delimiter ("{{" by default, as in spec compliant mustache) def_rdel -- The default right delimiter ("}}" by default, as in spec compliant mustache) Returns: A generator of mustache tags in the form of a tuple -- (tag_type, tag_key) Where tag_type is one of: * literal * section * inverted section * end * partial * no escape And tag_key is either the key or in the case of a literal tag, the literal itself. """ global _CURRENT_LINE, _LAST_TAG_LINE _CURRENT_LINE = 1 _LAST_TAG_LINE = None # If the template is a file-like object then read it try: template = template.read() except AttributeError: pass is_standalone = True open_sections = [] l_del = def_ldel r_del = def_rdel while template: literal, template = grab_literal(template, l_del) # If the template is completed if not template: # Then yield the literal and leave yield ('literal', literal) break # Do the first check to see if we could be a standalone is_standalone = l_sa_check(template, literal, is_standalone) # Parse the tag tag, template = parse_tag(template, l_del, r_del) tag_type, tag_key = tag # Special tag logic # If we are a set delimiter tag if tag_type == 'set delimiter': # Then get and set the delimiters dels = tag_key.strip().split(' ') l_del, r_del = dels[0], dels[-1] # If we are a section tag elif tag_type in ['section', 'inverted section']: # Then open a new section open_sections.append(tag_key) _LAST_TAG_LINE = _CURRENT_LINE # If we are an end tag elif tag_type == 'end': # Then check to see if the last opened section # is the same as us try: last_section = open_sections.pop() except IndexError: raise ChevronError('Trying to close tag "{0}"\n' 'Looks like it was not opened.\n' 'line {1}' .format(tag_key, _CURRENT_LINE + 1)) if tag_key != last_section: # Otherwise we need to complain raise ChevronError('Trying to close tag "{0}"\n' 'last open tag is "{1}"\n' 'line {2}' .format(tag_key, last_section, _CURRENT_LINE + 1)) # Do the second check to see if we're a standalone is_standalone = r_sa_check(template, tag_type, is_standalone) # Which if we are if is_standalone: # Remove the stuff before the newline template = template.split('\n', 1)[-1] # Partials need to keep the spaces on their left if tag_type != 'partial': # But other tags don't literal = literal.rstrip(' ') # Start yielding # Ignore literals that are empty if literal != '': yield ('literal', literal) # Ignore comments and set delimiters if tag_type not in ['comment', 'set delimiter?']: yield (tag_type, tag_key) # If there are any open sections when we're done if open_sections: # Then we need to complain raise ChevronError('Unexpected EOF\n' 'the tag "{0}" was never closed\n' 'was opened at line {1}' .format(open_sections[-1], _LAST_TAG_LINE))
[ "def", "tokenize", "(", "template", ",", "def_ldel", "=", "'{{'", ",", "def_rdel", "=", "'}}'", ")", ":", "global", "_CURRENT_LINE", ",", "_LAST_TAG_LINE", "_CURRENT_LINE", "=", "1", "_LAST_TAG_LINE", "=", "None", "# If the template is a file-like object then read it", "try", ":", "template", "=", "template", ".", "read", "(", ")", "except", "AttributeError", ":", "pass", "is_standalone", "=", "True", "open_sections", "=", "[", "]", "l_del", "=", "def_ldel", "r_del", "=", "def_rdel", "while", "template", ":", "literal", ",", "template", "=", "grab_literal", "(", "template", ",", "l_del", ")", "# If the template is completed", "if", "not", "template", ":", "# Then yield the literal and leave", "yield", "(", "'literal'", ",", "literal", ")", "break", "# Do the first check to see if we could be a standalone", "is_standalone", "=", "l_sa_check", "(", "template", ",", "literal", ",", "is_standalone", ")", "# Parse the tag", "tag", ",", "template", "=", "parse_tag", "(", "template", ",", "l_del", ",", "r_del", ")", "tag_type", ",", "tag_key", "=", "tag", "# Special tag logic", "# If we are a set delimiter tag", "if", "tag_type", "==", "'set delimiter'", ":", "# Then get and set the delimiters", "dels", "=", "tag_key", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "l_del", ",", "r_del", "=", "dels", "[", "0", "]", ",", "dels", "[", "-", "1", "]", "# If we are a section tag", "elif", "tag_type", "in", "[", "'section'", ",", "'inverted section'", "]", ":", "# Then open a new section", "open_sections", ".", "append", "(", "tag_key", ")", "_LAST_TAG_LINE", "=", "_CURRENT_LINE", "# If we are an end tag", "elif", "tag_type", "==", "'end'", ":", "# Then check to see if the last opened section", "# is the same as us", "try", ":", "last_section", "=", "open_sections", ".", "pop", "(", ")", "except", "IndexError", ":", "raise", "ChevronError", "(", "'Trying to close tag \"{0}\"\\n'", "'Looks like it was not opened.\\n'", "'line {1}'", ".", "format", "(", "tag_key", ",", "_CURRENT_LINE", "+", "1", ")", ")", "if", "tag_key", "!=", "last_section", ":", "# Otherwise we need to complain", "raise", "ChevronError", "(", "'Trying to close tag \"{0}\"\\n'", "'last open tag is \"{1}\"\\n'", "'line {2}'", ".", "format", "(", "tag_key", ",", "last_section", ",", "_CURRENT_LINE", "+", "1", ")", ")", "# Do the second check to see if we're a standalone", "is_standalone", "=", "r_sa_check", "(", "template", ",", "tag_type", ",", "is_standalone", ")", "# Which if we are", "if", "is_standalone", ":", "# Remove the stuff before the newline", "template", "=", "template", ".", "split", "(", "'\\n'", ",", "1", ")", "[", "-", "1", "]", "# Partials need to keep the spaces on their left", "if", "tag_type", "!=", "'partial'", ":", "# But other tags don't", "literal", "=", "literal", ".", "rstrip", "(", "' '", ")", "# Start yielding", "# Ignore literals that are empty", "if", "literal", "!=", "''", ":", "yield", "(", "'literal'", ",", "literal", ")", "# Ignore comments and set delimiters", "if", "tag_type", "not", "in", "[", "'comment'", ",", "'set delimiter?'", "]", ":", "yield", "(", "tag_type", ",", "tag_key", ")", "# If there are any open sections when we're done", "if", "open_sections", ":", "# Then we need to complain", "raise", "ChevronError", "(", "'Unexpected EOF\\n'", "'the tag \"{0}\" was never closed\\n'", "'was opened at line {1}'", ".", "format", "(", "open_sections", "[", "-", "1", "]", ",", "_LAST_TAG_LINE", ")", ")" ]
Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template def_ldel -- The default left delimiter ("{{" by default, as in spec compliant mustache) def_rdel -- The default right delimiter ("}}" by default, as in spec compliant mustache) Returns: A generator of mustache tags in the form of a tuple -- (tag_type, tag_key) Where tag_type is one of: * literal * section * inverted section * end * partial * no escape And tag_key is either the key or in the case of a literal tag, the literal itself.
[ "Tokenize", "a", "mustache", "template" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L126-L254
noahmorrison/chevron
chevron/main.py
cli_main
def cli_main(): """Render mustache templates using json files""" import argparse import os def is_file_or_pipe(arg): if not os.path.exists(arg) or os.path.isdir(arg): parser.error('The file {0} does not exist!'.format(arg)) else: return arg def is_dir(arg): if not os.path.isdir(arg): parser.error('The directory {0} does not exist!'.format(arg)) else: return arg parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--version', action='version', version=version) parser.add_argument('template', help='The mustache file', type=is_file_or_pipe) parser.add_argument('-d', '--data', dest='data', help='The json data file', type=is_file_or_pipe, default={}) parser.add_argument('-p', '--path', dest='partials_path', help='The directory where your partials reside', type=is_dir, default='.') parser.add_argument('-e', '--ext', dest='partials_ext', help='The extension for your mustache\ partials, \'mustache\' by default', default='mustache') parser.add_argument('-l', '--left-delimiter', dest='def_ldel', help='The default left delimiter, "{{" by default.', default='{{') parser.add_argument('-r', '--right-delimiter', dest='def_rdel', help='The default right delimiter, "}}" by default.', default='}}') args = vars(parser.parse_args()) try: sys.stdout.write(main(**args)) sys.stdout.flush() except SyntaxError as e: print('Chevron: syntax error') print(' ' + '\n '.join(e.args[0].split('\n'))) exit(1)
python
def cli_main(): """Render mustache templates using json files""" import argparse import os def is_file_or_pipe(arg): if not os.path.exists(arg) or os.path.isdir(arg): parser.error('The file {0} does not exist!'.format(arg)) else: return arg def is_dir(arg): if not os.path.isdir(arg): parser.error('The directory {0} does not exist!'.format(arg)) else: return arg parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--version', action='version', version=version) parser.add_argument('template', help='The mustache file', type=is_file_or_pipe) parser.add_argument('-d', '--data', dest='data', help='The json data file', type=is_file_or_pipe, default={}) parser.add_argument('-p', '--path', dest='partials_path', help='The directory where your partials reside', type=is_dir, default='.') parser.add_argument('-e', '--ext', dest='partials_ext', help='The extension for your mustache\ partials, \'mustache\' by default', default='mustache') parser.add_argument('-l', '--left-delimiter', dest='def_ldel', help='The default left delimiter, "{{" by default.', default='{{') parser.add_argument('-r', '--right-delimiter', dest='def_rdel', help='The default right delimiter, "}}" by default.', default='}}') args = vars(parser.parse_args()) try: sys.stdout.write(main(**args)) sys.stdout.flush() except SyntaxError as e: print('Chevron: syntax error') print(' ' + '\n '.join(e.args[0].split('\n'))) exit(1)
[ "def", "cli_main", "(", ")", ":", "import", "argparse", "import", "os", "def", "is_file_or_pipe", "(", "arg", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "arg", ")", "or", "os", ".", "path", ".", "isdir", "(", "arg", ")", ":", "parser", ".", "error", "(", "'The file {0} does not exist!'", ".", "format", "(", "arg", ")", ")", "else", ":", "return", "arg", "def", "is_dir", "(", "arg", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "arg", ")", ":", "parser", ".", "error", "(", "'The directory {0} does not exist!'", ".", "format", "(", "arg", ")", ")", "else", ":", "return", "arg", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "version", ")", "parser", ".", "add_argument", "(", "'template'", ",", "help", "=", "'The mustache file'", ",", "type", "=", "is_file_or_pipe", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--data'", ",", "dest", "=", "'data'", ",", "help", "=", "'The json data file'", ",", "type", "=", "is_file_or_pipe", ",", "default", "=", "{", "}", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--path'", ",", "dest", "=", "'partials_path'", ",", "help", "=", "'The directory where your partials reside'", ",", "type", "=", "is_dir", ",", "default", "=", "'.'", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "'--ext'", ",", "dest", "=", "'partials_ext'", ",", "help", "=", "'The extension for your mustache\\\n partials, \\'mustache\\' by default'", ",", "default", "=", "'mustache'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--left-delimiter'", ",", "dest", "=", "'def_ldel'", ",", "help", "=", "'The default left delimiter, \"{{\" by default.'", ",", "default", "=", "'{{'", ")", "parser", ".", "add_argument", "(", "'-r'", ",", "'--right-delimiter'", ",", "dest", "=", "'def_rdel'", ",", "help", "=", "'The default right delimiter, \"}}\" by default.'", ",", "default", "=", "'}}'", ")", "args", "=", "vars", "(", "parser", ".", "parse_args", "(", ")", ")", "try", ":", "sys", ".", "stdout", ".", "write", "(", "main", "(", "*", "*", "args", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "except", "SyntaxError", "as", "e", ":", "print", "(", "'Chevron: syntax error'", ")", "print", "(", "' '", "+", "'\\n '", ".", "join", "(", "e", ".", "args", "[", "0", "]", ".", "split", "(", "'\\n'", ")", ")", ")", "exit", "(", "1", ")" ]
Render mustache templates using json files
[ "Render", "mustache", "templates", "using", "json", "files" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/main.py#L35-L89
noahmorrison/chevron
chevron/renderer.py
_html_escape
def _html_escape(string): """HTML escape all of these " & < >""" html_codes = { '"': '&quot;', '<': '&lt;', '>': '&gt;', } # & must be handled first string = string.replace('&', '&amp;') for char in html_codes: string = string.replace(char, html_codes[char]) return string
python
def _html_escape(string): """HTML escape all of these " & < >""" html_codes = { '"': '&quot;', '<': '&lt;', '>': '&gt;', } # & must be handled first string = string.replace('&', '&amp;') for char in html_codes: string = string.replace(char, html_codes[char]) return string
[ "def", "_html_escape", "(", "string", ")", ":", "html_codes", "=", "{", "'\"'", ":", "'&quot;'", ",", "'<'", ":", "'&lt;'", ",", "'>'", ":", "'&gt;'", ",", "}", "# & must be handled first", "string", "=", "string", ".", "replace", "(", "'&'", ",", "'&amp;'", ")", "for", "char", "in", "html_codes", ":", "string", "=", "string", ".", "replace", "(", "char", ",", "html_codes", "[", "char", "]", ")", "return", "string" ]
HTML escape all of these " & < >
[ "HTML", "escape", "all", "of", "these", "&", "<", ">" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L34-L47
noahmorrison/chevron
chevron/renderer.py
_get_key
def _get_key(key, scopes): """Get a key from the current scope""" # If the key is a dot if key == '.': # Then just return the current scope return scopes[0] # Loop through the scopes for scope in scopes: try: # For every dot seperated key for child in key.split('.'): # Move into the scope try: # Try subscripting (Normal dictionaries) scope = scope[child] except (TypeError, AttributeError): try: # Try the dictionary (Complex types) scope = scope.__dict__[child] except (TypeError, AttributeError): # Try as a list scope = scope[int(child)] # Return an empty string if falsy, with two exceptions # 0 should return 0, and False should return False # While using is for this check is undefined it works and is fast if scope is 0: # noqa: F632 return 0 if scope is False: return False try: # This allows for custom falsy data types # https://github.com/noahmorrison/chevron/issues/35 if scope._CHEVRON_return_scope_when_falsy: return scope except AttributeError: return scope or '' except (AttributeError, KeyError, IndexError, ValueError): # We couldn't find the key in the current scope # We'll try again on the next pass pass # We couldn't find the key in any of the scopes return ''
python
def _get_key(key, scopes): """Get a key from the current scope""" # If the key is a dot if key == '.': # Then just return the current scope return scopes[0] # Loop through the scopes for scope in scopes: try: # For every dot seperated key for child in key.split('.'): # Move into the scope try: # Try subscripting (Normal dictionaries) scope = scope[child] except (TypeError, AttributeError): try: # Try the dictionary (Complex types) scope = scope.__dict__[child] except (TypeError, AttributeError): # Try as a list scope = scope[int(child)] # Return an empty string if falsy, with two exceptions # 0 should return 0, and False should return False # While using is for this check is undefined it works and is fast if scope is 0: # noqa: F632 return 0 if scope is False: return False try: # This allows for custom falsy data types # https://github.com/noahmorrison/chevron/issues/35 if scope._CHEVRON_return_scope_when_falsy: return scope except AttributeError: return scope or '' except (AttributeError, KeyError, IndexError, ValueError): # We couldn't find the key in the current scope # We'll try again on the next pass pass # We couldn't find the key in any of the scopes return ''
[ "def", "_get_key", "(", "key", ",", "scopes", ")", ":", "# If the key is a dot", "if", "key", "==", "'.'", ":", "# Then just return the current scope", "return", "scopes", "[", "0", "]", "# Loop through the scopes", "for", "scope", "in", "scopes", ":", "try", ":", "# For every dot seperated key", "for", "child", "in", "key", ".", "split", "(", "'.'", ")", ":", "# Move into the scope", "try", ":", "# Try subscripting (Normal dictionaries)", "scope", "=", "scope", "[", "child", "]", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "try", ":", "# Try the dictionary (Complex types)", "scope", "=", "scope", ".", "__dict__", "[", "child", "]", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "# Try as a list", "scope", "=", "scope", "[", "int", "(", "child", ")", "]", "# Return an empty string if falsy, with two exceptions", "# 0 should return 0, and False should return False", "# While using is for this check is undefined it works and is fast", "if", "scope", "is", "0", ":", "# noqa: F632", "return", "0", "if", "scope", "is", "False", ":", "return", "False", "try", ":", "# This allows for custom falsy data types", "# https://github.com/noahmorrison/chevron/issues/35", "if", "scope", ".", "_CHEVRON_return_scope_when_falsy", ":", "return", "scope", "except", "AttributeError", ":", "return", "scope", "or", "''", "except", "(", "AttributeError", ",", "KeyError", ",", "IndexError", ",", "ValueError", ")", ":", "# We couldn't find the key in the current scope", "# We'll try again on the next pass", "pass", "# We couldn't find the key in any of the scopes", "return", "''" ]
Get a key from the current scope
[ "Get", "a", "key", "from", "the", "current", "scope" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L50-L96
noahmorrison/chevron
chevron/renderer.py
_get_partial
def _get_partial(name, partials_dict, partials_path, partials_ext): """Load a partial""" try: # Maybe the partial is in the dictionary return partials_dict[name] except KeyError: # Nope... try: # Maybe it's in the file system path_ext = ('.' + partials_ext if partials_ext else '') path = partials_path + '/' + name + path_ext with io.open(path, 'r', encoding='utf-8') as partial: return partial.read() except IOError: # Alright I give up on you return ''
python
def _get_partial(name, partials_dict, partials_path, partials_ext): """Load a partial""" try: # Maybe the partial is in the dictionary return partials_dict[name] except KeyError: # Nope... try: # Maybe it's in the file system path_ext = ('.' + partials_ext if partials_ext else '') path = partials_path + '/' + name + path_ext with io.open(path, 'r', encoding='utf-8') as partial: return partial.read() except IOError: # Alright I give up on you return ''
[ "def", "_get_partial", "(", "name", ",", "partials_dict", ",", "partials_path", ",", "partials_ext", ")", ":", "try", ":", "# Maybe the partial is in the dictionary", "return", "partials_dict", "[", "name", "]", "except", "KeyError", ":", "# Nope...", "try", ":", "# Maybe it's in the file system", "path_ext", "=", "(", "'.'", "+", "partials_ext", "if", "partials_ext", "else", "''", ")", "path", "=", "partials_path", "+", "'/'", "+", "name", "+", "path_ext", "with", "io", ".", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "partial", ":", "return", "partial", ".", "read", "(", ")", "except", "IOError", ":", "# Alright I give up on you", "return", "''" ]
Load a partial
[ "Load", "a", "partial" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L99-L115
noahmorrison/chevron
chevron/renderer.py
render
def render(template='', data={}, partials_path='.', partials_ext='mustache', partials_dict={}, padding='', def_ldel='{{', def_rdel='}}', scopes=None): """Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷ ├─╼ main.py ├─╼ main.ms └─┮ partials └── part.ms then main.py would make the following call: render(open('main.ms', 'r'), {...}, 'partials', 'ms') Arguments: template -- A file-like object or a string containing the template data -- A python dictionary with your data scope partials_path -- The path to where your partials are stored (defaults to '.') partials_ext -- The extension that you want the parser to look for (defaults to 'mustache') partials_dict -- A python dictionary which will be search for partials before the filesystem is. {'include': 'foo'} is the same as a file called include.mustache (defaults to {}) padding -- This is for padding partials, and shouldn't be used (but can be if you really want to) def_ldel -- The default left delimiter ("{{" by default, as in spec compliant mustache) def_rdel -- The default right delimiter ("}}" by default, as in spec compliant mustache) scopes -- The list of scopes that get_key will look through Returns: A string containing the rendered template. """ # If the template is a seqeuence but not derived from a string if isinstance(template, Sequence) and \ not isinstance(template, string_type): # Then we don't need to tokenize it # But it does need to be a generator tokens = (token for token in template) else: if template in g_token_cache: tokens = (token for token in g_token_cache[template]) else: # Otherwise make a generator tokens = tokenize(template, def_ldel, def_rdel) output = unicode('', 'utf-8') if scopes is None: scopes = [data] # Run through the tokens for tag, key in tokens: # Set the current scope current_scope = scopes[0] # If we're an end tag if tag == 'end': # Pop out of the latest scope del scopes[0] # If the current scope is falsy and not the only scope elif not current_scope and len(scopes) != 1: if tag in ['section', 'inverted section']: # Set the most recent scope to a falsy value # (I heard False is a good one) scopes.insert(0, False) # If we're a literal tag elif tag == 'literal': # Add padding to the key and add it to the output if not isinstance(key, unicode_type): # python 2 key = unicode(key, 'utf-8') output += key.replace('\n', '\n' + padding) # If we're a variable tag elif tag == 'variable': # Add the html escaped key to the output thing = _get_key(key, scopes) if thing is True and key == '.': # if we've coerced into a boolean by accident # (inverted tags do this) # then get the un-coerced object (next in the stack) thing = scopes[1] if not isinstance(thing, unicode_type): thing = unicode(str(thing), 'utf-8') output += _html_escape(thing) # If we're a no html escape tag elif tag == 'no escape': # Just lookup the key and add it thing = _get_key(key, scopes) if not isinstance(thing, unicode_type): thing = unicode(str(thing), 'utf-8') output += thing # If we're a section tag elif tag == 'section': # Get the sections scope scope = _get_key(key, scopes) # If the scope is a callable (as described in # https://mustache.github.io/mustache.5.html) if isinstance(scope, Callable): # Generate template text from tags text = unicode('', 'utf-8') tags = [] for tag in tokens: if tag == ('end', key): break tags.append(tag) tag_type, tag_key = tag if tag_type == 'literal': text += tag_key elif tag_type == 'no escape': text += "%s& %s %s" % (def_ldel, tag_key, def_rdel) else: text += "%s%s %s%s" % (def_ldel, { 'commment': '!', 'section': '#', 'inverted section': '^', 'end': '/', 'partial': '>', 'set delimiter': '=', 'no escape': '&', 'variable': '' }[tag_type], tag_key, def_rdel) g_token_cache[text] = tags rend = scope(text, lambda template, data=None: render(template, data={}, partials_path=partials_path, partials_ext=partials_ext, partials_dict=partials_dict, padding=padding, def_ldel=def_ldel, def_rdel=def_rdel, scopes=data and [data]+scopes or scopes)) if python3: output += rend else: # python 2 output += rend.decode('utf-8') # If the scope is a sequence, an iterator or generator but not # derived from a string elif isinstance(scope, (Sequence, Iterator)) and \ not isinstance(scope, string_type): # Then we need to do some looping # Gather up all the tags inside the section # (And don't be tricked by nested end tags with the same key) # TODO: This feels like it still has edge cases, no? tags = [] tags_with_same_key = 0 for tag in tokens: if tag == ('section', key): tags_with_same_key += 1 if tag == ('end', key): tags_with_same_key -= 1 if tags_with_same_key < 0: break tags.append(tag) # For every item in the scope for thing in scope: # Append it as the most recent scope and render new_scope = [thing] + scopes rend = render(template=tags, scopes=new_scope, partials_path=partials_path, partials_ext=partials_ext, partials_dict=partials_dict, def_ldel=def_ldel, def_rdel=def_rdel) if python3: output += rend else: # python 2 output += rend.decode('utf-8') else: # Otherwise we're just a scope section scopes.insert(0, scope) # If we're an inverted section elif tag == 'inverted section': # Add the flipped scope to the scopes scope = _get_key(key, scopes) scopes.insert(0, not scope) # If we're a partial elif tag == 'partial': # Load the partial partial = _get_partial(key, partials_dict, partials_path, partials_ext) # Find what to pad the partial with left = output.split('\n')[-1] part_padding = padding if left.isspace(): part_padding += left # Render the partial part_out = render(template=partial, partials_path=partials_path, partials_ext=partials_ext, partials_dict=partials_dict, def_ldel=def_ldel, def_rdel=def_rdel, padding=part_padding, scopes=scopes) # If the partial was indented if left.isspace(): # then remove the spaces from the end part_out = part_out.rstrip(' \t') # Add the partials output to the ouput if python3: output += part_out else: # python 2 output += part_out.decode('utf-8') if python3: return output else: # python 2 return output.encode('utf-8')
python
def render(template='', data={}, partials_path='.', partials_ext='mustache', partials_dict={}, padding='', def_ldel='{{', def_rdel='}}', scopes=None): """Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷ ├─╼ main.py ├─╼ main.ms └─┮ partials └── part.ms then main.py would make the following call: render(open('main.ms', 'r'), {...}, 'partials', 'ms') Arguments: template -- A file-like object or a string containing the template data -- A python dictionary with your data scope partials_path -- The path to where your partials are stored (defaults to '.') partials_ext -- The extension that you want the parser to look for (defaults to 'mustache') partials_dict -- A python dictionary which will be search for partials before the filesystem is. {'include': 'foo'} is the same as a file called include.mustache (defaults to {}) padding -- This is for padding partials, and shouldn't be used (but can be if you really want to) def_ldel -- The default left delimiter ("{{" by default, as in spec compliant mustache) def_rdel -- The default right delimiter ("}}" by default, as in spec compliant mustache) scopes -- The list of scopes that get_key will look through Returns: A string containing the rendered template. """ # If the template is a seqeuence but not derived from a string if isinstance(template, Sequence) and \ not isinstance(template, string_type): # Then we don't need to tokenize it # But it does need to be a generator tokens = (token for token in template) else: if template in g_token_cache: tokens = (token for token in g_token_cache[template]) else: # Otherwise make a generator tokens = tokenize(template, def_ldel, def_rdel) output = unicode('', 'utf-8') if scopes is None: scopes = [data] # Run through the tokens for tag, key in tokens: # Set the current scope current_scope = scopes[0] # If we're an end tag if tag == 'end': # Pop out of the latest scope del scopes[0] # If the current scope is falsy and not the only scope elif not current_scope and len(scopes) != 1: if tag in ['section', 'inverted section']: # Set the most recent scope to a falsy value # (I heard False is a good one) scopes.insert(0, False) # If we're a literal tag elif tag == 'literal': # Add padding to the key and add it to the output if not isinstance(key, unicode_type): # python 2 key = unicode(key, 'utf-8') output += key.replace('\n', '\n' + padding) # If we're a variable tag elif tag == 'variable': # Add the html escaped key to the output thing = _get_key(key, scopes) if thing is True and key == '.': # if we've coerced into a boolean by accident # (inverted tags do this) # then get the un-coerced object (next in the stack) thing = scopes[1] if not isinstance(thing, unicode_type): thing = unicode(str(thing), 'utf-8') output += _html_escape(thing) # If we're a no html escape tag elif tag == 'no escape': # Just lookup the key and add it thing = _get_key(key, scopes) if not isinstance(thing, unicode_type): thing = unicode(str(thing), 'utf-8') output += thing # If we're a section tag elif tag == 'section': # Get the sections scope scope = _get_key(key, scopes) # If the scope is a callable (as described in # https://mustache.github.io/mustache.5.html) if isinstance(scope, Callable): # Generate template text from tags text = unicode('', 'utf-8') tags = [] for tag in tokens: if tag == ('end', key): break tags.append(tag) tag_type, tag_key = tag if tag_type == 'literal': text += tag_key elif tag_type == 'no escape': text += "%s& %s %s" % (def_ldel, tag_key, def_rdel) else: text += "%s%s %s%s" % (def_ldel, { 'commment': '!', 'section': '#', 'inverted section': '^', 'end': '/', 'partial': '>', 'set delimiter': '=', 'no escape': '&', 'variable': '' }[tag_type], tag_key, def_rdel) g_token_cache[text] = tags rend = scope(text, lambda template, data=None: render(template, data={}, partials_path=partials_path, partials_ext=partials_ext, partials_dict=partials_dict, padding=padding, def_ldel=def_ldel, def_rdel=def_rdel, scopes=data and [data]+scopes or scopes)) if python3: output += rend else: # python 2 output += rend.decode('utf-8') # If the scope is a sequence, an iterator or generator but not # derived from a string elif isinstance(scope, (Sequence, Iterator)) and \ not isinstance(scope, string_type): # Then we need to do some looping # Gather up all the tags inside the section # (And don't be tricked by nested end tags with the same key) # TODO: This feels like it still has edge cases, no? tags = [] tags_with_same_key = 0 for tag in tokens: if tag == ('section', key): tags_with_same_key += 1 if tag == ('end', key): tags_with_same_key -= 1 if tags_with_same_key < 0: break tags.append(tag) # For every item in the scope for thing in scope: # Append it as the most recent scope and render new_scope = [thing] + scopes rend = render(template=tags, scopes=new_scope, partials_path=partials_path, partials_ext=partials_ext, partials_dict=partials_dict, def_ldel=def_ldel, def_rdel=def_rdel) if python3: output += rend else: # python 2 output += rend.decode('utf-8') else: # Otherwise we're just a scope section scopes.insert(0, scope) # If we're an inverted section elif tag == 'inverted section': # Add the flipped scope to the scopes scope = _get_key(key, scopes) scopes.insert(0, not scope) # If we're a partial elif tag == 'partial': # Load the partial partial = _get_partial(key, partials_dict, partials_path, partials_ext) # Find what to pad the partial with left = output.split('\n')[-1] part_padding = padding if left.isspace(): part_padding += left # Render the partial part_out = render(template=partial, partials_path=partials_path, partials_ext=partials_ext, partials_dict=partials_dict, def_ldel=def_ldel, def_rdel=def_rdel, padding=part_padding, scopes=scopes) # If the partial was indented if left.isspace(): # then remove the spaces from the end part_out = part_out.rstrip(' \t') # Add the partials output to the ouput if python3: output += part_out else: # python 2 output += part_out.decode('utf-8') if python3: return output else: # python 2 return output.encode('utf-8')
[ "def", "render", "(", "template", "=", "''", ",", "data", "=", "{", "}", ",", "partials_path", "=", "'.'", ",", "partials_ext", "=", "'mustache'", ",", "partials_dict", "=", "{", "}", ",", "padding", "=", "''", ",", "def_ldel", "=", "'{{'", ",", "def_rdel", "=", "'}}'", ",", "scopes", "=", "None", ")", ":", "# If the template is a seqeuence but not derived from a string", "if", "isinstance", "(", "template", ",", "Sequence", ")", "and", "not", "isinstance", "(", "template", ",", "string_type", ")", ":", "# Then we don't need to tokenize it", "# But it does need to be a generator", "tokens", "=", "(", "token", "for", "token", "in", "template", ")", "else", ":", "if", "template", "in", "g_token_cache", ":", "tokens", "=", "(", "token", "for", "token", "in", "g_token_cache", "[", "template", "]", ")", "else", ":", "# Otherwise make a generator", "tokens", "=", "tokenize", "(", "template", ",", "def_ldel", ",", "def_rdel", ")", "output", "=", "unicode", "(", "''", ",", "'utf-8'", ")", "if", "scopes", "is", "None", ":", "scopes", "=", "[", "data", "]", "# Run through the tokens", "for", "tag", ",", "key", "in", "tokens", ":", "# Set the current scope", "current_scope", "=", "scopes", "[", "0", "]", "# If we're an end tag", "if", "tag", "==", "'end'", ":", "# Pop out of the latest scope", "del", "scopes", "[", "0", "]", "# If the current scope is falsy and not the only scope", "elif", "not", "current_scope", "and", "len", "(", "scopes", ")", "!=", "1", ":", "if", "tag", "in", "[", "'section'", ",", "'inverted section'", "]", ":", "# Set the most recent scope to a falsy value", "# (I heard False is a good one)", "scopes", ".", "insert", "(", "0", ",", "False", ")", "# If we're a literal tag", "elif", "tag", "==", "'literal'", ":", "# Add padding to the key and add it to the output", "if", "not", "isinstance", "(", "key", ",", "unicode_type", ")", ":", "# python 2", "key", "=", "unicode", "(", "key", ",", "'utf-8'", ")", "output", "+=", "key", ".", "replace", "(", "'\\n'", ",", "'\\n'", "+", "padding", ")", "# If we're a variable tag", "elif", "tag", "==", "'variable'", ":", "# Add the html escaped key to the output", "thing", "=", "_get_key", "(", "key", ",", "scopes", ")", "if", "thing", "is", "True", "and", "key", "==", "'.'", ":", "# if we've coerced into a boolean by accident", "# (inverted tags do this)", "# then get the un-coerced object (next in the stack)", "thing", "=", "scopes", "[", "1", "]", "if", "not", "isinstance", "(", "thing", ",", "unicode_type", ")", ":", "thing", "=", "unicode", "(", "str", "(", "thing", ")", ",", "'utf-8'", ")", "output", "+=", "_html_escape", "(", "thing", ")", "# If we're a no html escape tag", "elif", "tag", "==", "'no escape'", ":", "# Just lookup the key and add it", "thing", "=", "_get_key", "(", "key", ",", "scopes", ")", "if", "not", "isinstance", "(", "thing", ",", "unicode_type", ")", ":", "thing", "=", "unicode", "(", "str", "(", "thing", ")", ",", "'utf-8'", ")", "output", "+=", "thing", "# If we're a section tag", "elif", "tag", "==", "'section'", ":", "# Get the sections scope", "scope", "=", "_get_key", "(", "key", ",", "scopes", ")", "# If the scope is a callable (as described in", "# https://mustache.github.io/mustache.5.html)", "if", "isinstance", "(", "scope", ",", "Callable", ")", ":", "# Generate template text from tags", "text", "=", "unicode", "(", "''", ",", "'utf-8'", ")", "tags", "=", "[", "]", "for", "tag", "in", "tokens", ":", "if", "tag", "==", "(", "'end'", ",", "key", ")", ":", "break", "tags", ".", "append", "(", "tag", ")", "tag_type", ",", "tag_key", "=", "tag", "if", "tag_type", "==", "'literal'", ":", "text", "+=", "tag_key", "elif", "tag_type", "==", "'no escape'", ":", "text", "+=", "\"%s& %s %s\"", "%", "(", "def_ldel", ",", "tag_key", ",", "def_rdel", ")", "else", ":", "text", "+=", "\"%s%s %s%s\"", "%", "(", "def_ldel", ",", "{", "'commment'", ":", "'!'", ",", "'section'", ":", "'#'", ",", "'inverted section'", ":", "'^'", ",", "'end'", ":", "'/'", ",", "'partial'", ":", "'>'", ",", "'set delimiter'", ":", "'='", ",", "'no escape'", ":", "'&'", ",", "'variable'", ":", "''", "}", "[", "tag_type", "]", ",", "tag_key", ",", "def_rdel", ")", "g_token_cache", "[", "text", "]", "=", "tags", "rend", "=", "scope", "(", "text", ",", "lambda", "template", ",", "data", "=", "None", ":", "render", "(", "template", ",", "data", "=", "{", "}", ",", "partials_path", "=", "partials_path", ",", "partials_ext", "=", "partials_ext", ",", "partials_dict", "=", "partials_dict", ",", "padding", "=", "padding", ",", "def_ldel", "=", "def_ldel", ",", "def_rdel", "=", "def_rdel", ",", "scopes", "=", "data", "and", "[", "data", "]", "+", "scopes", "or", "scopes", ")", ")", "if", "python3", ":", "output", "+=", "rend", "else", ":", "# python 2", "output", "+=", "rend", ".", "decode", "(", "'utf-8'", ")", "# If the scope is a sequence, an iterator or generator but not", "# derived from a string", "elif", "isinstance", "(", "scope", ",", "(", "Sequence", ",", "Iterator", ")", ")", "and", "not", "isinstance", "(", "scope", ",", "string_type", ")", ":", "# Then we need to do some looping", "# Gather up all the tags inside the section", "# (And don't be tricked by nested end tags with the same key)", "# TODO: This feels like it still has edge cases, no?", "tags", "=", "[", "]", "tags_with_same_key", "=", "0", "for", "tag", "in", "tokens", ":", "if", "tag", "==", "(", "'section'", ",", "key", ")", ":", "tags_with_same_key", "+=", "1", "if", "tag", "==", "(", "'end'", ",", "key", ")", ":", "tags_with_same_key", "-=", "1", "if", "tags_with_same_key", "<", "0", ":", "break", "tags", ".", "append", "(", "tag", ")", "# For every item in the scope", "for", "thing", "in", "scope", ":", "# Append it as the most recent scope and render", "new_scope", "=", "[", "thing", "]", "+", "scopes", "rend", "=", "render", "(", "template", "=", "tags", ",", "scopes", "=", "new_scope", ",", "partials_path", "=", "partials_path", ",", "partials_ext", "=", "partials_ext", ",", "partials_dict", "=", "partials_dict", ",", "def_ldel", "=", "def_ldel", ",", "def_rdel", "=", "def_rdel", ")", "if", "python3", ":", "output", "+=", "rend", "else", ":", "# python 2", "output", "+=", "rend", ".", "decode", "(", "'utf-8'", ")", "else", ":", "# Otherwise we're just a scope section", "scopes", ".", "insert", "(", "0", ",", "scope", ")", "# If we're an inverted section", "elif", "tag", "==", "'inverted section'", ":", "# Add the flipped scope to the scopes", "scope", "=", "_get_key", "(", "key", ",", "scopes", ")", "scopes", ".", "insert", "(", "0", ",", "not", "scope", ")", "# If we're a partial", "elif", "tag", "==", "'partial'", ":", "# Load the partial", "partial", "=", "_get_partial", "(", "key", ",", "partials_dict", ",", "partials_path", ",", "partials_ext", ")", "# Find what to pad the partial with", "left", "=", "output", ".", "split", "(", "'\\n'", ")", "[", "-", "1", "]", "part_padding", "=", "padding", "if", "left", ".", "isspace", "(", ")", ":", "part_padding", "+=", "left", "# Render the partial", "part_out", "=", "render", "(", "template", "=", "partial", ",", "partials_path", "=", "partials_path", ",", "partials_ext", "=", "partials_ext", ",", "partials_dict", "=", "partials_dict", ",", "def_ldel", "=", "def_ldel", ",", "def_rdel", "=", "def_rdel", ",", "padding", "=", "part_padding", ",", "scopes", "=", "scopes", ")", "# If the partial was indented", "if", "left", ".", "isspace", "(", ")", ":", "# then remove the spaces from the end", "part_out", "=", "part_out", ".", "rstrip", "(", "' \\t'", ")", "# Add the partials output to the ouput", "if", "python3", ":", "output", "+=", "part_out", "else", ":", "# python 2", "output", "+=", "part_out", ".", "decode", "(", "'utf-8'", ")", "if", "python3", ":", "return", "output", "else", ":", "# python 2", "return", "output", ".", "encode", "(", "'utf-8'", ")" ]
Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷ ├─╼ main.py ├─╼ main.ms └─┮ partials └── part.ms then main.py would make the following call: render(open('main.ms', 'r'), {...}, 'partials', 'ms') Arguments: template -- A file-like object or a string containing the template data -- A python dictionary with your data scope partials_path -- The path to where your partials are stored (defaults to '.') partials_ext -- The extension that you want the parser to look for (defaults to 'mustache') partials_dict -- A python dictionary which will be search for partials before the filesystem is. {'include': 'foo'} is the same as a file called include.mustache (defaults to {}) padding -- This is for padding partials, and shouldn't be used (but can be if you really want to) def_ldel -- The default left delimiter ("{{" by default, as in spec compliant mustache) def_rdel -- The default right delimiter ("}}" by default, as in spec compliant mustache) scopes -- The list of scopes that get_key will look through Returns: A string containing the rendered template.
[ "Render", "a", "mustache", "template", "." ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L124-L367
tapanpandita/pocket
pocket.py
Pocket.bulk_add
def bulk_add( self, item_id, ref_id=None, tags=None, time=None, title=None, url=None, wait=True ): ''' Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add '''
python
def bulk_add( self, item_id, ref_id=None, tags=None, time=None, title=None, url=None, wait=True ): ''' Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add '''
[ "def", "bulk_add", "(", "self", ",", "item_id", ",", "ref_id", "=", "None", ",", "tags", "=", "None", ",", "time", "=", "None", ",", "title", "=", "None", ",", "url", "=", "None", ",", "wait", "=", "True", ")", ":" ]
Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add
[ "Add", "a", "new", "item", "to", "the", "user", "s", "list", "http", ":", "//", "getpocket", ".", "com", "/", "developer", "/", "docs", "/", "v3", "/", "modify#action_add" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L190-L198
tapanpandita/pocket
pocket.py
Pocket.commit
def commit(self): ''' This method executes the bulk query, flushes stored queries and returns the response ''' url = self.api_endpoints['send'] payload = { 'actions': self._bulk_query, } payload.update(self._payload) self._bulk_query = [] return self._make_request( url, json.dumps(payload), headers={'content-type': 'application/json'}, )
python
def commit(self): ''' This method executes the bulk query, flushes stored queries and returns the response ''' url = self.api_endpoints['send'] payload = { 'actions': self._bulk_query, } payload.update(self._payload) self._bulk_query = [] return self._make_request( url, json.dumps(payload), headers={'content-type': 'application/json'}, )
[ "def", "commit", "(", "self", ")", ":", "url", "=", "self", ".", "api_endpoints", "[", "'send'", "]", "payload", "=", "{", "'actions'", ":", "self", ".", "_bulk_query", ",", "}", "payload", ".", "update", "(", "self", ".", "_payload", ")", "self", ".", "_bulk_query", "=", "[", "]", "return", "self", ".", "_make_request", "(", "url", ",", "json", ".", "dumps", "(", "payload", ")", ",", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", ",", ")" ]
This method executes the bulk query, flushes stored queries and returns the response
[ "This", "method", "executes", "the", "bulk", "query", "flushes", "stored", "queries", "and", "returns", "the", "response" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L280-L297
tapanpandita/pocket
pocket.py
Pocket.get_request_token
def get_request_token( cls, consumer_key, redirect_uri='http://example.com/', state=None ): ''' Returns the request token that can be used to fetch the access token ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/oauth/request' payload = { 'consumer_key': consumer_key, 'redirect_uri': redirect_uri, } if state: payload['state'] = state return cls._make_request(url, payload, headers)[0]['code']
python
def get_request_token( cls, consumer_key, redirect_uri='http://example.com/', state=None ): ''' Returns the request token that can be used to fetch the access token ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/oauth/request' payload = { 'consumer_key': consumer_key, 'redirect_uri': redirect_uri, } if state: payload['state'] = state return cls._make_request(url, payload, headers)[0]['code']
[ "def", "get_request_token", "(", "cls", ",", "consumer_key", ",", "redirect_uri", "=", "'http://example.com/'", ",", "state", "=", "None", ")", ":", "headers", "=", "{", "'X-Accept'", ":", "'application/json'", ",", "}", "url", "=", "'https://getpocket.com/v3/oauth/request'", "payload", "=", "{", "'consumer_key'", ":", "consumer_key", ",", "'redirect_uri'", ":", "redirect_uri", ",", "}", "if", "state", ":", "payload", "[", "'state'", "]", "=", "state", "return", "cls", ".", "_make_request", "(", "url", ",", "payload", ",", "headers", ")", "[", "0", "]", "[", "'code'", "]" ]
Returns the request token that can be used to fetch the access token
[ "Returns", "the", "request", "token", "that", "can", "be", "used", "to", "fetch", "the", "access", "token" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L300-L319
tapanpandita/pocket
pocket.py
Pocket.get_credentials
def get_credentials(cls, consumer_key, code): ''' Fetches access token from using the request token and consumer key ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/oauth/authorize' payload = { 'consumer_key': consumer_key, 'code': code, } return cls._make_request(url, payload, headers)[0]
python
def get_credentials(cls, consumer_key, code): ''' Fetches access token from using the request token and consumer key ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/oauth/authorize' payload = { 'consumer_key': consumer_key, 'code': code, } return cls._make_request(url, payload, headers)[0]
[ "def", "get_credentials", "(", "cls", ",", "consumer_key", ",", "code", ")", ":", "headers", "=", "{", "'X-Accept'", ":", "'application/json'", ",", "}", "url", "=", "'https://getpocket.com/v3/oauth/authorize'", "payload", "=", "{", "'consumer_key'", ":", "consumer_key", ",", "'code'", ":", "code", ",", "}", "return", "cls", ".", "_make_request", "(", "url", ",", "payload", ",", "headers", ")", "[", "0", "]" ]
Fetches access token from using the request token and consumer key
[ "Fetches", "access", "token", "from", "using", "the", "request", "token", "and", "consumer", "key" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L322-L336
tapanpandita/pocket
pocket.py
Pocket.auth
def auth( cls, consumer_key, redirect_uri='http://example.com/', state=None, ): ''' This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/authentication ''' code = cls.get_request_token(consumer_key, redirect_uri, state) auth_url = 'https://getpocket.com/auth/authorize?request_token='\ '%s&redirect_uri=%s' % (code, redirect_uri) raw_input( 'Please open %s in your browser to authorize the app and ' 'press enter:' % auth_url ) return cls.get_access_token(consumer_key, code)
python
def auth( cls, consumer_key, redirect_uri='http://example.com/', state=None, ): ''' This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/authentication ''' code = cls.get_request_token(consumer_key, redirect_uri, state) auth_url = 'https://getpocket.com/auth/authorize?request_token='\ '%s&redirect_uri=%s' % (code, redirect_uri) raw_input( 'Please open %s in your browser to authorize the app and ' 'press enter:' % auth_url ) return cls.get_access_token(consumer_key, code)
[ "def", "auth", "(", "cls", ",", "consumer_key", ",", "redirect_uri", "=", "'http://example.com/'", ",", "state", "=", "None", ",", ")", ":", "code", "=", "cls", ".", "get_request_token", "(", "consumer_key", ",", "redirect_uri", ",", "state", ")", "auth_url", "=", "'https://getpocket.com/auth/authorize?request_token='", "'%s&redirect_uri=%s'", "%", "(", "code", ",", "redirect_uri", ")", "raw_input", "(", "'Please open %s in your browser to authorize the app and '", "'press enter:'", "%", "auth_url", ")", "return", "cls", ".", "get_access_token", "(", "consumer_key", ",", "code", ")" ]
This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/authentication
[ "This", "is", "a", "test", "method", "for", "verifying", "if", "oauth", "worked", "http", ":", "//", "getpocket", ".", "com", "/", "developer", "/", "docs", "/", "authentication" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L349-L366
adewes/blitzdb
blitzdb/backends/sql/relations.py
ManyToManyProxy.remove
def remove(self,obj): """ Remove an object from the relation """ relationship_table = self.params['relationship_table'] with self.obj.backend.transaction(implicit = True): condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk, relationship_table.c[self.params['pk_field_name']] == self.obj.pk) self.obj.backend.connection.execute(delete(relationship_table).where(condition)) self._queryset = None
python
def remove(self,obj): """ Remove an object from the relation """ relationship_table = self.params['relationship_table'] with self.obj.backend.transaction(implicit = True): condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk, relationship_table.c[self.params['pk_field_name']] == self.obj.pk) self.obj.backend.connection.execute(delete(relationship_table).where(condition)) self._queryset = None
[ "def", "remove", "(", "self", ",", "obj", ")", ":", "relationship_table", "=", "self", ".", "params", "[", "'relationship_table'", "]", "with", "self", ".", "obj", ".", "backend", ".", "transaction", "(", "implicit", "=", "True", ")", ":", "condition", "=", "and_", "(", "relationship_table", ".", "c", "[", "self", ".", "params", "[", "'related_pk_field_name'", "]", "]", "==", "obj", ".", "pk", ",", "relationship_table", ".", "c", "[", "self", ".", "params", "[", "'pk_field_name'", "]", "]", "==", "self", ".", "obj", ".", "pk", ")", "self", ".", "obj", ".", "backend", ".", "connection", ".", "execute", "(", "delete", "(", "relationship_table", ")", ".", "where", "(", "condition", ")", ")", "self", ".", "_queryset", "=", "None" ]
Remove an object from the relation
[ "Remove", "an", "object", "from", "the", "relation" ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/sql/relations.py#L123-L132
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.begin
def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, store in self.stores.items(): store.begin() indexes = self.indexes[collection] for index in indexes.values(): index.begin()
python
def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, store in self.stores.items(): store.begin() indexes = self.indexes[collection] for index in indexes.values(): index.begin()
[ "def", "begin", "(", "self", ")", ":", "if", "self", ".", "in_transaction", ":", "# we're already in a transaction...", "if", "self", ".", "_auto_transaction", ":", "self", ".", "_auto_transaction", "=", "False", "return", "self", ".", "commit", "(", ")", "self", ".", "in_transaction", "=", "True", "for", "collection", ",", "store", "in", "self", ".", "stores", ".", "items", "(", ")", ":", "store", ".", "begin", "(", ")", "indexes", "=", "self", ".", "indexes", "[", "collection", "]", "for", "index", "in", "indexes", ".", "values", "(", ")", ":", "index", ".", "begin", "(", ")" ]
Start a new transaction.
[ "Start", "a", "new", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L113-L125
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.rollback
def rollback(self, transaction = None): """Roll back a transaction.""" if not self.in_transaction: raise NotInTransaction for collection, store in self.stores.items(): store.rollback() indexes = self.indexes[collection] indexes_to_rebuild = [] for key, index in indexes.items(): try: index.rollback() except NotInTransaction: # this index is "dirty" and needs to be rebuilt # (probably it has been created within a transaction) indexes_to_rebuild.append(key) if indexes_to_rebuild: self.rebuild_indexes(collection, indexes_to_rebuild) self.in_transaction = False
python
def rollback(self, transaction = None): """Roll back a transaction.""" if not self.in_transaction: raise NotInTransaction for collection, store in self.stores.items(): store.rollback() indexes = self.indexes[collection] indexes_to_rebuild = [] for key, index in indexes.items(): try: index.rollback() except NotInTransaction: # this index is "dirty" and needs to be rebuilt # (probably it has been created within a transaction) indexes_to_rebuild.append(key) if indexes_to_rebuild: self.rebuild_indexes(collection, indexes_to_rebuild) self.in_transaction = False
[ "def", "rollback", "(", "self", ",", "transaction", "=", "None", ")", ":", "if", "not", "self", ".", "in_transaction", ":", "raise", "NotInTransaction", "for", "collection", ",", "store", "in", "self", ".", "stores", ".", "items", "(", ")", ":", "store", ".", "rollback", "(", ")", "indexes", "=", "self", ".", "indexes", "[", "collection", "]", "indexes_to_rebuild", "=", "[", "]", "for", "key", ",", "index", "in", "indexes", ".", "items", "(", ")", ":", "try", ":", "index", ".", "rollback", "(", ")", "except", "NotInTransaction", ":", "# this index is \"dirty\" and needs to be rebuilt", "# (probably it has been created within a transaction)", "indexes_to_rebuild", ".", "append", "(", "key", ")", "if", "indexes_to_rebuild", ":", "self", ".", "rebuild_indexes", "(", "collection", ",", "indexes_to_rebuild", ")", "self", ".", "in_transaction", "=", "False" ]
Roll back a transaction.
[ "Roll", "back", "a", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L143-L160
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.commit
def commit(self,transaction = None): """Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database indexes to be written to disk. """ for collection in self.collections: store = self.get_collection_store(collection) store.commit() indexes = self.get_collection_indexes(collection) for index in indexes.values(): index.commit() self.in_transaction = False self.begin()
python
def commit(self,transaction = None): """Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database indexes to be written to disk. """ for collection in self.collections: store = self.get_collection_store(collection) store.commit() indexes = self.get_collection_indexes(collection) for index in indexes.values(): index.commit() self.in_transaction = False self.begin()
[ "def", "commit", "(", "self", ",", "transaction", "=", "None", ")", ":", "for", "collection", "in", "self", ".", "collections", ":", "store", "=", "self", ".", "get_collection_store", "(", "collection", ")", "store", ".", "commit", "(", ")", "indexes", "=", "self", ".", "get_collection_indexes", "(", "collection", ")", "for", "index", "in", "indexes", ".", "values", "(", ")", ":", "index", ".", "commit", "(", ")", "self", ".", "in_transaction", "=", "False", "self", ".", "begin", "(", ")" ]
Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database indexes to be written to disk.
[ "Commit", "all", "pending", "transactions", "to", "the", "database", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L162-L179
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.create_index
def create_index(self, cls_or_collection, params=None, fields=None, ephemeral=False, unique=False): """Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an index :param params: The parameters of the index :param ephemeral: Whether to create a persistent or an ephemeral index :param unique: Whether the indexed field(s) must be unique `params` expects either a dictionary of parameters or a string value. In the latter case, it will interpret the string as the name of the key for which an index is to be created. If `ephemeral = True`, the index will be created only in memory and will not be written to disk when :py:meth:`.commit` is called. This is useful for optimizing query performance. ..notice:: By default, BlitzDB will create ephemeral indexes for all keys over which you perform queries, so after you've run a query on a given key for the first time, the second run will usually be much faster. **Specifying keys** Keys can be specified just like in MongoDB, using a dot ('.') to specify nested keys. .. code-block:: python actor = Actor({'name' : 'Charlie Chaplin', 'foo' : {'value' : 'bar'}}) If you want to create an index on `actor['foo']['value']` , you can just say .. code-block:: python backend.create_index(Actor,'foo.value') .. warning:: Transcendental indexes (i.e. indexes transcending the boundaries of referenced objects) are currently not supported by Blitz, which means you can't create an index on an attribute value of a document that is embedded in another document. """ if params: return self.create_indexes(cls_or_collection, [params], ephemeral=ephemeral, unique=unique) elif fields: params = [] if len(fields.items()) > 1: raise ValueError("File backend currently does not support multi-key indexes, sorry :/") return self.create_indexes(cls_or_collection, [{'key': list(fields.keys())[0]}], ephemeral=ephemeral, unique=unique) else: raise AttributeError('You must either specify params or fields!')
python
def create_index(self, cls_or_collection, params=None, fields=None, ephemeral=False, unique=False): """Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an index :param params: The parameters of the index :param ephemeral: Whether to create a persistent or an ephemeral index :param unique: Whether the indexed field(s) must be unique `params` expects either a dictionary of parameters or a string value. In the latter case, it will interpret the string as the name of the key for which an index is to be created. If `ephemeral = True`, the index will be created only in memory and will not be written to disk when :py:meth:`.commit` is called. This is useful for optimizing query performance. ..notice:: By default, BlitzDB will create ephemeral indexes for all keys over which you perform queries, so after you've run a query on a given key for the first time, the second run will usually be much faster. **Specifying keys** Keys can be specified just like in MongoDB, using a dot ('.') to specify nested keys. .. code-block:: python actor = Actor({'name' : 'Charlie Chaplin', 'foo' : {'value' : 'bar'}}) If you want to create an index on `actor['foo']['value']` , you can just say .. code-block:: python backend.create_index(Actor,'foo.value') .. warning:: Transcendental indexes (i.e. indexes transcending the boundaries of referenced objects) are currently not supported by Blitz, which means you can't create an index on an attribute value of a document that is embedded in another document. """ if params: return self.create_indexes(cls_or_collection, [params], ephemeral=ephemeral, unique=unique) elif fields: params = [] if len(fields.items()) > 1: raise ValueError("File backend currently does not support multi-key indexes, sorry :/") return self.create_indexes(cls_or_collection, [{'key': list(fields.keys())[0]}], ephemeral=ephemeral, unique=unique) else: raise AttributeError('You must either specify params or fields!')
[ "def", "create_index", "(", "self", ",", "cls_or_collection", ",", "params", "=", "None", ",", "fields", "=", "None", ",", "ephemeral", "=", "False", ",", "unique", "=", "False", ")", ":", "if", "params", ":", "return", "self", ".", "create_indexes", "(", "cls_or_collection", ",", "[", "params", "]", ",", "ephemeral", "=", "ephemeral", ",", "unique", "=", "unique", ")", "elif", "fields", ":", "params", "=", "[", "]", "if", "len", "(", "fields", ".", "items", "(", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"File backend currently does not support multi-key indexes, sorry :/\"", ")", "return", "self", ".", "create_indexes", "(", "cls_or_collection", ",", "[", "{", "'key'", ":", "list", "(", "fields", ".", "keys", "(", ")", ")", "[", "0", "]", "}", "]", ",", "ephemeral", "=", "ephemeral", ",", "unique", "=", "unique", ")", "else", ":", "raise", "AttributeError", "(", "'You must either specify params or fields!'", ")" ]
Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an index :param params: The parameters of the index :param ephemeral: Whether to create a persistent or an ephemeral index :param unique: Whether the indexed field(s) must be unique `params` expects either a dictionary of parameters or a string value. In the latter case, it will interpret the string as the name of the key for which an index is to be created. If `ephemeral = True`, the index will be created only in memory and will not be written to disk when :py:meth:`.commit` is called. This is useful for optimizing query performance. ..notice:: By default, BlitzDB will create ephemeral indexes for all keys over which you perform queries, so after you've run a query on a given key for the first time, the second run will usually be much faster. **Specifying keys** Keys can be specified just like in MongoDB, using a dot ('.') to specify nested keys. .. code-block:: python actor = Actor({'name' : 'Charlie Chaplin', 'foo' : {'value' : 'bar'}}) If you want to create an index on `actor['foo']['value']` , you can just say .. code-block:: python backend.create_index(Actor,'foo.value') .. warning:: Transcendental indexes (i.e. indexes transcending the boundaries of referenced objects) are currently not supported by Blitz, which means you can't create an index on an attribute value of a document that is embedded in another document.
[ "Create", "new", "index", "on", "the", "given", "collection", "/", "class", "with", "given", "parameters", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L190-L250
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.get_pk_index
def get_pk_index(self, collection): """Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection """ cls = self.collections[collection] if not cls.get_pk_name() in self.indexes[collection]: self.create_index(cls.get_pk_name(), collection) return self.indexes[collection][cls.get_pk_name()]
python
def get_pk_index(self, collection): """Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection """ cls = self.collections[collection] if not cls.get_pk_name() in self.indexes[collection]: self.create_index(cls.get_pk_name(), collection) return self.indexes[collection][cls.get_pk_name()]
[ "def", "get_pk_index", "(", "self", ",", "collection", ")", ":", "cls", "=", "self", ".", "collections", "[", "collection", "]", "if", "not", "cls", ".", "get_pk_name", "(", ")", "in", "self", ".", "indexes", "[", "collection", "]", ":", "self", ".", "create_index", "(", "cls", ".", "get_pk_name", "(", ")", ",", "collection", ")", "return", "self", ".", "indexes", "[", "collection", "]", "[", "cls", ".", "get_pk_name", "(", ")", "]" ]
Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection
[ "Return", "the", "primary", "key", "index", "for", "a", "given", "collection", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L252-L264
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.update
def update(self, obj, set_fields = None, unset_fields = None, update_obj = True): """ We return the result of the save method (updates are not yet implemented here). """ if set_fields: if isinstance(set_fields,(list,tuple)): set_attributes = {} for key in set_fields: try: set_attributes[key] = get_value(obj,key) except KeyError: pass else: set_attributes = set_fields else: set_attributes = {} if unset_fields: unset_attributes = unset_fields else: unset_attributes = [] self.call_hook('before_update',obj,set_attributes,unset_attributes) if update_obj: for key,value in set_attributes.items(): set_value(obj,key,value) for key in unset_attributes: delete_value(obj,key) return self.save(obj,call_hook = False)
python
def update(self, obj, set_fields = None, unset_fields = None, update_obj = True): """ We return the result of the save method (updates are not yet implemented here). """ if set_fields: if isinstance(set_fields,(list,tuple)): set_attributes = {} for key in set_fields: try: set_attributes[key] = get_value(obj,key) except KeyError: pass else: set_attributes = set_fields else: set_attributes = {} if unset_fields: unset_attributes = unset_fields else: unset_attributes = [] self.call_hook('before_update',obj,set_attributes,unset_attributes) if update_obj: for key,value in set_attributes.items(): set_value(obj,key,value) for key in unset_attributes: delete_value(obj,key) return self.save(obj,call_hook = False)
[ "def", "update", "(", "self", ",", "obj", ",", "set_fields", "=", "None", ",", "unset_fields", "=", "None", ",", "update_obj", "=", "True", ")", ":", "if", "set_fields", ":", "if", "isinstance", "(", "set_fields", ",", "(", "list", ",", "tuple", ")", ")", ":", "set_attributes", "=", "{", "}", "for", "key", "in", "set_fields", ":", "try", ":", "set_attributes", "[", "key", "]", "=", "get_value", "(", "obj", ",", "key", ")", "except", "KeyError", ":", "pass", "else", ":", "set_attributes", "=", "set_fields", "else", ":", "set_attributes", "=", "{", "}", "if", "unset_fields", ":", "unset_attributes", "=", "unset_fields", "else", ":", "unset_attributes", "=", "[", "]", "self", ".", "call_hook", "(", "'before_update'", ",", "obj", ",", "set_attributes", ",", "unset_attributes", ")", "if", "update_obj", ":", "for", "key", ",", "value", "in", "set_attributes", ".", "items", "(", ")", ":", "set_value", "(", "obj", ",", "key", ",", "value", ")", "for", "key", "in", "unset_attributes", ":", "delete_value", "(", "obj", ",", "key", ")", "return", "self", ".", "save", "(", "obj", ",", "call_hook", "=", "False", ")" ]
We return the result of the save method (updates are not yet implemented here).
[ "We", "return", "the", "result", "of", "the", "save", "method", "(", "updates", "are", "not", "yet", "implemented", "here", ")", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L427-L456
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend._canonicalize_query
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {} for key,value in q.items(): nq[key] = transform_query(value) return nq elif isinstance(q, (list,QuerySet,tuple)): return [transform_query(x) for x in q] elif isinstance(q,Document): collection = self.get_collection_for_obj(q) ref = "%s:%s" % (collection,q.pk) return ref else: return q return transform_query(query)
python
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {} for key,value in q.items(): nq[key] = transform_query(value) return nq elif isinstance(q, (list,QuerySet,tuple)): return [transform_query(x) for x in q] elif isinstance(q,Document): collection = self.get_collection_for_obj(q) ref = "%s:%s" % (collection,q.pk) return ref else: return q return transform_query(query)
[ "def", "_canonicalize_query", "(", "self", ",", "query", ")", ":", "def", "transform_query", "(", "q", ")", ":", "if", "isinstance", "(", "q", ",", "dict", ")", ":", "nq", "=", "{", "}", "for", "key", ",", "value", "in", "q", ".", "items", "(", ")", ":", "nq", "[", "key", "]", "=", "transform_query", "(", "value", ")", "return", "nq", "elif", "isinstance", "(", "q", ",", "(", "list", ",", "QuerySet", ",", "tuple", ")", ")", ":", "return", "[", "transform_query", "(", "x", ")", "for", "x", "in", "q", "]", "elif", "isinstance", "(", "q", ",", "Document", ")", ":", "collection", "=", "self", ".", "get_collection_for_obj", "(", "q", ")", "ref", "=", "\"%s:%s\"", "%", "(", "collection", ",", "q", ".", "pk", ")", "return", "ref", "else", ":", "return", "q", "return", "transform_query", "(", "query", ")" ]
Transform the query dictionary to replace e.g. documents with __ref__ fields.
[ "Transform", "the", "query", "dictionary", "to", "replace", "e", ".", "g", ".", "documents", "with", "__ref__", "fields", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L567-L589
adewes/blitzdb
blitzdb/backends/base.py
Backend.register
def register(self, cls, parameters=None,overwrite = False): """ Explicitly register a new document class for use in the backend. :param cls: A reference to the class to be defined :param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used to specify the collection in which to store the documents of the given class. .. admonition:: Registering classes If possible, always use `autodiscover_classes = True` or register your document classes beforehand using the `register` function, since this ensures that related documents can be initialized appropriately. For example, suppose you have a document class `Author` that contains a list of references to documents of class `Book`. If you retrieve an instance of an `Author` object from the database without having registered the `Book` class, the references to that class will not get parsed properly and will just show up as dictionaries containing a primary key and a collection name. Also, when :py:meth:`blitzdb.backends.base.Backend.autoregister` is used to register a class, you can't pass in any parameters to customize e.g. the collection name for that class (you can of course do this throught the `Meta` attribute of the class) ## Inheritance If `register` encounters a document class with a collection name that overlaps with the collection name of an already registered document class, it checks if the new class is a subclass of the one that is already register. If yes, it associates the new class to the collection name. Otherwise, it leaves the collection associated to the already registered class. """ if cls in self.deprecated_classes and not overwrite: return False if parameters is None: parameters = {} if 'collection' in parameters: collection_name = parameters['collection'] elif hasattr(cls.Meta,'collection'): collection_name = cls.Meta.collection else: collection_name = cls.__name__.lower() delete_list = [] def register_class(collection_name,cls): self.collections[collection_name] = cls self.classes[cls] = parameters.copy() self.classes[cls]['collection'] = collection_name if collection_name in self.collections: old_cls = self.collections[collection_name] if (issubclass(cls,old_cls) and not (cls is old_cls)) or overwrite: logger.warning("Replacing class %s with %s for collection %s" % (old_cls,cls,collection_name)) self.deprecated_classes[old_cls] = self.classes[old_cls] del self.classes[old_cls] register_class(collection_name,cls) return True else: logger.debug("Registering class %s under collection %s" % (cls,collection_name)) register_class(collection_name,cls) return True return False
python
def register(self, cls, parameters=None,overwrite = False): """ Explicitly register a new document class for use in the backend. :param cls: A reference to the class to be defined :param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used to specify the collection in which to store the documents of the given class. .. admonition:: Registering classes If possible, always use `autodiscover_classes = True` or register your document classes beforehand using the `register` function, since this ensures that related documents can be initialized appropriately. For example, suppose you have a document class `Author` that contains a list of references to documents of class `Book`. If you retrieve an instance of an `Author` object from the database without having registered the `Book` class, the references to that class will not get parsed properly and will just show up as dictionaries containing a primary key and a collection name. Also, when :py:meth:`blitzdb.backends.base.Backend.autoregister` is used to register a class, you can't pass in any parameters to customize e.g. the collection name for that class (you can of course do this throught the `Meta` attribute of the class) ## Inheritance If `register` encounters a document class with a collection name that overlaps with the collection name of an already registered document class, it checks if the new class is a subclass of the one that is already register. If yes, it associates the new class to the collection name. Otherwise, it leaves the collection associated to the already registered class. """ if cls in self.deprecated_classes and not overwrite: return False if parameters is None: parameters = {} if 'collection' in parameters: collection_name = parameters['collection'] elif hasattr(cls.Meta,'collection'): collection_name = cls.Meta.collection else: collection_name = cls.__name__.lower() delete_list = [] def register_class(collection_name,cls): self.collections[collection_name] = cls self.classes[cls] = parameters.copy() self.classes[cls]['collection'] = collection_name if collection_name in self.collections: old_cls = self.collections[collection_name] if (issubclass(cls,old_cls) and not (cls is old_cls)) or overwrite: logger.warning("Replacing class %s with %s for collection %s" % (old_cls,cls,collection_name)) self.deprecated_classes[old_cls] = self.classes[old_cls] del self.classes[old_cls] register_class(collection_name,cls) return True else: logger.debug("Registering class %s under collection %s" % (cls,collection_name)) register_class(collection_name,cls) return True return False
[ "def", "register", "(", "self", ",", "cls", ",", "parameters", "=", "None", ",", "overwrite", "=", "False", ")", ":", "if", "cls", "in", "self", ".", "deprecated_classes", "and", "not", "overwrite", ":", "return", "False", "if", "parameters", "is", "None", ":", "parameters", "=", "{", "}", "if", "'collection'", "in", "parameters", ":", "collection_name", "=", "parameters", "[", "'collection'", "]", "elif", "hasattr", "(", "cls", ".", "Meta", ",", "'collection'", ")", ":", "collection_name", "=", "cls", ".", "Meta", ".", "collection", "else", ":", "collection_name", "=", "cls", ".", "__name__", ".", "lower", "(", ")", "delete_list", "=", "[", "]", "def", "register_class", "(", "collection_name", ",", "cls", ")", ":", "self", ".", "collections", "[", "collection_name", "]", "=", "cls", "self", ".", "classes", "[", "cls", "]", "=", "parameters", ".", "copy", "(", ")", "self", ".", "classes", "[", "cls", "]", "[", "'collection'", "]", "=", "collection_name", "if", "collection_name", "in", "self", ".", "collections", ":", "old_cls", "=", "self", ".", "collections", "[", "collection_name", "]", "if", "(", "issubclass", "(", "cls", ",", "old_cls", ")", "and", "not", "(", "cls", "is", "old_cls", ")", ")", "or", "overwrite", ":", "logger", ".", "warning", "(", "\"Replacing class %s with %s for collection %s\"", "%", "(", "old_cls", ",", "cls", ",", "collection_name", ")", ")", "self", ".", "deprecated_classes", "[", "old_cls", "]", "=", "self", ".", "classes", "[", "old_cls", "]", "del", "self", ".", "classes", "[", "old_cls", "]", "register_class", "(", "collection_name", ",", "cls", ")", "return", "True", "else", ":", "logger", ".", "debug", "(", "\"Registering class %s under collection %s\"", "%", "(", "cls", ",", "collection_name", ")", ")", "register_class", "(", "collection_name", ",", "cls", ")", "return", "True", "return", "False" ]
Explicitly register a new document class for use in the backend. :param cls: A reference to the class to be defined :param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used to specify the collection in which to store the documents of the given class. .. admonition:: Registering classes If possible, always use `autodiscover_classes = True` or register your document classes beforehand using the `register` function, since this ensures that related documents can be initialized appropriately. For example, suppose you have a document class `Author` that contains a list of references to documents of class `Book`. If you retrieve an instance of an `Author` object from the database without having registered the `Book` class, the references to that class will not get parsed properly and will just show up as dictionaries containing a primary key and a collection name. Also, when :py:meth:`blitzdb.backends.base.Backend.autoregister` is used to register a class, you can't pass in any parameters to customize e.g. the collection name for that class (you can of course do this throught the `Meta` attribute of the class) ## Inheritance If `register` encounters a document class with a collection name that overlaps with the collection name of an already registered document class, it checks if the new class is a subclass of the one that is already register. If yes, it associates the new class to the collection name. Otherwise, it leaves the collection associated to the already registered class.
[ "Explicitly", "register", "a", "new", "document", "class", "for", "use", "in", "the", "backend", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L101-L163
adewes/blitzdb
blitzdb/backends/base.py
Backend.autoregister
def autoregister(self, cls): """ Autoregister a class that is encountered for the first time. :param cls: The class that should be registered. """ params = self.get_meta_attributes(cls) return self.register(cls, params)
python
def autoregister(self, cls): """ Autoregister a class that is encountered for the first time. :param cls: The class that should be registered. """ params = self.get_meta_attributes(cls) return self.register(cls, params)
[ "def", "autoregister", "(", "self", ",", "cls", ")", ":", "params", "=", "self", ".", "get_meta_attributes", "(", "cls", ")", "return", "self", ".", "register", "(", "cls", ",", "params", ")" ]
Autoregister a class that is encountered for the first time. :param cls: The class that should be registered.
[ "Autoregister", "a", "class", "that", "is", "encountered", "for", "the", "first", "time", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L180-L188
adewes/blitzdb
blitzdb/backends/base.py
Backend.serialize
def serialize(self, obj, convert_keys_to_str=False, embed_level=0, encoders=None, autosave=True, for_query=False,path = None): """ Serializes a given object, i.e. converts it to a representation that can be stored in the database. This usually involves replacing all `Document` instances by database references to them. :param obj: The object to serialize. :param convert_keys_to_str: If `True`, converts all dictionary keys to string (this is e.g. required for the MongoDB backend) :param embed_level: If `embed_level > 0`, instances of `Document` classes will be embedded instead of referenced. The value of the parameter will get decremented by 1 when calling `serialize` on child objects. :param autosave: Whether to automatically save embedded objects without a primary key to the database. :param for_query: If true, only the `pk` and `__collection__` attributes will be included in document references. :returns: The serialized object. """ if path is None: path = [] def get_value(obj,key): key_fragments = key.split(".") current_dict = obj for key_fragment in key_fragments: current_dict = current_dict[key_fragment] return current_dict serialize_with_opts = lambda value,*args,**kwargs : self.serialize(value,*args, encoders = encoders, convert_keys_to_str = convert_keys_to_str, autosave = autosave, for_query = for_query, **kwargs) if encoders is None: encoders = [] for encoder in self.standard_encoders+encoders: obj = encoder.encode(obj,path = path) def encode_as_str(obj): if six.PY3: return str(obj) else: if isinstance(obj,unicode): return obj elif isinstance(obj,str): return unicode(obj) else: return unicode(str(obj),errors='replace') if isinstance(obj, dict): output_obj = {} for key, value in obj.items(): new_path = path[:]+[key] try: output_obj[encode_as_str(key) if convert_keys_to_str else key] = serialize_with_opts(value, embed_level=embed_level,path = new_path) except DoNotSerialize: pass elif isinstance(obj,six.string_types): output_obj = encode_as_str(obj) elif isinstance(obj, (list,tuple)): try: output_obj = [serialize_with_opts(x, embed_level=embed_level,path = path[:]+[i]) for i,x in enumerate(obj)] except DoNotSerialize: pass elif isinstance(obj, Document): collection = self.get_collection_for_obj(obj) if embed_level > 0: try: output_obj = self.serialize(obj, embed_level=embed_level-1) except obj.DoesNotExist:#cannot load object, ignoring... output_obj = self.serialize(obj.lazy_attributes, embed_level=embed_level-1) except DoNotSerialize: pass elif obj.embed: output_obj = self.serialize(obj) else: if obj.pk == None and autosave: obj.save(self) if obj._lazy: # We make sure that all attributes that are already present get included in the reference output_obj = {} if obj.get_pk_name() in output_obj: del output_obj[obj.get_pk_name()] output_obj['pk'] = obj.pk output_obj['__collection__'] = self.classes[obj.__class__]['collection'] else: if for_query and not self._allow_documents_in_query: raise ValueError("Documents are not allowed in queries!") if for_query: output_obj = {'$elemMatch' : {'pk':obj.pk,'__collection__':self.classes[obj.__class__]['collection']}} else: ref = "%s:%s" % (self.classes[obj.__class__]['collection'],str(obj.pk)) output_obj = {'__ref__' : ref,'pk':obj.pk,'__collection__':self.classes[obj.__class__]['collection']} if hasattr(obj,'Meta') and hasattr(obj.Meta,'dbref_includes') and obj.Meta.dbref_includes: for include_key in obj.Meta.dbref_includes: try: value = get_value(obj,include_key) output_obj[include_key.replace(".","_")] = value except KeyError: continue else: output_obj = obj return output_obj
python
def serialize(self, obj, convert_keys_to_str=False, embed_level=0, encoders=None, autosave=True, for_query=False,path = None): """ Serializes a given object, i.e. converts it to a representation that can be stored in the database. This usually involves replacing all `Document` instances by database references to them. :param obj: The object to serialize. :param convert_keys_to_str: If `True`, converts all dictionary keys to string (this is e.g. required for the MongoDB backend) :param embed_level: If `embed_level > 0`, instances of `Document` classes will be embedded instead of referenced. The value of the parameter will get decremented by 1 when calling `serialize` on child objects. :param autosave: Whether to automatically save embedded objects without a primary key to the database. :param for_query: If true, only the `pk` and `__collection__` attributes will be included in document references. :returns: The serialized object. """ if path is None: path = [] def get_value(obj,key): key_fragments = key.split(".") current_dict = obj for key_fragment in key_fragments: current_dict = current_dict[key_fragment] return current_dict serialize_with_opts = lambda value,*args,**kwargs : self.serialize(value,*args, encoders = encoders, convert_keys_to_str = convert_keys_to_str, autosave = autosave, for_query = for_query, **kwargs) if encoders is None: encoders = [] for encoder in self.standard_encoders+encoders: obj = encoder.encode(obj,path = path) def encode_as_str(obj): if six.PY3: return str(obj) else: if isinstance(obj,unicode): return obj elif isinstance(obj,str): return unicode(obj) else: return unicode(str(obj),errors='replace') if isinstance(obj, dict): output_obj = {} for key, value in obj.items(): new_path = path[:]+[key] try: output_obj[encode_as_str(key) if convert_keys_to_str else key] = serialize_with_opts(value, embed_level=embed_level,path = new_path) except DoNotSerialize: pass elif isinstance(obj,six.string_types): output_obj = encode_as_str(obj) elif isinstance(obj, (list,tuple)): try: output_obj = [serialize_with_opts(x, embed_level=embed_level,path = path[:]+[i]) for i,x in enumerate(obj)] except DoNotSerialize: pass elif isinstance(obj, Document): collection = self.get_collection_for_obj(obj) if embed_level > 0: try: output_obj = self.serialize(obj, embed_level=embed_level-1) except obj.DoesNotExist:#cannot load object, ignoring... output_obj = self.serialize(obj.lazy_attributes, embed_level=embed_level-1) except DoNotSerialize: pass elif obj.embed: output_obj = self.serialize(obj) else: if obj.pk == None and autosave: obj.save(self) if obj._lazy: # We make sure that all attributes that are already present get included in the reference output_obj = {} if obj.get_pk_name() in output_obj: del output_obj[obj.get_pk_name()] output_obj['pk'] = obj.pk output_obj['__collection__'] = self.classes[obj.__class__]['collection'] else: if for_query and not self._allow_documents_in_query: raise ValueError("Documents are not allowed in queries!") if for_query: output_obj = {'$elemMatch' : {'pk':obj.pk,'__collection__':self.classes[obj.__class__]['collection']}} else: ref = "%s:%s" % (self.classes[obj.__class__]['collection'],str(obj.pk)) output_obj = {'__ref__' : ref,'pk':obj.pk,'__collection__':self.classes[obj.__class__]['collection']} if hasattr(obj,'Meta') and hasattr(obj.Meta,'dbref_includes') and obj.Meta.dbref_includes: for include_key in obj.Meta.dbref_includes: try: value = get_value(obj,include_key) output_obj[include_key.replace(".","_")] = value except KeyError: continue else: output_obj = obj return output_obj
[ "def", "serialize", "(", "self", ",", "obj", ",", "convert_keys_to_str", "=", "False", ",", "embed_level", "=", "0", ",", "encoders", "=", "None", ",", "autosave", "=", "True", ",", "for_query", "=", "False", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "[", "]", "def", "get_value", "(", "obj", ",", "key", ")", ":", "key_fragments", "=", "key", ".", "split", "(", "\".\"", ")", "current_dict", "=", "obj", "for", "key_fragment", "in", "key_fragments", ":", "current_dict", "=", "current_dict", "[", "key_fragment", "]", "return", "current_dict", "serialize_with_opts", "=", "lambda", "value", ",", "*", "args", ",", "*", "*", "kwargs", ":", "self", ".", "serialize", "(", "value", ",", "*", "args", ",", "encoders", "=", "encoders", ",", "convert_keys_to_str", "=", "convert_keys_to_str", ",", "autosave", "=", "autosave", ",", "for_query", "=", "for_query", ",", "*", "*", "kwargs", ")", "if", "encoders", "is", "None", ":", "encoders", "=", "[", "]", "for", "encoder", "in", "self", ".", "standard_encoders", "+", "encoders", ":", "obj", "=", "encoder", ".", "encode", "(", "obj", ",", "path", "=", "path", ")", "def", "encode_as_str", "(", "obj", ")", ":", "if", "six", ".", "PY3", ":", "return", "str", "(", "obj", ")", "else", ":", "if", "isinstance", "(", "obj", ",", "unicode", ")", ":", "return", "obj", "elif", "isinstance", "(", "obj", ",", "str", ")", ":", "return", "unicode", "(", "obj", ")", "else", ":", "return", "unicode", "(", "str", "(", "obj", ")", ",", "errors", "=", "'replace'", ")", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "output_obj", "=", "{", "}", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "new_path", "=", "path", "[", ":", "]", "+", "[", "key", "]", "try", ":", "output_obj", "[", "encode_as_str", "(", "key", ")", "if", "convert_keys_to_str", "else", "key", "]", "=", "serialize_with_opts", "(", "value", ",", "embed_level", "=", "embed_level", ",", "path", "=", "new_path", ")", "except", "DoNotSerialize", ":", "pass", "elif", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")", ":", "output_obj", "=", "encode_as_str", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "try", ":", "output_obj", "=", "[", "serialize_with_opts", "(", "x", ",", "embed_level", "=", "embed_level", ",", "path", "=", "path", "[", ":", "]", "+", "[", "i", "]", ")", "for", "i", ",", "x", "in", "enumerate", "(", "obj", ")", "]", "except", "DoNotSerialize", ":", "pass", "elif", "isinstance", "(", "obj", ",", "Document", ")", ":", "collection", "=", "self", ".", "get_collection_for_obj", "(", "obj", ")", "if", "embed_level", ">", "0", ":", "try", ":", "output_obj", "=", "self", ".", "serialize", "(", "obj", ",", "embed_level", "=", "embed_level", "-", "1", ")", "except", "obj", ".", "DoesNotExist", ":", "#cannot load object, ignoring...", "output_obj", "=", "self", ".", "serialize", "(", "obj", ".", "lazy_attributes", ",", "embed_level", "=", "embed_level", "-", "1", ")", "except", "DoNotSerialize", ":", "pass", "elif", "obj", ".", "embed", ":", "output_obj", "=", "self", ".", "serialize", "(", "obj", ")", "else", ":", "if", "obj", ".", "pk", "==", "None", "and", "autosave", ":", "obj", ".", "save", "(", "self", ")", "if", "obj", ".", "_lazy", ":", "# We make sure that all attributes that are already present get included in the reference", "output_obj", "=", "{", "}", "if", "obj", ".", "get_pk_name", "(", ")", "in", "output_obj", ":", "del", "output_obj", "[", "obj", ".", "get_pk_name", "(", ")", "]", "output_obj", "[", "'pk'", "]", "=", "obj", ".", "pk", "output_obj", "[", "'__collection__'", "]", "=", "self", ".", "classes", "[", "obj", ".", "__class__", "]", "[", "'collection'", "]", "else", ":", "if", "for_query", "and", "not", "self", ".", "_allow_documents_in_query", ":", "raise", "ValueError", "(", "\"Documents are not allowed in queries!\"", ")", "if", "for_query", ":", "output_obj", "=", "{", "'$elemMatch'", ":", "{", "'pk'", ":", "obj", ".", "pk", ",", "'__collection__'", ":", "self", ".", "classes", "[", "obj", ".", "__class__", "]", "[", "'collection'", "]", "}", "}", "else", ":", "ref", "=", "\"%s:%s\"", "%", "(", "self", ".", "classes", "[", "obj", ".", "__class__", "]", "[", "'collection'", "]", ",", "str", "(", "obj", ".", "pk", ")", ")", "output_obj", "=", "{", "'__ref__'", ":", "ref", ",", "'pk'", ":", "obj", ".", "pk", ",", "'__collection__'", ":", "self", ".", "classes", "[", "obj", ".", "__class__", "]", "[", "'collection'", "]", "}", "if", "hasattr", "(", "obj", ",", "'Meta'", ")", "and", "hasattr", "(", "obj", ".", "Meta", ",", "'dbref_includes'", ")", "and", "obj", ".", "Meta", ".", "dbref_includes", ":", "for", "include_key", "in", "obj", ".", "Meta", ".", "dbref_includes", ":", "try", ":", "value", "=", "get_value", "(", "obj", ",", "include_key", ")", "output_obj", "[", "include_key", ".", "replace", "(", "\".\"", ",", "\"_\"", ")", "]", "=", "value", "except", "KeyError", ":", "continue", "else", ":", "output_obj", "=", "obj", "return", "output_obj" ]
Serializes a given object, i.e. converts it to a representation that can be stored in the database. This usually involves replacing all `Document` instances by database references to them. :param obj: The object to serialize. :param convert_keys_to_str: If `True`, converts all dictionary keys to string (this is e.g. required for the MongoDB backend) :param embed_level: If `embed_level > 0`, instances of `Document` classes will be embedded instead of referenced. The value of the parameter will get decremented by 1 when calling `serialize` on child objects. :param autosave: Whether to automatically save embedded objects without a primary key to the database. :param for_query: If true, only the `pk` and `__collection__` attributes will be included in document references. :returns: The serialized object.
[ "Serializes", "a", "given", "object", "i", ".", "e", ".", "converts", "it", "to", "a", "representation", "that", "can", "be", "stored", "in", "the", "database", ".", "This", "usually", "involves", "replacing", "all", "Document", "instances", "by", "database", "references", "to", "them", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L190-L300
adewes/blitzdb
blitzdb/backends/base.py
Backend.deserialize
def deserialize(self, obj, encoders=None, embedded=False, create_instance=True): """ Deserializes a given object, i.e. converts references to other (known) `Document` objects by lazy instances of the corresponding class. This allows the automatic fetching of related documents from the database as required. :param obj: The object to be deserialized. :returns: The deserialized object. """ if not encoders: encoders = [] for encoder in encoders + self.standard_encoders: obj = encoder.decode(obj) if isinstance(obj, dict): if create_instance and '__collection__' in obj and obj['__collection__'] in self.collections and 'pk' in obj: #for backwards compatibility attributes = copy.deepcopy(obj) del attributes['__collection__'] if '__ref__' in attributes: del attributes['__ref__'] if '__lazy__' in attributes: lazy = attributes['__lazy__'] del attributes['__lazy__'] else: lazy = True output_obj = self.create_instance(obj['__collection__'], attributes, lazy=lazy) else: output_obj = {} for key, value in obj.items(): output_obj[key] = self.deserialize(value,encoders = encoders) elif isinstance(obj, (list,tuple)): output_obj = list(map(lambda x: self.deserialize(x), obj)) else: output_obj = obj return output_obj
python
def deserialize(self, obj, encoders=None, embedded=False, create_instance=True): """ Deserializes a given object, i.e. converts references to other (known) `Document` objects by lazy instances of the corresponding class. This allows the automatic fetching of related documents from the database as required. :param obj: The object to be deserialized. :returns: The deserialized object. """ if not encoders: encoders = [] for encoder in encoders + self.standard_encoders: obj = encoder.decode(obj) if isinstance(obj, dict): if create_instance and '__collection__' in obj and obj['__collection__'] in self.collections and 'pk' in obj: #for backwards compatibility attributes = copy.deepcopy(obj) del attributes['__collection__'] if '__ref__' in attributes: del attributes['__ref__'] if '__lazy__' in attributes: lazy = attributes['__lazy__'] del attributes['__lazy__'] else: lazy = True output_obj = self.create_instance(obj['__collection__'], attributes, lazy=lazy) else: output_obj = {} for key, value in obj.items(): output_obj[key] = self.deserialize(value,encoders = encoders) elif isinstance(obj, (list,tuple)): output_obj = list(map(lambda x: self.deserialize(x), obj)) else: output_obj = obj return output_obj
[ "def", "deserialize", "(", "self", ",", "obj", ",", "encoders", "=", "None", ",", "embedded", "=", "False", ",", "create_instance", "=", "True", ")", ":", "if", "not", "encoders", ":", "encoders", "=", "[", "]", "for", "encoder", "in", "encoders", "+", "self", ".", "standard_encoders", ":", "obj", "=", "encoder", ".", "decode", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "if", "create_instance", "and", "'__collection__'", "in", "obj", "and", "obj", "[", "'__collection__'", "]", "in", "self", ".", "collections", "and", "'pk'", "in", "obj", ":", "#for backwards compatibility", "attributes", "=", "copy", ".", "deepcopy", "(", "obj", ")", "del", "attributes", "[", "'__collection__'", "]", "if", "'__ref__'", "in", "attributes", ":", "del", "attributes", "[", "'__ref__'", "]", "if", "'__lazy__'", "in", "attributes", ":", "lazy", "=", "attributes", "[", "'__lazy__'", "]", "del", "attributes", "[", "'__lazy__'", "]", "else", ":", "lazy", "=", "True", "output_obj", "=", "self", ".", "create_instance", "(", "obj", "[", "'__collection__'", "]", ",", "attributes", ",", "lazy", "=", "lazy", ")", "else", ":", "output_obj", "=", "{", "}", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "output_obj", "[", "key", "]", "=", "self", ".", "deserialize", "(", "value", ",", "encoders", "=", "encoders", ")", "elif", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "output_obj", "=", "list", "(", "map", "(", "lambda", "x", ":", "self", ".", "deserialize", "(", "x", ")", ",", "obj", ")", ")", "else", ":", "output_obj", "=", "obj", "return", "output_obj" ]
Deserializes a given object, i.e. converts references to other (known) `Document` objects by lazy instances of the corresponding class. This allows the automatic fetching of related documents from the database as required. :param obj: The object to be deserialized. :returns: The deserialized object.
[ "Deserializes", "a", "given", "object", "i", ".", "e", ".", "converts", "references", "to", "other", "(", "known", ")", "Document", "objects", "by", "lazy", "instances", "of", "the", "corresponding", "class", ".", "This", "allows", "the", "automatic", "fetching", "of", "related", "documents", "from", "the", "database", "as", "required", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L302-L340
adewes/blitzdb
blitzdb/backends/base.py
Backend.create_instance
def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None): """ Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to the class for which to create an instance. :param attributes: The attributes of the instance to be created :param lazy: Whether to create a `lazy` object or not. :returns: An instance of the requested Document class with the given attributes. """ creation_args = { 'backend' : self, 'autoload' : self._autoload_embedded, 'lazy' : lazy, 'db_loader' : db_loader } if collection_or_class in self.classes: cls = collection_or_class elif collection_or_class in self.collections: cls = self.collections[collection_or_class] else: raise AttributeError("Unknown collection or class: %s!" % str(collection_or_class)) #we deserialize the attributes that we receive if deserialize: deserialized_attributes = self.deserialize(attributes, create_instance=False) else: deserialized_attributes = attributes if 'constructor' in self.classes[cls]: obj = self.classes[cls]['constructor'](deserialized_attributes, **creation_args) else: obj = cls(deserialized_attributes, **creation_args) if call_hook: self.call_hook('after_load',obj) return obj
python
def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None): """ Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to the class for which to create an instance. :param attributes: The attributes of the instance to be created :param lazy: Whether to create a `lazy` object or not. :returns: An instance of the requested Document class with the given attributes. """ creation_args = { 'backend' : self, 'autoload' : self._autoload_embedded, 'lazy' : lazy, 'db_loader' : db_loader } if collection_or_class in self.classes: cls = collection_or_class elif collection_or_class in self.collections: cls = self.collections[collection_or_class] else: raise AttributeError("Unknown collection or class: %s!" % str(collection_or_class)) #we deserialize the attributes that we receive if deserialize: deserialized_attributes = self.deserialize(attributes, create_instance=False) else: deserialized_attributes = attributes if 'constructor' in self.classes[cls]: obj = self.classes[cls]['constructor'](deserialized_attributes, **creation_args) else: obj = cls(deserialized_attributes, **creation_args) if call_hook: self.call_hook('after_load',obj) return obj
[ "def", "create_instance", "(", "self", ",", "collection_or_class", ",", "attributes", ",", "lazy", "=", "False", ",", "call_hook", "=", "True", ",", "deserialize", "=", "True", ",", "db_loader", "=", "None", ")", ":", "creation_args", "=", "{", "'backend'", ":", "self", ",", "'autoload'", ":", "self", ".", "_autoload_embedded", ",", "'lazy'", ":", "lazy", ",", "'db_loader'", ":", "db_loader", "}", "if", "collection_or_class", "in", "self", ".", "classes", ":", "cls", "=", "collection_or_class", "elif", "collection_or_class", "in", "self", ".", "collections", ":", "cls", "=", "self", ".", "collections", "[", "collection_or_class", "]", "else", ":", "raise", "AttributeError", "(", "\"Unknown collection or class: %s!\"", "%", "str", "(", "collection_or_class", ")", ")", "#we deserialize the attributes that we receive", "if", "deserialize", ":", "deserialized_attributes", "=", "self", ".", "deserialize", "(", "attributes", ",", "create_instance", "=", "False", ")", "else", ":", "deserialized_attributes", "=", "attributes", "if", "'constructor'", "in", "self", ".", "classes", "[", "cls", "]", ":", "obj", "=", "self", ".", "classes", "[", "cls", "]", "[", "'constructor'", "]", "(", "deserialized_attributes", ",", "*", "*", "creation_args", ")", "else", ":", "obj", "=", "cls", "(", "deserialized_attributes", ",", "*", "*", "creation_args", ")", "if", "call_hook", ":", "self", ".", "call_hook", "(", "'after_load'", ",", "obj", ")", "return", "obj" ]
Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to the class for which to create an instance. :param attributes: The attributes of the instance to be created :param lazy: Whether to create a `lazy` object or not. :returns: An instance of the requested Document class with the given attributes.
[ "Creates", "an", "instance", "of", "a", "Document", "class", "corresponding", "to", "the", "given", "collection", "name", "or", "class", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L342-L380
adewes/blitzdb
blitzdb/backends/base.py
Backend.transaction
def transaction(self,implicit = False): """ This returns a context guard which will automatically open and close a transaction """ class TransactionManager(object): def __init__(self,backend,implicit = False): self.backend = backend self.implicit = implicit def __enter__(self): self.within_transaction = True if self.backend.current_transaction else False self.transaction = self.backend.begin() def __exit__(self,exc_type,exc_value,traceback_obj): if exc_type: self.backend.rollback(self.transaction) return False else: #if the transaction has been created implicitly and we are not within #another transaction, we leave it open (the user needs to call commit manually) #if self.implicit and not self.within_transaction: # return self.backend.commit(self.transaction) return TransactionManager(self,implicit = implicit)
python
def transaction(self,implicit = False): """ This returns a context guard which will automatically open and close a transaction """ class TransactionManager(object): def __init__(self,backend,implicit = False): self.backend = backend self.implicit = implicit def __enter__(self): self.within_transaction = True if self.backend.current_transaction else False self.transaction = self.backend.begin() def __exit__(self,exc_type,exc_value,traceback_obj): if exc_type: self.backend.rollback(self.transaction) return False else: #if the transaction has been created implicitly and we are not within #another transaction, we leave it open (the user needs to call commit manually) #if self.implicit and not self.within_transaction: # return self.backend.commit(self.transaction) return TransactionManager(self,implicit = implicit)
[ "def", "transaction", "(", "self", ",", "implicit", "=", "False", ")", ":", "class", "TransactionManager", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "backend", ",", "implicit", "=", "False", ")", ":", "self", ".", "backend", "=", "backend", "self", ".", "implicit", "=", "implicit", "def", "__enter__", "(", "self", ")", ":", "self", ".", "within_transaction", "=", "True", "if", "self", ".", "backend", ".", "current_transaction", "else", "False", "self", ".", "transaction", "=", "self", ".", "backend", ".", "begin", "(", ")", "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_value", ",", "traceback_obj", ")", ":", "if", "exc_type", ":", "self", ".", "backend", ".", "rollback", "(", "self", ".", "transaction", ")", "return", "False", "else", ":", "#if the transaction has been created implicitly and we are not within", "#another transaction, we leave it open (the user needs to call commit manually)", "#if self.implicit and not self.within_transaction:", "# return", "self", ".", "backend", ".", "commit", "(", "self", ".", "transaction", ")", "return", "TransactionManager", "(", "self", ",", "implicit", "=", "implicit", ")" ]
This returns a context guard which will automatically open and close a transaction
[ "This", "returns", "a", "context", "guard", "which", "will", "automatically", "open", "and", "close", "a", "transaction" ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L387-L413
adewes/blitzdb
blitzdb/backends/base.py
Backend.get_collection_for_cls
def get_collection_for_cls(self, cls): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ if cls not in self.classes: if issubclass(cls, Document) and cls not in self.classes and cls not in self.deprecated_classes: self.autoregister(cls) else: raise AttributeError("Unknown object type: %s" % cls.__name__) collection = self.classes[cls]['collection'] return collection
python
def get_collection_for_cls(self, cls): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ if cls not in self.classes: if issubclass(cls, Document) and cls not in self.classes and cls not in self.deprecated_classes: self.autoregister(cls) else: raise AttributeError("Unknown object type: %s" % cls.__name__) collection = self.classes[cls]['collection'] return collection
[ "def", "get_collection_for_cls", "(", "self", ",", "cls", ")", ":", "if", "cls", "not", "in", "self", ".", "classes", ":", "if", "issubclass", "(", "cls", ",", "Document", ")", "and", "cls", "not", "in", "self", ".", "classes", "and", "cls", "not", "in", "self", ".", "deprecated_classes", ":", "self", ".", "autoregister", "(", "cls", ")", "else", ":", "raise", "AttributeError", "(", "\"Unknown object type: %s\"", "%", "cls", ".", "__name__", ")", "collection", "=", "self", ".", "classes", "[", "cls", "]", "[", "'collection'", "]", "return", "collection" ]
Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class.
[ "Returns", "the", "collection", "name", "for", "a", "given", "document", "class", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L425-L439
adewes/blitzdb
blitzdb/backends/base.py
Backend.get_collection_for_cls_name
def get_collection_for_cls_name(self, cls_name): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ for cls in self.classes: if cls.__name__ == cls_name: return self.classes[cls]['collection'] raise AttributeError("Unknown class name: %s" % cls_name)
python
def get_collection_for_cls_name(self, cls_name): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ for cls in self.classes: if cls.__name__ == cls_name: return self.classes[cls]['collection'] raise AttributeError("Unknown class name: %s" % cls_name)
[ "def", "get_collection_for_cls_name", "(", "self", ",", "cls_name", ")", ":", "for", "cls", "in", "self", ".", "classes", ":", "if", "cls", ".", "__name__", "==", "cls_name", ":", "return", "self", ".", "classes", "[", "cls", "]", "[", "'collection'", "]", "raise", "AttributeError", "(", "\"Unknown class name: %s\"", "%", "cls_name", ")" ]
Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class.
[ "Returns", "the", "collection", "name", "for", "a", "given", "document", "class", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L441-L452
adewes/blitzdb
blitzdb/backends/base.py
Backend.get_cls_for_collection
def get_cls_for_collection(self, collection): """ Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name. """ for cls, params in self.classes.items(): if params['collection'] == collection: return cls raise AttributeError("Unknown collection: %s" % collection)
python
def get_cls_for_collection(self, collection): """ Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name. """ for cls, params in self.classes.items(): if params['collection'] == collection: return cls raise AttributeError("Unknown collection: %s" % collection)
[ "def", "get_cls_for_collection", "(", "self", ",", "collection", ")", ":", "for", "cls", ",", "params", "in", "self", ".", "classes", ".", "items", "(", ")", ":", "if", "params", "[", "'collection'", "]", "==", "collection", ":", "return", "cls", "raise", "AttributeError", "(", "\"Unknown collection: %s\"", "%", "collection", ")" ]
Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name.
[ "Return", "the", "class", "for", "a", "given", "collection", "name", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L454-L465
adewes/blitzdb
blitzdb/backends/file/index.py
Index.clear
def clear(self): """Clear index.""" self._index = defaultdict(list) self._reverse_index = defaultdict(list) self._undefined_keys = {}
python
def clear(self): """Clear index.""" self._index = defaultdict(list) self._reverse_index = defaultdict(list) self._undefined_keys = {}
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_index", "=", "defaultdict", "(", "list", ")", "self", ".", "_reverse_index", "=", "defaultdict", "(", "list", ")", "self", ".", "_undefined_keys", "=", "{", "}" ]
Clear index.
[ "Clear", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L54-L58
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_value
def get_value(self, attributes,key = None): """Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object """ value = attributes if key is None: key = self._splitted_key # A splitted key like 'a.b.c' goes into nested properties # and the value is retrieved recursively for i,elem in enumerate(key): if isinstance(value, (list,tuple)): #if this is a list, we return all matching values for the given list items return [self.get_value(v,key[i:]) for v in value] else: value = value[elem] return value
python
def get_value(self, attributes,key = None): """Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object """ value = attributes if key is None: key = self._splitted_key # A splitted key like 'a.b.c' goes into nested properties # and the value is retrieved recursively for i,elem in enumerate(key): if isinstance(value, (list,tuple)): #if this is a list, we return all matching values for the given list items return [self.get_value(v,key[i:]) for v in value] else: value = value[elem] return value
[ "def", "get_value", "(", "self", ",", "attributes", ",", "key", "=", "None", ")", ":", "value", "=", "attributes", "if", "key", "is", "None", ":", "key", "=", "self", ".", "_splitted_key", "# A splitted key like 'a.b.c' goes into nested properties", "# and the value is retrieved recursively", "for", "i", ",", "elem", "in", "enumerate", "(", "key", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "#if this is a list, we return all matching values for the given list items", "return", "[", "self", ".", "get_value", "(", "v", ",", "key", "[", "i", ":", "]", ")", "for", "v", "in", "value", "]", "else", ":", "value", "=", "value", "[", "elem", "]", "return", "value" ]
Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object
[ "Get", "value", "to", "be", "indexed", "from", "document", "attributes", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L74-L97
adewes/blitzdb
blitzdb/backends/file/index.py
Index.save_to_store
def save_to_store(self): """Save index to store. :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') saved_data = self.save_to_data(in_place=True) data = Serializer.serialize(saved_data) self._store.store_blob(data, 'all_keys_with_undefined')
python
def save_to_store(self): """Save index to store. :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') saved_data = self.save_to_data(in_place=True) data = Serializer.serialize(saved_data) self._store.store_blob(data, 'all_keys_with_undefined')
[ "def", "save_to_store", "(", "self", ")", ":", "if", "not", "self", ".", "_store", ":", "raise", "AttributeError", "(", "'No datastore defined!'", ")", "saved_data", "=", "self", ".", "save_to_data", "(", "in_place", "=", "True", ")", "data", "=", "Serializer", ".", "serialize", "(", "saved_data", ")", "self", ".", "_store", ".", "store_blob", "(", "data", ",", "'all_keys_with_undefined'", ")" ]
Save index to store. :raise AttributeError: If no datastore is defined
[ "Save", "index", "to", "store", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L99-L109
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_all_keys
def get_all_keys(self): """Get all keys indexed. :return: All keys :rtype: list(str) """ all_keys = [] for keys in self._index.values(): all_keys.extend(keys) return all_keys
python
def get_all_keys(self): """Get all keys indexed. :return: All keys :rtype: list(str) """ all_keys = [] for keys in self._index.values(): all_keys.extend(keys) return all_keys
[ "def", "get_all_keys", "(", "self", ")", ":", "all_keys", "=", "[", "]", "for", "keys", "in", "self", ".", "_index", ".", "values", "(", ")", ":", "all_keys", ".", "extend", "(", "keys", ")", "return", "all_keys" ]
Get all keys indexed. :return: All keys :rtype: list(str)
[ "Get", "all", "keys", "indexed", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L111-L121
adewes/blitzdb
blitzdb/backends/file/index.py
Index.load_from_store
def load_from_store(self): """Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') if self._store.has_blob('all_keys'): data = Serializer.deserialize(self._store.get_blob('all_keys')) self.load_from_data(data) return True elif self._store.has_blob('all_keys_with_undefined'): blob = self._store.get_blob('all_keys_with_undefined') data = Serializer.deserialize(blob) self.load_from_data(data, with_undefined=True) return True else: return False
python
def load_from_store(self): """Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') if self._store.has_blob('all_keys'): data = Serializer.deserialize(self._store.get_blob('all_keys')) self.load_from_data(data) return True elif self._store.has_blob('all_keys_with_undefined'): blob = self._store.get_blob('all_keys_with_undefined') data = Serializer.deserialize(blob) self.load_from_data(data, with_undefined=True) return True else: return False
[ "def", "load_from_store", "(", "self", ")", ":", "if", "not", "self", ".", "_store", ":", "raise", "AttributeError", "(", "'No datastore defined!'", ")", "if", "self", ".", "_store", ".", "has_blob", "(", "'all_keys'", ")", ":", "data", "=", "Serializer", ".", "deserialize", "(", "self", ".", "_store", ".", "get_blob", "(", "'all_keys'", ")", ")", "self", ".", "load_from_data", "(", "data", ")", "return", "True", "elif", "self", ".", "_store", ".", "has_blob", "(", "'all_keys_with_undefined'", ")", ":", "blob", "=", "self", ".", "_store", ".", "get_blob", "(", "'all_keys_with_undefined'", ")", "data", "=", "Serializer", ".", "deserialize", "(", "blob", ")", "self", ".", "load_from_data", "(", "data", ",", "with_undefined", "=", "True", ")", "return", "True", "else", ":", "return", "False" ]
Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined
[ "Load", "index", "from", "store", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L132-L152
adewes/blitzdb
blitzdb/backends/file/index.py
Index.sort_keys
def sort_keys(self, keys, order=QuerySet.ASCENDING): """Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted keys :rtype: list(str) :raise ValueError: If invalid order value is passed """ # to do: check that all reverse index values are unambiguous missing_keys = [ key for key in keys if not len(self._reverse_index[key]) ] keys_and_values = [ (key, self._reverse_index[key][0]) for key in keys if key not in missing_keys ] sorted_keys = [ kv[0] for kv in sorted( keys_and_values, key=lambda x: x[1], reverse=True if order == QuerySet.DESCENDING else False) ] if order == QuerySet.ASCENDING: return missing_keys + sorted_keys elif order == QuerySet.DESCENDING: return sorted_keys + missing_keys else: raise ValueError('Unexpected order value: {:d}'.format(order))
python
def sort_keys(self, keys, order=QuerySet.ASCENDING): """Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted keys :rtype: list(str) :raise ValueError: If invalid order value is passed """ # to do: check that all reverse index values are unambiguous missing_keys = [ key for key in keys if not len(self._reverse_index[key]) ] keys_and_values = [ (key, self._reverse_index[key][0]) for key in keys if key not in missing_keys ] sorted_keys = [ kv[0] for kv in sorted( keys_and_values, key=lambda x: x[1], reverse=True if order == QuerySet.DESCENDING else False) ] if order == QuerySet.ASCENDING: return missing_keys + sorted_keys elif order == QuerySet.DESCENDING: return sorted_keys + missing_keys else: raise ValueError('Unexpected order value: {:d}'.format(order))
[ "def", "sort_keys", "(", "self", ",", "keys", ",", "order", "=", "QuerySet", ".", "ASCENDING", ")", ":", "# to do: check that all reverse index values are unambiguous", "missing_keys", "=", "[", "key", "for", "key", "in", "keys", "if", "not", "len", "(", "self", ".", "_reverse_index", "[", "key", "]", ")", "]", "keys_and_values", "=", "[", "(", "key", ",", "self", ".", "_reverse_index", "[", "key", "]", "[", "0", "]", ")", "for", "key", "in", "keys", "if", "key", "not", "in", "missing_keys", "]", "sorted_keys", "=", "[", "kv", "[", "0", "]", "for", "kv", "in", "sorted", "(", "keys_and_values", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", "if", "order", "==", "QuerySet", ".", "DESCENDING", "else", "False", ")", "]", "if", "order", "==", "QuerySet", ".", "ASCENDING", ":", "return", "missing_keys", "+", "sorted_keys", "elif", "order", "==", "QuerySet", ".", "DESCENDING", ":", "return", "sorted_keys", "+", "missing_keys", "else", ":", "raise", "ValueError", "(", "'Unexpected order value: {:d}'", ".", "format", "(", "order", ")", ")" ]
Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted keys :rtype: list(str) :raise ValueError: If invalid order value is passed
[ "Sort", "keys", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L154-L191
adewes/blitzdb
blitzdb/backends/file/index.py
Index.save_to_data
def save_to_data(self, in_place=False): """Save index to data structure. :param in_place: Do not copy index value to a new list object :type in_place: bool :return: Index data structure :rtype: list """ if in_place: return [ list(self._index.items()), list(self._undefined_keys.keys()) ] return ( [(key, values[:]) for key, values in self._index.items()], list(self._undefined_keys.keys()), )
python
def save_to_data(self, in_place=False): """Save index to data structure. :param in_place: Do not copy index value to a new list object :type in_place: bool :return: Index data structure :rtype: list """ if in_place: return [ list(self._index.items()), list(self._undefined_keys.keys()) ] return ( [(key, values[:]) for key, values in self._index.items()], list(self._undefined_keys.keys()), )
[ "def", "save_to_data", "(", "self", ",", "in_place", "=", "False", ")", ":", "if", "in_place", ":", "return", "[", "list", "(", "self", ".", "_index", ".", "items", "(", ")", ")", ",", "list", "(", "self", ".", "_undefined_keys", ".", "keys", "(", ")", ")", "]", "return", "(", "[", "(", "key", ",", "values", "[", ":", "]", ")", "for", "key", ",", "values", "in", "self", ".", "_index", ".", "items", "(", ")", "]", ",", "list", "(", "self", ".", "_undefined_keys", ".", "keys", "(", ")", ")", ",", ")" ]
Save index to data structure. :param in_place: Do not copy index value to a new list object :type in_place: bool :return: Index data structure :rtype: list
[ "Save", "index", "to", "data", "structure", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L193-L210
adewes/blitzdb
blitzdb/backends/file/index.py
Index.load_from_data
def load_from_data(self, data, with_undefined=False): """Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool """ if with_undefined: defined_values, undefined_values = data else: defined_values = data undefined_values = None self._index = defaultdict(list, defined_values) self._reverse_index = defaultdict(list) for key, values in self._index.items(): for value in values: self._reverse_index[value].append(key) if undefined_values: self._undefined_keys = {key: True for key in undefined_values} else: self._undefined_keys = {}
python
def load_from_data(self, data, with_undefined=False): """Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool """ if with_undefined: defined_values, undefined_values = data else: defined_values = data undefined_values = None self._index = defaultdict(list, defined_values) self._reverse_index = defaultdict(list) for key, values in self._index.items(): for value in values: self._reverse_index[value].append(key) if undefined_values: self._undefined_keys = {key: True for key in undefined_values} else: self._undefined_keys = {}
[ "def", "load_from_data", "(", "self", ",", "data", ",", "with_undefined", "=", "False", ")", ":", "if", "with_undefined", ":", "defined_values", ",", "undefined_values", "=", "data", "else", ":", "defined_values", "=", "data", "undefined_values", "=", "None", "self", ".", "_index", "=", "defaultdict", "(", "list", ",", "defined_values", ")", "self", ".", "_reverse_index", "=", "defaultdict", "(", "list", ")", "for", "key", ",", "values", "in", "self", ".", "_index", ".", "items", "(", ")", ":", "for", "value", "in", "values", ":", "self", ".", "_reverse_index", "[", "value", "]", ".", "append", "(", "key", ")", "if", "undefined_values", ":", "self", ".", "_undefined_keys", "=", "{", "key", ":", "True", "for", "key", "in", "undefined_values", "}", "else", ":", "self", ".", "_undefined_keys", "=", "{", "}" ]
Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool
[ "Load", "index", "structure", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L212-L232
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_hash_for
def get_hash_for(self, value): """Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str """ if isinstance(value,dict) and '__ref__' in value: return self.get_hash_for(value['__ref__']) serialized_value = self._serializer(value) if isinstance(serialized_value, dict): # Hash each item and return the hash of all the hashes return hash(frozenset([ self.get_hash_for(x) for x in serialized_value.items() ])) elif isinstance(serialized_value, (list,tuple)): # Hash each element and return the hash of all the hashes return hash(tuple([ self.get_hash_for(x) for x in serialized_value ])) return value
python
def get_hash_for(self, value): """Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str """ if isinstance(value,dict) and '__ref__' in value: return self.get_hash_for(value['__ref__']) serialized_value = self._serializer(value) if isinstance(serialized_value, dict): # Hash each item and return the hash of all the hashes return hash(frozenset([ self.get_hash_for(x) for x in serialized_value.items() ])) elif isinstance(serialized_value, (list,tuple)): # Hash each element and return the hash of all the hashes return hash(tuple([ self.get_hash_for(x) for x in serialized_value ])) return value
[ "def", "get_hash_for", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "'__ref__'", "in", "value", ":", "return", "self", ".", "get_hash_for", "(", "value", "[", "'__ref__'", "]", ")", "serialized_value", "=", "self", ".", "_serializer", "(", "value", ")", "if", "isinstance", "(", "serialized_value", ",", "dict", ")", ":", "# Hash each item and return the hash of all the hashes", "return", "hash", "(", "frozenset", "(", "[", "self", ".", "get_hash_for", "(", "x", ")", "for", "x", "in", "serialized_value", ".", "items", "(", ")", "]", ")", ")", "elif", "isinstance", "(", "serialized_value", ",", "(", "list", ",", "tuple", ")", ")", ":", "# Hash each element and return the hash of all the hashes", "return", "hash", "(", "tuple", "(", "[", "self", ".", "get_hash_for", "(", "x", ")", "for", "x", "in", "serialized_value", "]", ")", ")", "return", "value" ]
Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str
[ "Get", "hash", "for", "a", "given", "value", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L234-L257
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_keys_for
def get_keys_for(self, value): """Get keys for a given value. :param value: The value to look for :type value: object :return: The keys for the given value :rtype: list(str) """ if callable(value): return value(self) hash_value = self.get_hash_for(value) return self._index[hash_value][:]
python
def get_keys_for(self, value): """Get keys for a given value. :param value: The value to look for :type value: object :return: The keys for the given value :rtype: list(str) """ if callable(value): return value(self) hash_value = self.get_hash_for(value) return self._index[hash_value][:]
[ "def", "get_keys_for", "(", "self", ",", "value", ")", ":", "if", "callable", "(", "value", ")", ":", "return", "value", "(", "self", ")", "hash_value", "=", "self", ".", "get_hash_for", "(", "value", ")", "return", "self", ".", "_index", "[", "hash_value", "]", "[", ":", "]" ]
Get keys for a given value. :param value: The value to look for :type value: object :return: The keys for the given value :rtype: list(str)
[ "Get", "keys", "for", "a", "given", "value", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L259-L271
adewes/blitzdb
blitzdb/backends/file/index.py
Index.add_hashed_value
def add_hashed_value(self, hash_value, store_key): """Add hashed value to the index. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object """ if self._unique and hash_value in self._index: raise NonUnique('Hash value {} already in index'.format(hash_value)) if store_key not in self._index[hash_value]: self._index[hash_value].append(store_key) if hash_value not in self._reverse_index[store_key]: self._reverse_index[store_key].append(hash_value)
python
def add_hashed_value(self, hash_value, store_key): """Add hashed value to the index. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object """ if self._unique and hash_value in self._index: raise NonUnique('Hash value {} already in index'.format(hash_value)) if store_key not in self._index[hash_value]: self._index[hash_value].append(store_key) if hash_value not in self._reverse_index[store_key]: self._reverse_index[store_key].append(hash_value)
[ "def", "add_hashed_value", "(", "self", ",", "hash_value", ",", "store_key", ")", ":", "if", "self", ".", "_unique", "and", "hash_value", "in", "self", ".", "_index", ":", "raise", "NonUnique", "(", "'Hash value {} already in index'", ".", "format", "(", "hash_value", ")", ")", "if", "store_key", "not", "in", "self", ".", "_index", "[", "hash_value", "]", ":", "self", ".", "_index", "[", "hash_value", "]", ".", "append", "(", "store_key", ")", "if", "hash_value", "not", "in", "self", ".", "_reverse_index", "[", "store_key", "]", ":", "self", ".", "_reverse_index", "[", "store_key", "]", ".", "append", "(", "hash_value", ")" ]
Add hashed value to the index. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object
[ "Add", "hashed", "value", "to", "the", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L284-L298
adewes/blitzdb
blitzdb/backends/file/index.py
Index.add_key
def add_key(self, attributes, store_key): """Add key to the index. :param attributes: Attributes to be added to the index :type attributes: dict(str) :param store_key: The key for the document in the store :type store_key: str """ undefined = False try: value = self.get_value(attributes) except (KeyError, IndexError): undefined = True # We remove old values in _reverse_index self.remove_key(store_key) if not undefined: if isinstance(value, (list,tuple)): # We add an extra hash value for the list itself # (this allows for querying the whole list) values = value hash_value = self.get_hash_for(value) self.add_hashed_value(hash_value, store_key) else: values = [value] for value in values: hash_value = self.get_hash_for(value) self.add_hashed_value(hash_value, store_key) else: self.add_undefined(store_key)
python
def add_key(self, attributes, store_key): """Add key to the index. :param attributes: Attributes to be added to the index :type attributes: dict(str) :param store_key: The key for the document in the store :type store_key: str """ undefined = False try: value = self.get_value(attributes) except (KeyError, IndexError): undefined = True # We remove old values in _reverse_index self.remove_key(store_key) if not undefined: if isinstance(value, (list,tuple)): # We add an extra hash value for the list itself # (this allows for querying the whole list) values = value hash_value = self.get_hash_for(value) self.add_hashed_value(hash_value, store_key) else: values = [value] for value in values: hash_value = self.get_hash_for(value) self.add_hashed_value(hash_value, store_key) else: self.add_undefined(store_key)
[ "def", "add_key", "(", "self", ",", "attributes", ",", "store_key", ")", ":", "undefined", "=", "False", "try", ":", "value", "=", "self", ".", "get_value", "(", "attributes", ")", "except", "(", "KeyError", ",", "IndexError", ")", ":", "undefined", "=", "True", "# We remove old values in _reverse_index", "self", ".", "remove_key", "(", "store_key", ")", "if", "not", "undefined", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "# We add an extra hash value for the list itself", "# (this allows for querying the whole list)", "values", "=", "value", "hash_value", "=", "self", ".", "get_hash_for", "(", "value", ")", "self", ".", "add_hashed_value", "(", "hash_value", ",", "store_key", ")", "else", ":", "values", "=", "[", "value", "]", "for", "value", "in", "values", ":", "hash_value", "=", "self", ".", "get_hash_for", "(", "value", ")", "self", ".", "add_hashed_value", "(", "hash_value", ",", "store_key", ")", "else", ":", "self", ".", "add_undefined", "(", "store_key", ")" ]
Add key to the index. :param attributes: Attributes to be added to the index :type attributes: dict(str) :param store_key: The key for the document in the store :type store_key: str
[ "Add", "key", "to", "the", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L300-L331
adewes/blitzdb
blitzdb/backends/file/index.py
Index.remove_key
def remove_key(self, store_key): """Remove key from the index. :param store_key: The key for the document in the store :type store_key: str """ if store_key in self._undefined_keys: del self._undefined_keys[store_key] if store_key in self._reverse_index: for value in self._reverse_index[store_key]: self._index[value].remove(store_key) del self._reverse_index[store_key]
python
def remove_key(self, store_key): """Remove key from the index. :param store_key: The key for the document in the store :type store_key: str """ if store_key in self._undefined_keys: del self._undefined_keys[store_key] if store_key in self._reverse_index: for value in self._reverse_index[store_key]: self._index[value].remove(store_key) del self._reverse_index[store_key]
[ "def", "remove_key", "(", "self", ",", "store_key", ")", ":", "if", "store_key", "in", "self", ".", "_undefined_keys", ":", "del", "self", ".", "_undefined_keys", "[", "store_key", "]", "if", "store_key", "in", "self", ".", "_reverse_index", ":", "for", "value", "in", "self", ".", "_reverse_index", "[", "store_key", "]", ":", "self", ".", "_index", "[", "value", "]", ".", "remove", "(", "store_key", ")", "del", "self", ".", "_reverse_index", "[", "store_key", "]" ]
Remove key from the index. :param store_key: The key for the document in the store :type store_key: str
[ "Remove", "key", "from", "the", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L342-L354
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex._init_cache
def _init_cache(self): """Initialize cache.""" self._add_cache = defaultdict(list) self._reverse_add_cache = defaultdict(list) self._undefined_cache = {} self._remove_cache = {}
python
def _init_cache(self): """Initialize cache.""" self._add_cache = defaultdict(list) self._reverse_add_cache = defaultdict(list) self._undefined_cache = {} self._remove_cache = {}
[ "def", "_init_cache", "(", "self", ")", ":", "self", ".", "_add_cache", "=", "defaultdict", "(", "list", ")", "self", ".", "_reverse_add_cache", "=", "defaultdict", "(", "list", ")", "self", ".", "_undefined_cache", "=", "{", "}", "self", ".", "_remove_cache", "=", "{", "}" ]
Initialize cache.
[ "Initialize", "cache", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L371-L376
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.commit
def commit(self): """Commit current transaction.""" if (not self._add_cache and not self._remove_cache and not self._undefined_cache): return for store_key, hash_values in self._add_cache.items(): for hash_value in hash_values: super(TransactionalIndex, self).add_hashed_value( hash_value, store_key) for store_key in self._remove_cache: super(TransactionalIndex, self).remove_key(store_key) for store_key in self._undefined_cache: super(TransactionalIndex, self).add_undefined(store_key) if not self.ephemeral: self.save_to_store() self._init_cache() self._in_transaction = True
python
def commit(self): """Commit current transaction.""" if (not self._add_cache and not self._remove_cache and not self._undefined_cache): return for store_key, hash_values in self._add_cache.items(): for hash_value in hash_values: super(TransactionalIndex, self).add_hashed_value( hash_value, store_key) for store_key in self._remove_cache: super(TransactionalIndex, self).remove_key(store_key) for store_key in self._undefined_cache: super(TransactionalIndex, self).add_undefined(store_key) if not self.ephemeral: self.save_to_store() self._init_cache() self._in_transaction = True
[ "def", "commit", "(", "self", ")", ":", "if", "(", "not", "self", ".", "_add_cache", "and", "not", "self", ".", "_remove_cache", "and", "not", "self", ".", "_undefined_cache", ")", ":", "return", "for", "store_key", ",", "hash_values", "in", "self", ".", "_add_cache", ".", "items", "(", ")", ":", "for", "hash_value", "in", "hash_values", ":", "super", "(", "TransactionalIndex", ",", "self", ")", ".", "add_hashed_value", "(", "hash_value", ",", "store_key", ")", "for", "store_key", "in", "self", ".", "_remove_cache", ":", "super", "(", "TransactionalIndex", ",", "self", ")", ".", "remove_key", "(", "store_key", ")", "for", "store_key", "in", "self", ".", "_undefined_cache", ":", "super", "(", "TransactionalIndex", ",", "self", ")", ".", "add_undefined", "(", "store_key", ")", "if", "not", "self", ".", "ephemeral", ":", "self", ".", "save_to_store", "(", ")", "self", ".", "_init_cache", "(", ")", "self", ".", "_in_transaction", "=", "True" ]
Commit current transaction.
[ "Commit", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L386-L405
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.rollback
def rollback(self): """Drop changes from current transaction.""" if not self._in_transaction: raise NotInTransaction self._init_cache() self._in_transaction = False
python
def rollback(self): """Drop changes from current transaction.""" if not self._in_transaction: raise NotInTransaction self._init_cache() self._in_transaction = False
[ "def", "rollback", "(", "self", ")", ":", "if", "not", "self", ".", "_in_transaction", ":", "raise", "NotInTransaction", "self", ".", "_init_cache", "(", ")", "self", ".", "_in_transaction", "=", "False" ]
Drop changes from current transaction.
[ "Drop", "changes", "from", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L407-L412
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.add_hashed_value
def add_hashed_value(self, hash_value, store_key): """Add hashed value in the context of the current transaction. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object """ if hash_value not in self._add_cache[store_key]: self._add_cache[store_key].append(hash_value) if store_key not in self._reverse_add_cache[hash_value]: self._reverse_add_cache[hash_value].append(store_key) if store_key in self._remove_cache: del self._remove_cache[store_key] if store_key in self._undefined_cache: del self._undefined_cache[store_key]
python
def add_hashed_value(self, hash_value, store_key): """Add hashed value in the context of the current transaction. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object """ if hash_value not in self._add_cache[store_key]: self._add_cache[store_key].append(hash_value) if store_key not in self._reverse_add_cache[hash_value]: self._reverse_add_cache[hash_value].append(store_key) if store_key in self._remove_cache: del self._remove_cache[store_key] if store_key in self._undefined_cache: del self._undefined_cache[store_key]
[ "def", "add_hashed_value", "(", "self", ",", "hash_value", ",", "store_key", ")", ":", "if", "hash_value", "not", "in", "self", ".", "_add_cache", "[", "store_key", "]", ":", "self", ".", "_add_cache", "[", "store_key", "]", ".", "append", "(", "hash_value", ")", "if", "store_key", "not", "in", "self", ".", "_reverse_add_cache", "[", "hash_value", "]", ":", "self", ".", "_reverse_add_cache", "[", "hash_value", "]", ".", "append", "(", "store_key", ")", "if", "store_key", "in", "self", ".", "_remove_cache", ":", "del", "self", ".", "_remove_cache", "[", "store_key", "]", "if", "store_key", "in", "self", ".", "_undefined_cache", ":", "del", "self", ".", "_undefined_cache", "[", "store_key", "]" ]
Add hashed value in the context of the current transaction. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object
[ "Add", "hashed", "value", "in", "the", "context", "of", "the", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L424-L440
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.remove_key
def remove_key(self, store_key): """Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str """ self._remove_cache[store_key] = True if store_key in self._add_cache: for hash_value in self._add_cache[store_key]: self._reverse_add_cache[hash_value].remove(store_key) del self._add_cache[store_key] if store_key in self._undefined_cache: del self._undefined_cache[store_key]
python
def remove_key(self, store_key): """Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str """ self._remove_cache[store_key] = True if store_key in self._add_cache: for hash_value in self._add_cache[store_key]: self._reverse_add_cache[hash_value].remove(store_key) del self._add_cache[store_key] if store_key in self._undefined_cache: del self._undefined_cache[store_key]
[ "def", "remove_key", "(", "self", ",", "store_key", ")", ":", "self", ".", "_remove_cache", "[", "store_key", "]", "=", "True", "if", "store_key", "in", "self", ".", "_add_cache", ":", "for", "hash_value", "in", "self", ".", "_add_cache", "[", "store_key", "]", ":", "self", ".", "_reverse_add_cache", "[", "hash_value", "]", ".", "remove", "(", "store_key", ")", "del", "self", ".", "_add_cache", "[", "store_key", "]", "if", "store_key", "in", "self", ".", "_undefined_cache", ":", "del", "self", ".", "_undefined_cache", "[", "store_key", "]" ]
Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str
[ "Remove", "key", "in", "the", "context", "of", "the", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L442-L455
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.get_keys_for
def get_keys_for(self, value, include_uncommitted=False): """Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the given value :rtype: list(str) """ if not include_uncommitted: return super(TransactionalIndex, self).get_keys_for(value) else: keys = super(TransactionalIndex, self).get_keys_for(value) hash_value = self.get_hash_for(value) keys += self._reverse_add_cache[hash_value] return keys
python
def get_keys_for(self, value, include_uncommitted=False): """Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the given value :rtype: list(str) """ if not include_uncommitted: return super(TransactionalIndex, self).get_keys_for(value) else: keys = super(TransactionalIndex, self).get_keys_for(value) hash_value = self.get_hash_for(value) keys += self._reverse_add_cache[hash_value] return keys
[ "def", "get_keys_for", "(", "self", ",", "value", ",", "include_uncommitted", "=", "False", ")", ":", "if", "not", "include_uncommitted", ":", "return", "super", "(", "TransactionalIndex", ",", "self", ")", ".", "get_keys_for", "(", "value", ")", "else", ":", "keys", "=", "super", "(", "TransactionalIndex", ",", "self", ")", ".", "get_keys_for", "(", "value", ")", "hash_value", "=", "self", ".", "get_hash_for", "(", "value", ")", "keys", "+=", "self", ".", "_reverse_add_cache", "[", "hash_value", "]", "return", "keys" ]
Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the given value :rtype: list(str)
[ "Get", "keys", "for", "a", "given", "value", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L457-L474
adewes/blitzdb
blitzdb/backends/sql/backend.py
Backend.filter
def filter(self, cls_or_collection, query, raw = False,only = None,include = None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports all query operators that are available in SQLAlchemy and returns a query set that is based on a SQLAlchemy cursor. """ if not isinstance(cls_or_collection, six.string_types): collection = self.get_collection_for_cls(cls_or_collection) cls = cls_or_collection else: collection = cls_or_collection cls = self.get_cls_for_collection(collection) table = self._collection_tables[collection] joins = defaultdict(dict) joins_list = [] group_bys = [] havings = [] def compile_query(collection,query,table = None,path = None): if path is None: path = [] """ This function emits a list of WHERE statements that can be used to retrieve """ if table is None: table = self._collection_tables[collection] where_statements = [] if any([True if key.startswith('$') else False for key in query.keys()]): #this is a special operator query if len(query) > 1: raise AttributeError('Currently not supported!') operator = list(query.keys())[0][1:] if not operator in ('and','or','not'): raise AttributeError("Non-supported logical operator: $%s" % operator) if operator in ('and','or'): where_statements = [sq for expr in query['$%s' % operator] for sq in compile_query(collection,expr,path = path)] if operator == 'and': return [and_(*where_statements)] else: return [or_(*where_statements)] elif operator == 'not': return [not_(*compile_query(collection,query['$not'],table = table,path = path))] def compile_one_to_many_query(key,query,field_name,related_table,count_column,path): def prepare_subquery(tail,query_dict): d = {} if not tail: if isinstance(query_dict,dict): return query_dict.copy() if not isinstance(query_dict,Document): raise AttributeError("Must be a document!") if not query_dict.pk: raise AttributeError("Performing a query without a primary key!") return {'pk' : query_dict.pk} return {tail : query_dict} tail = key[len(field_name)+1:] if isinstance(query,Document) and not tail: query = {'pk' : query.pk} #to do: implement $size and $not: {$size} operators... if isinstance(query,dict) and len(query) == 1 and list(query.keys())[0] in ('$all','$in','$elemMatch','$nin'): #this is an $in/$all/$nin query query_type = list(query.keys())[0][1:] subquery = list(query.values())[0] if query_type == 'elemMatch': queries = compile_query(params['collection'], prepare_subquery(tail,query['$elemMatch']), table = related_table, path = path) return queries else: if isinstance(subquery,(ManyToManyProxy,QuerySet)): if tail: #this query has a tail query = {tail : query} queries = compile_query(params['collection'],query, table = related_table, path = path) return queries #this is a query with a ManyToManyProxy/QuerySet if isinstance(subquery,ManyToManyProxy): qs = subquery.get_queryset() else: qs = subquery if not query_type in ('in','nin','all'): raise AttributeError if query_type == 'all': op = 'in' else: op = query_type if query_type == 'all': cnt = func.count(count_column) condition = cnt == qs.get_count_select() havings.append(condition) return [getattr(related_table.c['pk'],op+'_')(qs.get_select(columns = ['pk']))] elif isinstance(subquery,(list,tuple)): if subquery and isinstance(subquery[0],dict) and len(subquery[0]) == 1 and \ list(subquery[0].keys())[0] == '$elemMatch': queries = [sq for v in subquery for sq in compile_query(params['collection'], prepare_subquery(tail,v['$elemMatch']), table = related_table, path = path)] else: queries = [sq for v in subquery for sq in compile_query(params['collection'], prepare_subquery(tail,v), table = related_table, path = path)] where_statement = or_(*queries) if query_type == 'nin': where_statement = not_(where_statement) if query_type == 'all' and len(queries) > 1: cnt = func.count(count_column) havings.append(cnt == len(queries)) return [where_statement] else: raise AttributeError("$in/$nin/$all query requires a list/tuple/QuerySet/ManyToManyProxy") else: return compile_query(params['collection'],prepare_subquery(tail,query), table = related_table, path = path) def compile_many_to_many_query(key,value,field_name,params,relationship_table,path): related_collection = params['collection'] related_table = self._collection_tables[related_collection] path_str = ".".join(path) if path_str in joins[relationship_table]: relationship_table_alias = joins[relationship_table][path_str] else: relationship_table_alias = relationship_table.alias() joins[relationship_table][path_str] = relationship_table_alias joins_list.append((relationship_table_alias, relationship_table_alias.c[params['pk_field_name']] == table.c['pk'])) if path_str in joins[related_table]: related_table_alias = joins[related_table][path_str] else: related_table_alias = related_table.alias() joins[related_table][path_str] = related_table_alias joins_list.append((related_table_alias,relationship_table_alias.c[params['related_pk_field_name']] == related_table_alias.c['pk'])) return compile_one_to_many_query(key,value,field_name,related_table_alias,relationship_table_alias.c[params['pk_field_name']],new_path) def prepare_special_query(field_name,params,query): def sanitize(value): if isinstance(value,(list,tuple)): return [v.pk if isinstance(v,Document) else v for v in value] return value column_name = params['column'] if '$not' in query: return [not_(*prepare_special_query(column_name,params,sanitize(query['$not'])))] elif '$in' in query: if not query['$in']: #we return an impossible condition since the $in query does not contain any values return [expression.cast(True,Boolean) == expression.cast(False,Boolean)] return [table.c[column_name].in_(sanitize(query['$in']))] elif '$nin' in query: if not query['$nin']: return [expression.cast(True,Boolean) == expression.cast(False,Boolean)] return [~table.c[column_name].in_(sanitize(query['$nin']))] elif '$eq' in query: return [table.c[column_name] == sanitize(query['$eq'])] elif '$ne' in query: return [table.c[column_name] != sanitize(query['$ne'])] elif '$gt' in query: return [table.c[column_name] > sanitize(query['$gt'])] elif '$gte' in query: return [table.c[column_name] >= sanitize(query['$gte'])] elif '$lt' in query: return [table.c[column_name] < sanitize(query['$lt'])] elif '$lte' in query: return [table.c[column_name] <= sanitize(query['$lte'])] elif '$exists' in query: if query['$exists']: return [table.c[column_name] != None] else: return [table.c[column_name] == None] elif '$like' in query: return [table.c[column_name].like(expression.cast(query['$like'],String))] elif '$ilike' in query: return [table.c[column_name].ilike(expression.cast(query['$ilike'],String))] elif '$regex' in query: if not self.engine.url.drivername in ('postgres','mysql','sqlite'): raise AttributeError("Regex queries not supported with %s engine!" % self.engine.url.drivername) return [table.c[column_name].op('REGEXP')(expression.cast(query['$regex'],String))] else: raise AttributeError("Invalid query!") #this is a normal, field-base query for key,value in query.items(): for field_name,params in self._index_fields[collection].items(): if key == field_name: if isinstance(value,re._pattern_type): value = {'$regex' : value.pattern} if isinstance(value,dict): #this is a special query where_statements.extend(prepare_special_query(field_name,params,value)) else: #this is a normal value query where_statements.append(table.c[params['column']] == expression.cast(value,params['type'])) break else: #we check the normal relationships for field_name,params in self._related_fields[collection].items(): if key.startswith(field_name): head,tail = key[:len(field_name)],key[len(field_name)+1:] new_path = path + [head] path_str = ".".join(new_path) #ManyToManyField if isinstance(params['field'],ManyToManyField): relationship_table = self._relationship_tables[collection][field_name] where_statements.extend(compile_many_to_many_query(key,value,field_name,params,relationship_table,path = new_path)) elif isinstance(params['field'],ForeignKeyField):#this is a normal ForeignKey relation if key == field_name: #this is a ForeignKey query if isinstance(value,dict): if len(value) == 1: key,query = list(value.items())[0] if key == '$exists': if not isinstance(query,bool): raise AttributeError("$exists operator requires a Boolean operator") if query: where_statements.append(table.c[params['column']] != None) else: where_statements.append(table.c[params['column']] == None) break elif not key in ('$in','$nin'): raise AttributeError("Invalid query!") query_type = key[1:] else: raise AttributeError("Invalid query!") else: query_type = 'exact' query = value if isinstance(query,(QuerySet,ManyToManyProxy)): if not query_type in ('in','nin'): raise AttributeError("QuerySet/ManyToManyProxy objects must be used in conjunction with $in/$nin when querying a ForeignKey relationship") if isinstance(query,ManyToManyProxy): qs = query.get_queryset() else: qs = query if qs.count is not None and qs.count == 0: raise AttributeError("$in/$nin query with empty QuerySet/ManyToManyProxy!") if qs.cls is not params['class']: raise AttributeError("Invalid QuerySet class!") condition = getattr(table.c[params['column']],query_type+'_')(qs.get_select(columns = ['pk'])) where_statements.append(condition) elif isinstance(query,(list,tuple)): if not query_type in ('in','nin'): raise AttributeError("Lists/tuples must be used in conjunction with $in/$nin when querying a ForeignKey relationship") if not query: raise AttributeError("in/nin query with empty list!") if query[0].__class__ is params['class']: if any((element.__class__ is not params['class'] for element in query)): raise AttributeError("Invalid document type in ForeignKey query") where_statements.append(getattr(table.c[params['column']],query_type+'_')([expression.cast(doc.pk,params['type']) for doc in query])) else: where_statements.append(getattr(table.c[params['column']],query_type+'_')([expression.cast(element,params['type']) for element in query])) elif isinstance(query,Document): #we need an exact clas match here... if query.__class__ is not params['class']: raise AttributeError("Invalid Document class!") where_statements.append(table.c[params['column']] == query.pk) else: where_statements.append(table.c[params['column']] == expression.cast(query,params['class'].Meta.PkType)) else: #we query a sub-field of the relation related_table = self._collection_tables[params['collection']] if path_str in joins[related_table]: related_table_alias = joins[related_table][path_str] else: related_table_alias = related_table.alias() joins[related_table][path_str] = related_table_alias joins_list.append((related_table_alias,table.c[params['column']] == related_table_alias.c['pk'])) where_statements.extend(compile_query(params['collection'],{tail : value},table = related_table_alias,path = new_path)) elif isinstance(params['field'],OneToManyField): related_table = self._collection_tables[params['collection']] if path_str in joins[related_table]: related_table_alias = joins[related_table][path_str] else: related_table_alias = related_table.alias() joins[related_table][path_str] = related_table_alias joins_list.append((related_table_alias,related_table_alias.c[params['backref']['column']] == table.c['pk'])) where_statements.extend(compile_one_to_many_query(key,value,field_name,related_table_alias,table.c.pk,new_path)) break else: raise AttributeError("Query over non-indexed field %s in collection %s!" % (key,collection)) return where_statements compiled_query = compile_query(collection,query) if len(compiled_query) > 1: compiled_query = and_(*compiled_query) elif compiled_query: compiled_query = compiled_query[0] else: compiled_query = None return QuerySet(backend = self, table = table, joins = joins_list, cls = cls, condition = compiled_query, raw = raw, group_bys = group_bys, only = only, include = include, havings = havings )
python
def filter(self, cls_or_collection, query, raw = False,only = None,include = None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports all query operators that are available in SQLAlchemy and returns a query set that is based on a SQLAlchemy cursor. """ if not isinstance(cls_or_collection, six.string_types): collection = self.get_collection_for_cls(cls_or_collection) cls = cls_or_collection else: collection = cls_or_collection cls = self.get_cls_for_collection(collection) table = self._collection_tables[collection] joins = defaultdict(dict) joins_list = [] group_bys = [] havings = [] def compile_query(collection,query,table = None,path = None): if path is None: path = [] """ This function emits a list of WHERE statements that can be used to retrieve """ if table is None: table = self._collection_tables[collection] where_statements = [] if any([True if key.startswith('$') else False for key in query.keys()]): #this is a special operator query if len(query) > 1: raise AttributeError('Currently not supported!') operator = list(query.keys())[0][1:] if not operator in ('and','or','not'): raise AttributeError("Non-supported logical operator: $%s" % operator) if operator in ('and','or'): where_statements = [sq for expr in query['$%s' % operator] for sq in compile_query(collection,expr,path = path)] if operator == 'and': return [and_(*where_statements)] else: return [or_(*where_statements)] elif operator == 'not': return [not_(*compile_query(collection,query['$not'],table = table,path = path))] def compile_one_to_many_query(key,query,field_name,related_table,count_column,path): def prepare_subquery(tail,query_dict): d = {} if not tail: if isinstance(query_dict,dict): return query_dict.copy() if not isinstance(query_dict,Document): raise AttributeError("Must be a document!") if not query_dict.pk: raise AttributeError("Performing a query without a primary key!") return {'pk' : query_dict.pk} return {tail : query_dict} tail = key[len(field_name)+1:] if isinstance(query,Document) and not tail: query = {'pk' : query.pk} #to do: implement $size and $not: {$size} operators... if isinstance(query,dict) and len(query) == 1 and list(query.keys())[0] in ('$all','$in','$elemMatch','$nin'): #this is an $in/$all/$nin query query_type = list(query.keys())[0][1:] subquery = list(query.values())[0] if query_type == 'elemMatch': queries = compile_query(params['collection'], prepare_subquery(tail,query['$elemMatch']), table = related_table, path = path) return queries else: if isinstance(subquery,(ManyToManyProxy,QuerySet)): if tail: #this query has a tail query = {tail : query} queries = compile_query(params['collection'],query, table = related_table, path = path) return queries #this is a query with a ManyToManyProxy/QuerySet if isinstance(subquery,ManyToManyProxy): qs = subquery.get_queryset() else: qs = subquery if not query_type in ('in','nin','all'): raise AttributeError if query_type == 'all': op = 'in' else: op = query_type if query_type == 'all': cnt = func.count(count_column) condition = cnt == qs.get_count_select() havings.append(condition) return [getattr(related_table.c['pk'],op+'_')(qs.get_select(columns = ['pk']))] elif isinstance(subquery,(list,tuple)): if subquery and isinstance(subquery[0],dict) and len(subquery[0]) == 1 and \ list(subquery[0].keys())[0] == '$elemMatch': queries = [sq for v in subquery for sq in compile_query(params['collection'], prepare_subquery(tail,v['$elemMatch']), table = related_table, path = path)] else: queries = [sq for v in subquery for sq in compile_query(params['collection'], prepare_subquery(tail,v), table = related_table, path = path)] where_statement = or_(*queries) if query_type == 'nin': where_statement = not_(where_statement) if query_type == 'all' and len(queries) > 1: cnt = func.count(count_column) havings.append(cnt == len(queries)) return [where_statement] else: raise AttributeError("$in/$nin/$all query requires a list/tuple/QuerySet/ManyToManyProxy") else: return compile_query(params['collection'],prepare_subquery(tail,query), table = related_table, path = path) def compile_many_to_many_query(key,value,field_name,params,relationship_table,path): related_collection = params['collection'] related_table = self._collection_tables[related_collection] path_str = ".".join(path) if path_str in joins[relationship_table]: relationship_table_alias = joins[relationship_table][path_str] else: relationship_table_alias = relationship_table.alias() joins[relationship_table][path_str] = relationship_table_alias joins_list.append((relationship_table_alias, relationship_table_alias.c[params['pk_field_name']] == table.c['pk'])) if path_str in joins[related_table]: related_table_alias = joins[related_table][path_str] else: related_table_alias = related_table.alias() joins[related_table][path_str] = related_table_alias joins_list.append((related_table_alias,relationship_table_alias.c[params['related_pk_field_name']] == related_table_alias.c['pk'])) return compile_one_to_many_query(key,value,field_name,related_table_alias,relationship_table_alias.c[params['pk_field_name']],new_path) def prepare_special_query(field_name,params,query): def sanitize(value): if isinstance(value,(list,tuple)): return [v.pk if isinstance(v,Document) else v for v in value] return value column_name = params['column'] if '$not' in query: return [not_(*prepare_special_query(column_name,params,sanitize(query['$not'])))] elif '$in' in query: if not query['$in']: #we return an impossible condition since the $in query does not contain any values return [expression.cast(True,Boolean) == expression.cast(False,Boolean)] return [table.c[column_name].in_(sanitize(query['$in']))] elif '$nin' in query: if not query['$nin']: return [expression.cast(True,Boolean) == expression.cast(False,Boolean)] return [~table.c[column_name].in_(sanitize(query['$nin']))] elif '$eq' in query: return [table.c[column_name] == sanitize(query['$eq'])] elif '$ne' in query: return [table.c[column_name] != sanitize(query['$ne'])] elif '$gt' in query: return [table.c[column_name] > sanitize(query['$gt'])] elif '$gte' in query: return [table.c[column_name] >= sanitize(query['$gte'])] elif '$lt' in query: return [table.c[column_name] < sanitize(query['$lt'])] elif '$lte' in query: return [table.c[column_name] <= sanitize(query['$lte'])] elif '$exists' in query: if query['$exists']: return [table.c[column_name] != None] else: return [table.c[column_name] == None] elif '$like' in query: return [table.c[column_name].like(expression.cast(query['$like'],String))] elif '$ilike' in query: return [table.c[column_name].ilike(expression.cast(query['$ilike'],String))] elif '$regex' in query: if not self.engine.url.drivername in ('postgres','mysql','sqlite'): raise AttributeError("Regex queries not supported with %s engine!" % self.engine.url.drivername) return [table.c[column_name].op('REGEXP')(expression.cast(query['$regex'],String))] else: raise AttributeError("Invalid query!") #this is a normal, field-base query for key,value in query.items(): for field_name,params in self._index_fields[collection].items(): if key == field_name: if isinstance(value,re._pattern_type): value = {'$regex' : value.pattern} if isinstance(value,dict): #this is a special query where_statements.extend(prepare_special_query(field_name,params,value)) else: #this is a normal value query where_statements.append(table.c[params['column']] == expression.cast(value,params['type'])) break else: #we check the normal relationships for field_name,params in self._related_fields[collection].items(): if key.startswith(field_name): head,tail = key[:len(field_name)],key[len(field_name)+1:] new_path = path + [head] path_str = ".".join(new_path) #ManyToManyField if isinstance(params['field'],ManyToManyField): relationship_table = self._relationship_tables[collection][field_name] where_statements.extend(compile_many_to_many_query(key,value,field_name,params,relationship_table,path = new_path)) elif isinstance(params['field'],ForeignKeyField):#this is a normal ForeignKey relation if key == field_name: #this is a ForeignKey query if isinstance(value,dict): if len(value) == 1: key,query = list(value.items())[0] if key == '$exists': if not isinstance(query,bool): raise AttributeError("$exists operator requires a Boolean operator") if query: where_statements.append(table.c[params['column']] != None) else: where_statements.append(table.c[params['column']] == None) break elif not key in ('$in','$nin'): raise AttributeError("Invalid query!") query_type = key[1:] else: raise AttributeError("Invalid query!") else: query_type = 'exact' query = value if isinstance(query,(QuerySet,ManyToManyProxy)): if not query_type in ('in','nin'): raise AttributeError("QuerySet/ManyToManyProxy objects must be used in conjunction with $in/$nin when querying a ForeignKey relationship") if isinstance(query,ManyToManyProxy): qs = query.get_queryset() else: qs = query if qs.count is not None and qs.count == 0: raise AttributeError("$in/$nin query with empty QuerySet/ManyToManyProxy!") if qs.cls is not params['class']: raise AttributeError("Invalid QuerySet class!") condition = getattr(table.c[params['column']],query_type+'_')(qs.get_select(columns = ['pk'])) where_statements.append(condition) elif isinstance(query,(list,tuple)): if not query_type in ('in','nin'): raise AttributeError("Lists/tuples must be used in conjunction with $in/$nin when querying a ForeignKey relationship") if not query: raise AttributeError("in/nin query with empty list!") if query[0].__class__ is params['class']: if any((element.__class__ is not params['class'] for element in query)): raise AttributeError("Invalid document type in ForeignKey query") where_statements.append(getattr(table.c[params['column']],query_type+'_')([expression.cast(doc.pk,params['type']) for doc in query])) else: where_statements.append(getattr(table.c[params['column']],query_type+'_')([expression.cast(element,params['type']) for element in query])) elif isinstance(query,Document): #we need an exact clas match here... if query.__class__ is not params['class']: raise AttributeError("Invalid Document class!") where_statements.append(table.c[params['column']] == query.pk) else: where_statements.append(table.c[params['column']] == expression.cast(query,params['class'].Meta.PkType)) else: #we query a sub-field of the relation related_table = self._collection_tables[params['collection']] if path_str in joins[related_table]: related_table_alias = joins[related_table][path_str] else: related_table_alias = related_table.alias() joins[related_table][path_str] = related_table_alias joins_list.append((related_table_alias,table.c[params['column']] == related_table_alias.c['pk'])) where_statements.extend(compile_query(params['collection'],{tail : value},table = related_table_alias,path = new_path)) elif isinstance(params['field'],OneToManyField): related_table = self._collection_tables[params['collection']] if path_str in joins[related_table]: related_table_alias = joins[related_table][path_str] else: related_table_alias = related_table.alias() joins[related_table][path_str] = related_table_alias joins_list.append((related_table_alias,related_table_alias.c[params['backref']['column']] == table.c['pk'])) where_statements.extend(compile_one_to_many_query(key,value,field_name,related_table_alias,table.c.pk,new_path)) break else: raise AttributeError("Query over non-indexed field %s in collection %s!" % (key,collection)) return where_statements compiled_query = compile_query(collection,query) if len(compiled_query) > 1: compiled_query = and_(*compiled_query) elif compiled_query: compiled_query = compiled_query[0] else: compiled_query = None return QuerySet(backend = self, table = table, joins = joins_list, cls = cls, condition = compiled_query, raw = raw, group_bys = group_bys, only = only, include = include, havings = havings )
[ "def", "filter", "(", "self", ",", "cls_or_collection", ",", "query", ",", "raw", "=", "False", ",", "only", "=", "None", ",", "include", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cls_or_collection", ",", "six", ".", "string_types", ")", ":", "collection", "=", "self", ".", "get_collection_for_cls", "(", "cls_or_collection", ")", "cls", "=", "cls_or_collection", "else", ":", "collection", "=", "cls_or_collection", "cls", "=", "self", ".", "get_cls_for_collection", "(", "collection", ")", "table", "=", "self", ".", "_collection_tables", "[", "collection", "]", "joins", "=", "defaultdict", "(", "dict", ")", "joins_list", "=", "[", "]", "group_bys", "=", "[", "]", "havings", "=", "[", "]", "def", "compile_query", "(", "collection", ",", "query", ",", "table", "=", "None", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "[", "]", "\"\"\"\n This function emits a list of WHERE statements that can be used to retrieve\n \"\"\"", "if", "table", "is", "None", ":", "table", "=", "self", ".", "_collection_tables", "[", "collection", "]", "where_statements", "=", "[", "]", "if", "any", "(", "[", "True", "if", "key", ".", "startswith", "(", "'$'", ")", "else", "False", "for", "key", "in", "query", ".", "keys", "(", ")", "]", ")", ":", "#this is a special operator query", "if", "len", "(", "query", ")", ">", "1", ":", "raise", "AttributeError", "(", "'Currently not supported!'", ")", "operator", "=", "list", "(", "query", ".", "keys", "(", ")", ")", "[", "0", "]", "[", "1", ":", "]", "if", "not", "operator", "in", "(", "'and'", ",", "'or'", ",", "'not'", ")", ":", "raise", "AttributeError", "(", "\"Non-supported logical operator: $%s\"", "%", "operator", ")", "if", "operator", "in", "(", "'and'", ",", "'or'", ")", ":", "where_statements", "=", "[", "sq", "for", "expr", "in", "query", "[", "'$%s'", "%", "operator", "]", "for", "sq", "in", "compile_query", "(", "collection", ",", "expr", ",", "path", "=", "path", ")", "]", "if", "operator", "==", "'and'", ":", "return", "[", "and_", "(", "*", "where_statements", ")", "]", "else", ":", "return", "[", "or_", "(", "*", "where_statements", ")", "]", "elif", "operator", "==", "'not'", ":", "return", "[", "not_", "(", "*", "compile_query", "(", "collection", ",", "query", "[", "'$not'", "]", ",", "table", "=", "table", ",", "path", "=", "path", ")", ")", "]", "def", "compile_one_to_many_query", "(", "key", ",", "query", ",", "field_name", ",", "related_table", ",", "count_column", ",", "path", ")", ":", "def", "prepare_subquery", "(", "tail", ",", "query_dict", ")", ":", "d", "=", "{", "}", "if", "not", "tail", ":", "if", "isinstance", "(", "query_dict", ",", "dict", ")", ":", "return", "query_dict", ".", "copy", "(", ")", "if", "not", "isinstance", "(", "query_dict", ",", "Document", ")", ":", "raise", "AttributeError", "(", "\"Must be a document!\"", ")", "if", "not", "query_dict", ".", "pk", ":", "raise", "AttributeError", "(", "\"Performing a query without a primary key!\"", ")", "return", "{", "'pk'", ":", "query_dict", ".", "pk", "}", "return", "{", "tail", ":", "query_dict", "}", "tail", "=", "key", "[", "len", "(", "field_name", ")", "+", "1", ":", "]", "if", "isinstance", "(", "query", ",", "Document", ")", "and", "not", "tail", ":", "query", "=", "{", "'pk'", ":", "query", ".", "pk", "}", "#to do: implement $size and $not: {$size} operators...", "if", "isinstance", "(", "query", ",", "dict", ")", "and", "len", "(", "query", ")", "==", "1", "and", "list", "(", "query", ".", "keys", "(", ")", ")", "[", "0", "]", "in", "(", "'$all'", ",", "'$in'", ",", "'$elemMatch'", ",", "'$nin'", ")", ":", "#this is an $in/$all/$nin query", "query_type", "=", "list", "(", "query", ".", "keys", "(", ")", ")", "[", "0", "]", "[", "1", ":", "]", "subquery", "=", "list", "(", "query", ".", "values", "(", ")", ")", "[", "0", "]", "if", "query_type", "==", "'elemMatch'", ":", "queries", "=", "compile_query", "(", "params", "[", "'collection'", "]", ",", "prepare_subquery", "(", "tail", ",", "query", "[", "'$elemMatch'", "]", ")", ",", "table", "=", "related_table", ",", "path", "=", "path", ")", "return", "queries", "else", ":", "if", "isinstance", "(", "subquery", ",", "(", "ManyToManyProxy", ",", "QuerySet", ")", ")", ":", "if", "tail", ":", "#this query has a tail", "query", "=", "{", "tail", ":", "query", "}", "queries", "=", "compile_query", "(", "params", "[", "'collection'", "]", ",", "query", ",", "table", "=", "related_table", ",", "path", "=", "path", ")", "return", "queries", "#this is a query with a ManyToManyProxy/QuerySet", "if", "isinstance", "(", "subquery", ",", "ManyToManyProxy", ")", ":", "qs", "=", "subquery", ".", "get_queryset", "(", ")", "else", ":", "qs", "=", "subquery", "if", "not", "query_type", "in", "(", "'in'", ",", "'nin'", ",", "'all'", ")", ":", "raise", "AttributeError", "if", "query_type", "==", "'all'", ":", "op", "=", "'in'", "else", ":", "op", "=", "query_type", "if", "query_type", "==", "'all'", ":", "cnt", "=", "func", ".", "count", "(", "count_column", ")", "condition", "=", "cnt", "==", "qs", ".", "get_count_select", "(", ")", "havings", ".", "append", "(", "condition", ")", "return", "[", "getattr", "(", "related_table", ".", "c", "[", "'pk'", "]", ",", "op", "+", "'_'", ")", "(", "qs", ".", "get_select", "(", "columns", "=", "[", "'pk'", "]", ")", ")", "]", "elif", "isinstance", "(", "subquery", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "subquery", "and", "isinstance", "(", "subquery", "[", "0", "]", ",", "dict", ")", "and", "len", "(", "subquery", "[", "0", "]", ")", "==", "1", "and", "list", "(", "subquery", "[", "0", "]", ".", "keys", "(", ")", ")", "[", "0", "]", "==", "'$elemMatch'", ":", "queries", "=", "[", "sq", "for", "v", "in", "subquery", "for", "sq", "in", "compile_query", "(", "params", "[", "'collection'", "]", ",", "prepare_subquery", "(", "tail", ",", "v", "[", "'$elemMatch'", "]", ")", ",", "table", "=", "related_table", ",", "path", "=", "path", ")", "]", "else", ":", "queries", "=", "[", "sq", "for", "v", "in", "subquery", "for", "sq", "in", "compile_query", "(", "params", "[", "'collection'", "]", ",", "prepare_subquery", "(", "tail", ",", "v", ")", ",", "table", "=", "related_table", ",", "path", "=", "path", ")", "]", "where_statement", "=", "or_", "(", "*", "queries", ")", "if", "query_type", "==", "'nin'", ":", "where_statement", "=", "not_", "(", "where_statement", ")", "if", "query_type", "==", "'all'", "and", "len", "(", "queries", ")", ">", "1", ":", "cnt", "=", "func", ".", "count", "(", "count_column", ")", "havings", ".", "append", "(", "cnt", "==", "len", "(", "queries", ")", ")", "return", "[", "where_statement", "]", "else", ":", "raise", "AttributeError", "(", "\"$in/$nin/$all query requires a list/tuple/QuerySet/ManyToManyProxy\"", ")", "else", ":", "return", "compile_query", "(", "params", "[", "'collection'", "]", ",", "prepare_subquery", "(", "tail", ",", "query", ")", ",", "table", "=", "related_table", ",", "path", "=", "path", ")", "def", "compile_many_to_many_query", "(", "key", ",", "value", ",", "field_name", ",", "params", ",", "relationship_table", ",", "path", ")", ":", "related_collection", "=", "params", "[", "'collection'", "]", "related_table", "=", "self", ".", "_collection_tables", "[", "related_collection", "]", "path_str", "=", "\".\"", ".", "join", "(", "path", ")", "if", "path_str", "in", "joins", "[", "relationship_table", "]", ":", "relationship_table_alias", "=", "joins", "[", "relationship_table", "]", "[", "path_str", "]", "else", ":", "relationship_table_alias", "=", "relationship_table", ".", "alias", "(", ")", "joins", "[", "relationship_table", "]", "[", "path_str", "]", "=", "relationship_table_alias", "joins_list", ".", "append", "(", "(", "relationship_table_alias", ",", "relationship_table_alias", ".", "c", "[", "params", "[", "'pk_field_name'", "]", "]", "==", "table", ".", "c", "[", "'pk'", "]", ")", ")", "if", "path_str", "in", "joins", "[", "related_table", "]", ":", "related_table_alias", "=", "joins", "[", "related_table", "]", "[", "path_str", "]", "else", ":", "related_table_alias", "=", "related_table", ".", "alias", "(", ")", "joins", "[", "related_table", "]", "[", "path_str", "]", "=", "related_table_alias", "joins_list", ".", "append", "(", "(", "related_table_alias", ",", "relationship_table_alias", ".", "c", "[", "params", "[", "'related_pk_field_name'", "]", "]", "==", "related_table_alias", ".", "c", "[", "'pk'", "]", ")", ")", "return", "compile_one_to_many_query", "(", "key", ",", "value", ",", "field_name", ",", "related_table_alias", ",", "relationship_table_alias", ".", "c", "[", "params", "[", "'pk_field_name'", "]", "]", ",", "new_path", ")", "def", "prepare_special_query", "(", "field_name", ",", "params", ",", "query", ")", ":", "def", "sanitize", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "v", ".", "pk", "if", "isinstance", "(", "v", ",", "Document", ")", "else", "v", "for", "v", "in", "value", "]", "return", "value", "column_name", "=", "params", "[", "'column'", "]", "if", "'$not'", "in", "query", ":", "return", "[", "not_", "(", "*", "prepare_special_query", "(", "column_name", ",", "params", ",", "sanitize", "(", "query", "[", "'$not'", "]", ")", ")", ")", "]", "elif", "'$in'", "in", "query", ":", "if", "not", "query", "[", "'$in'", "]", ":", "#we return an impossible condition since the $in query does not contain any values", "return", "[", "expression", ".", "cast", "(", "True", ",", "Boolean", ")", "==", "expression", ".", "cast", "(", "False", ",", "Boolean", ")", "]", "return", "[", "table", ".", "c", "[", "column_name", "]", ".", "in_", "(", "sanitize", "(", "query", "[", "'$in'", "]", ")", ")", "]", "elif", "'$nin'", "in", "query", ":", "if", "not", "query", "[", "'$nin'", "]", ":", "return", "[", "expression", ".", "cast", "(", "True", ",", "Boolean", ")", "==", "expression", ".", "cast", "(", "False", ",", "Boolean", ")", "]", "return", "[", "~", "table", ".", "c", "[", "column_name", "]", ".", "in_", "(", "sanitize", "(", "query", "[", "'$nin'", "]", ")", ")", "]", "elif", "'$eq'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", "==", "sanitize", "(", "query", "[", "'$eq'", "]", ")", "]", "elif", "'$ne'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", "!=", "sanitize", "(", "query", "[", "'$ne'", "]", ")", "]", "elif", "'$gt'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", ">", "sanitize", "(", "query", "[", "'$gt'", "]", ")", "]", "elif", "'$gte'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", ">=", "sanitize", "(", "query", "[", "'$gte'", "]", ")", "]", "elif", "'$lt'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", "<", "sanitize", "(", "query", "[", "'$lt'", "]", ")", "]", "elif", "'$lte'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", "<=", "sanitize", "(", "query", "[", "'$lte'", "]", ")", "]", "elif", "'$exists'", "in", "query", ":", "if", "query", "[", "'$exists'", "]", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", "!=", "None", "]", "else", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", "==", "None", "]", "elif", "'$like'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", ".", "like", "(", "expression", ".", "cast", "(", "query", "[", "'$like'", "]", ",", "String", ")", ")", "]", "elif", "'$ilike'", "in", "query", ":", "return", "[", "table", ".", "c", "[", "column_name", "]", ".", "ilike", "(", "expression", ".", "cast", "(", "query", "[", "'$ilike'", "]", ",", "String", ")", ")", "]", "elif", "'$regex'", "in", "query", ":", "if", "not", "self", ".", "engine", ".", "url", ".", "drivername", "in", "(", "'postgres'", ",", "'mysql'", ",", "'sqlite'", ")", ":", "raise", "AttributeError", "(", "\"Regex queries not supported with %s engine!\"", "%", "self", ".", "engine", ".", "url", ".", "drivername", ")", "return", "[", "table", ".", "c", "[", "column_name", "]", ".", "op", "(", "'REGEXP'", ")", "(", "expression", ".", "cast", "(", "query", "[", "'$regex'", "]", ",", "String", ")", ")", "]", "else", ":", "raise", "AttributeError", "(", "\"Invalid query!\"", ")", "#this is a normal, field-base query", "for", "key", ",", "value", "in", "query", ".", "items", "(", ")", ":", "for", "field_name", ",", "params", "in", "self", ".", "_index_fields", "[", "collection", "]", ".", "items", "(", ")", ":", "if", "key", "==", "field_name", ":", "if", "isinstance", "(", "value", ",", "re", ".", "_pattern_type", ")", ":", "value", "=", "{", "'$regex'", ":", "value", ".", "pattern", "}", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "#this is a special query", "where_statements", ".", "extend", "(", "prepare_special_query", "(", "field_name", ",", "params", ",", "value", ")", ")", "else", ":", "#this is a normal value query", "where_statements", ".", "append", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", "==", "expression", ".", "cast", "(", "value", ",", "params", "[", "'type'", "]", ")", ")", "break", "else", ":", "#we check the normal relationships", "for", "field_name", ",", "params", "in", "self", ".", "_related_fields", "[", "collection", "]", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "field_name", ")", ":", "head", ",", "tail", "=", "key", "[", ":", "len", "(", "field_name", ")", "]", ",", "key", "[", "len", "(", "field_name", ")", "+", "1", ":", "]", "new_path", "=", "path", "+", "[", "head", "]", "path_str", "=", "\".\"", ".", "join", "(", "new_path", ")", "#ManyToManyField", "if", "isinstance", "(", "params", "[", "'field'", "]", ",", "ManyToManyField", ")", ":", "relationship_table", "=", "self", ".", "_relationship_tables", "[", "collection", "]", "[", "field_name", "]", "where_statements", ".", "extend", "(", "compile_many_to_many_query", "(", "key", ",", "value", ",", "field_name", ",", "params", ",", "relationship_table", ",", "path", "=", "new_path", ")", ")", "elif", "isinstance", "(", "params", "[", "'field'", "]", ",", "ForeignKeyField", ")", ":", "#this is a normal ForeignKey relation", "if", "key", "==", "field_name", ":", "#this is a ForeignKey query", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "if", "len", "(", "value", ")", "==", "1", ":", "key", ",", "query", "=", "list", "(", "value", ".", "items", "(", ")", ")", "[", "0", "]", "if", "key", "==", "'$exists'", ":", "if", "not", "isinstance", "(", "query", ",", "bool", ")", ":", "raise", "AttributeError", "(", "\"$exists operator requires a Boolean operator\"", ")", "if", "query", ":", "where_statements", ".", "append", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", "!=", "None", ")", "else", ":", "where_statements", ".", "append", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", "==", "None", ")", "break", "elif", "not", "key", "in", "(", "'$in'", ",", "'$nin'", ")", ":", "raise", "AttributeError", "(", "\"Invalid query!\"", ")", "query_type", "=", "key", "[", "1", ":", "]", "else", ":", "raise", "AttributeError", "(", "\"Invalid query!\"", ")", "else", ":", "query_type", "=", "'exact'", "query", "=", "value", "if", "isinstance", "(", "query", ",", "(", "QuerySet", ",", "ManyToManyProxy", ")", ")", ":", "if", "not", "query_type", "in", "(", "'in'", ",", "'nin'", ")", ":", "raise", "AttributeError", "(", "\"QuerySet/ManyToManyProxy objects must be used in conjunction with $in/$nin when querying a ForeignKey relationship\"", ")", "if", "isinstance", "(", "query", ",", "ManyToManyProxy", ")", ":", "qs", "=", "query", ".", "get_queryset", "(", ")", "else", ":", "qs", "=", "query", "if", "qs", ".", "count", "is", "not", "None", "and", "qs", ".", "count", "==", "0", ":", "raise", "AttributeError", "(", "\"$in/$nin query with empty QuerySet/ManyToManyProxy!\"", ")", "if", "qs", ".", "cls", "is", "not", "params", "[", "'class'", "]", ":", "raise", "AttributeError", "(", "\"Invalid QuerySet class!\"", ")", "condition", "=", "getattr", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", ",", "query_type", "+", "'_'", ")", "(", "qs", ".", "get_select", "(", "columns", "=", "[", "'pk'", "]", ")", ")", "where_statements", ".", "append", "(", "condition", ")", "elif", "isinstance", "(", "query", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "query_type", "in", "(", "'in'", ",", "'nin'", ")", ":", "raise", "AttributeError", "(", "\"Lists/tuples must be used in conjunction with $in/$nin when querying a ForeignKey relationship\"", ")", "if", "not", "query", ":", "raise", "AttributeError", "(", "\"in/nin query with empty list!\"", ")", "if", "query", "[", "0", "]", ".", "__class__", "is", "params", "[", "'class'", "]", ":", "if", "any", "(", "(", "element", ".", "__class__", "is", "not", "params", "[", "'class'", "]", "for", "element", "in", "query", ")", ")", ":", "raise", "AttributeError", "(", "\"Invalid document type in ForeignKey query\"", ")", "where_statements", ".", "append", "(", "getattr", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", ",", "query_type", "+", "'_'", ")", "(", "[", "expression", ".", "cast", "(", "doc", ".", "pk", ",", "params", "[", "'type'", "]", ")", "for", "doc", "in", "query", "]", ")", ")", "else", ":", "where_statements", ".", "append", "(", "getattr", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", ",", "query_type", "+", "'_'", ")", "(", "[", "expression", ".", "cast", "(", "element", ",", "params", "[", "'type'", "]", ")", "for", "element", "in", "query", "]", ")", ")", "elif", "isinstance", "(", "query", ",", "Document", ")", ":", "#we need an exact clas match here...", "if", "query", ".", "__class__", "is", "not", "params", "[", "'class'", "]", ":", "raise", "AttributeError", "(", "\"Invalid Document class!\"", ")", "where_statements", ".", "append", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", "==", "query", ".", "pk", ")", "else", ":", "where_statements", ".", "append", "(", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", "==", "expression", ".", "cast", "(", "query", ",", "params", "[", "'class'", "]", ".", "Meta", ".", "PkType", ")", ")", "else", ":", "#we query a sub-field of the relation", "related_table", "=", "self", ".", "_collection_tables", "[", "params", "[", "'collection'", "]", "]", "if", "path_str", "in", "joins", "[", "related_table", "]", ":", "related_table_alias", "=", "joins", "[", "related_table", "]", "[", "path_str", "]", "else", ":", "related_table_alias", "=", "related_table", ".", "alias", "(", ")", "joins", "[", "related_table", "]", "[", "path_str", "]", "=", "related_table_alias", "joins_list", ".", "append", "(", "(", "related_table_alias", ",", "table", ".", "c", "[", "params", "[", "'column'", "]", "]", "==", "related_table_alias", ".", "c", "[", "'pk'", "]", ")", ")", "where_statements", ".", "extend", "(", "compile_query", "(", "params", "[", "'collection'", "]", ",", "{", "tail", ":", "value", "}", ",", "table", "=", "related_table_alias", ",", "path", "=", "new_path", ")", ")", "elif", "isinstance", "(", "params", "[", "'field'", "]", ",", "OneToManyField", ")", ":", "related_table", "=", "self", ".", "_collection_tables", "[", "params", "[", "'collection'", "]", "]", "if", "path_str", "in", "joins", "[", "related_table", "]", ":", "related_table_alias", "=", "joins", "[", "related_table", "]", "[", "path_str", "]", "else", ":", "related_table_alias", "=", "related_table", ".", "alias", "(", ")", "joins", "[", "related_table", "]", "[", "path_str", "]", "=", "related_table_alias", "joins_list", ".", "append", "(", "(", "related_table_alias", ",", "related_table_alias", ".", "c", "[", "params", "[", "'backref'", "]", "[", "'column'", "]", "]", "==", "table", ".", "c", "[", "'pk'", "]", ")", ")", "where_statements", ".", "extend", "(", "compile_one_to_many_query", "(", "key", ",", "value", ",", "field_name", ",", "related_table_alias", ",", "table", ".", "c", ".", "pk", ",", "new_path", ")", ")", "break", "else", ":", "raise", "AttributeError", "(", "\"Query over non-indexed field %s in collection %s!\"", "%", "(", "key", ",", "collection", ")", ")", "return", "where_statements", "compiled_query", "=", "compile_query", "(", "collection", ",", "query", ")", "if", "len", "(", "compiled_query", ")", ">", "1", ":", "compiled_query", "=", "and_", "(", "*", "compiled_query", ")", "elif", "compiled_query", ":", "compiled_query", "=", "compiled_query", "[", "0", "]", "else", ":", "compiled_query", "=", "None", "return", "QuerySet", "(", "backend", "=", "self", ",", "table", "=", "table", ",", "joins", "=", "joins_list", ",", "cls", "=", "cls", ",", "condition", "=", "compiled_query", ",", "raw", "=", "raw", ",", "group_bys", "=", "group_bys", ",", "only", "=", "only", ",", "include", "=", "include", ",", "havings", "=", "havings", ")" ]
Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports all query operators that are available in SQLAlchemy and returns a query set that is based on a SQLAlchemy cursor.
[ "Filter", "objects", "from", "the", "database", "that", "correspond", "to", "a", "given", "set", "of", "properties", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/sql/backend.py#L1070-L1404
adewes/blitzdb
blitzdb/backends/mongo/backend.py
Backend._canonicalize_query
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): for encoder in self.query_encoders: q = encoder.encode(q,[]) if isinstance(q, dict): nq = {} for key,value in q.items(): new_key = key if isinstance(value,dict) and len(value) == 1 and list(value.keys())[0].startswith('$'): if list(value.keys())[0] in ('$all','$in'): if list(value.values())[0] and isinstance(list(value.values())[0][0],Document): if self._use_pk_based_refs: new_key+='.pk' else: new_key+='.__ref__' elif isinstance(value,Document): if self._use_pk_based_refs: new_key+='.pk' else: new_key+='.__ref__' nq[new_key] = transform_query(value) return nq elif isinstance(q, (list,QuerySet,tuple)): return [transform_query(x) for x in q] elif isinstance(q,Document): collection = self.get_collection_for_obj(q) if self._use_pk_based_refs: return q.pk else: return "%s:%s" % (collection,q.pk) else: return q return transform_query(query)
python
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): for encoder in self.query_encoders: q = encoder.encode(q,[]) if isinstance(q, dict): nq = {} for key,value in q.items(): new_key = key if isinstance(value,dict) and len(value) == 1 and list(value.keys())[0].startswith('$'): if list(value.keys())[0] in ('$all','$in'): if list(value.values())[0] and isinstance(list(value.values())[0][0],Document): if self._use_pk_based_refs: new_key+='.pk' else: new_key+='.__ref__' elif isinstance(value,Document): if self._use_pk_based_refs: new_key+='.pk' else: new_key+='.__ref__' nq[new_key] = transform_query(value) return nq elif isinstance(q, (list,QuerySet,tuple)): return [transform_query(x) for x in q] elif isinstance(q,Document): collection = self.get_collection_for_obj(q) if self._use_pk_based_refs: return q.pk else: return "%s:%s" % (collection,q.pk) else: return q return transform_query(query)
[ "def", "_canonicalize_query", "(", "self", ",", "query", ")", ":", "def", "transform_query", "(", "q", ")", ":", "for", "encoder", "in", "self", ".", "query_encoders", ":", "q", "=", "encoder", ".", "encode", "(", "q", ",", "[", "]", ")", "if", "isinstance", "(", "q", ",", "dict", ")", ":", "nq", "=", "{", "}", "for", "key", ",", "value", "in", "q", ".", "items", "(", ")", ":", "new_key", "=", "key", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "len", "(", "value", ")", "==", "1", "and", "list", "(", "value", ".", "keys", "(", ")", ")", "[", "0", "]", ".", "startswith", "(", "'$'", ")", ":", "if", "list", "(", "value", ".", "keys", "(", ")", ")", "[", "0", "]", "in", "(", "'$all'", ",", "'$in'", ")", ":", "if", "list", "(", "value", ".", "values", "(", ")", ")", "[", "0", "]", "and", "isinstance", "(", "list", "(", "value", ".", "values", "(", ")", ")", "[", "0", "]", "[", "0", "]", ",", "Document", ")", ":", "if", "self", ".", "_use_pk_based_refs", ":", "new_key", "+=", "'.pk'", "else", ":", "new_key", "+=", "'.__ref__'", "elif", "isinstance", "(", "value", ",", "Document", ")", ":", "if", "self", ".", "_use_pk_based_refs", ":", "new_key", "+=", "'.pk'", "else", ":", "new_key", "+=", "'.__ref__'", "nq", "[", "new_key", "]", "=", "transform_query", "(", "value", ")", "return", "nq", "elif", "isinstance", "(", "q", ",", "(", "list", ",", "QuerySet", ",", "tuple", ")", ")", ":", "return", "[", "transform_query", "(", "x", ")", "for", "x", "in", "q", "]", "elif", "isinstance", "(", "q", ",", "Document", ")", ":", "collection", "=", "self", ".", "get_collection_for_obj", "(", "q", ")", "if", "self", ".", "_use_pk_based_refs", ":", "return", "q", ".", "pk", "else", ":", "return", "\"%s:%s\"", "%", "(", "collection", ",", "q", ".", "pk", ")", "else", ":", "return", "q", "return", "transform_query", "(", "query", ")" ]
Transform the query dictionary to replace e.g. documents with __ref__ fields.
[ "Transform", "the", "query", "dictionary", "to", "replace", "e", ".", "g", ".", "documents", "with", "__ref__", "fields", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/mongo/backend.py#L294-L334
adewes/blitzdb
blitzdb/backends/mongo/backend.py
Backend.filter
def filter(self, cls_or_collection, query, raw=False, only=None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports most query operators that are available in MongoDB and returns a query set that is based on a MongoDB cursor. """ if not isinstance(cls_or_collection, six.string_types): collection = self.get_collection_for_cls(cls_or_collection) cls = cls_or_collection else: collection = cls_or_collection cls = self.get_cls_for_collection(collection) canonical_query = self._canonicalize_query(query) args = {} if only: if isinstance(only,tuple): args['projection'] = list(only) else: args['projection'] = only return QuerySet(self, cls, self.db[collection].find(canonical_query, **args), raw=raw, only=only)
python
def filter(self, cls_or_collection, query, raw=False, only=None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports most query operators that are available in MongoDB and returns a query set that is based on a MongoDB cursor. """ if not isinstance(cls_or_collection, six.string_types): collection = self.get_collection_for_cls(cls_or_collection) cls = cls_or_collection else: collection = cls_or_collection cls = self.get_cls_for_collection(collection) canonical_query = self._canonicalize_query(query) args = {} if only: if isinstance(only,tuple): args['projection'] = list(only) else: args['projection'] = only return QuerySet(self, cls, self.db[collection].find(canonical_query, **args), raw=raw, only=only)
[ "def", "filter", "(", "self", ",", "cls_or_collection", ",", "query", ",", "raw", "=", "False", ",", "only", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cls_or_collection", ",", "six", ".", "string_types", ")", ":", "collection", "=", "self", ".", "get_collection_for_cls", "(", "cls_or_collection", ")", "cls", "=", "cls_or_collection", "else", ":", "collection", "=", "cls_or_collection", "cls", "=", "self", ".", "get_cls_for_collection", "(", "collection", ")", "canonical_query", "=", "self", ".", "_canonicalize_query", "(", "query", ")", "args", "=", "{", "}", "if", "only", ":", "if", "isinstance", "(", "only", ",", "tuple", ")", ":", "args", "[", "'projection'", "]", "=", "list", "(", "only", ")", "else", ":", "args", "[", "'projection'", "]", "=", "only", "return", "QuerySet", "(", "self", ",", "cls", ",", "self", ".", "db", "[", "collection", "]", ".", "find", "(", "canonical_query", ",", "*", "*", "args", ")", ",", "raw", "=", "raw", ",", "only", "=", "only", ")" ]
Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports most query operators that are available in MongoDB and returns a query set that is based on a MongoDB cursor.
[ "Filter", "objects", "from", "the", "database", "that", "correspond", "to", "a", "given", "set", "of", "properties", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/mongo/backend.py#L349-L379
adewes/blitzdb
blitzdb/backends/file/queries.py
boolean_operator_query
def boolean_operator_query(boolean_operator): """Generate boolean operator checking function.""" def _boolean_operator_query(expressions): """Apply boolean operator to expressions.""" def _apply_boolean_operator(query_function, expressions=expressions): """Return if expressions with boolean operator are satisfied.""" compiled_expressions = [compile_query(e) for e in expressions] return reduce( boolean_operator, [e(query_function) for e in compiled_expressions] ) return _apply_boolean_operator return _boolean_operator_query
python
def boolean_operator_query(boolean_operator): """Generate boolean operator checking function.""" def _boolean_operator_query(expressions): """Apply boolean operator to expressions.""" def _apply_boolean_operator(query_function, expressions=expressions): """Return if expressions with boolean operator are satisfied.""" compiled_expressions = [compile_query(e) for e in expressions] return reduce( boolean_operator, [e(query_function) for e in compiled_expressions] ) return _apply_boolean_operator return _boolean_operator_query
[ "def", "boolean_operator_query", "(", "boolean_operator", ")", ":", "def", "_boolean_operator_query", "(", "expressions", ")", ":", "\"\"\"Apply boolean operator to expressions.\"\"\"", "def", "_apply_boolean_operator", "(", "query_function", ",", "expressions", "=", "expressions", ")", ":", "\"\"\"Return if expressions with boolean operator are satisfied.\"\"\"", "compiled_expressions", "=", "[", "compile_query", "(", "e", ")", "for", "e", "in", "expressions", "]", "return", "reduce", "(", "boolean_operator", ",", "[", "e", "(", "query_function", ")", "for", "e", "in", "compiled_expressions", "]", ")", "return", "_apply_boolean_operator", "return", "_boolean_operator_query" ]
Generate boolean operator checking function.
[ "Generate", "boolean", "operator", "checking", "function", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L11-L24
adewes/blitzdb
blitzdb/backends/file/queries.py
filter_query
def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expression = compile_query(expression) elif callable(expression): def _filter(index, expression=expression): result = [store_key for value, store_keys in index.get_index().items() if expression(value) for store_key in store_keys] return result compiled_expression = _filter else: compiled_expression = expression def _get(query_function, key=key, expression=compiled_expression): """Get document key and check against expression.""" return query_function(key, expression) return _get
python
def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expression = compile_query(expression) elif callable(expression): def _filter(index, expression=expression): result = [store_key for value, store_keys in index.get_index().items() if expression(value) for store_key in store_keys] return result compiled_expression = _filter else: compiled_expression = expression def _get(query_function, key=key, expression=compiled_expression): """Get document key and check against expression.""" return query_function(key, expression) return _get
[ "def", "filter_query", "(", "key", ",", "expression", ")", ":", "if", "(", "isinstance", "(", "expression", ",", "dict", ")", "and", "len", "(", "expression", ")", "==", "1", "and", "list", "(", "expression", ".", "keys", "(", ")", ")", "[", "0", "]", ".", "startswith", "(", "'$'", ")", ")", ":", "compiled_expression", "=", "compile_query", "(", "expression", ")", "elif", "callable", "(", "expression", ")", ":", "def", "_filter", "(", "index", ",", "expression", "=", "expression", ")", ":", "result", "=", "[", "store_key", "for", "value", ",", "store_keys", "in", "index", ".", "get_index", "(", ")", ".", "items", "(", ")", "if", "expression", "(", "value", ")", "for", "store_key", "in", "store_keys", "]", "return", "result", "compiled_expression", "=", "_filter", "else", ":", "compiled_expression", "=", "expression", "def", "_get", "(", "query_function", ",", "key", "=", "key", ",", "expression", "=", "compiled_expression", ")", ":", "\"\"\"Get document key and check against expression.\"\"\"", "return", "query_function", "(", "key", ",", "expression", ")", "return", "_get" ]
Filter documents with a key that satisfies an expression.
[ "Filter", "documents", "with", "a", "key", "that", "satisfies", "an", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L27-L48
adewes/blitzdb
blitzdb/backends/file/queries.py
not_query
def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() returned_keys = expression(index) return [key for key in all_keys if key not in returned_keys] return _not
python
def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() returned_keys = expression(index) return [key for key in all_keys if key not in returned_keys] return _not
[ "def", "not_query", "(", "expression", ")", ":", "compiled_expression", "=", "compile_query", "(", "expression", ")", "def", "_not", "(", "index", ",", "expression", "=", "compiled_expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "all_keys", "=", "index", ".", "get_all_keys", "(", ")", "returned_keys", "=", "expression", "(", "index", ")", "return", "[", "key", "for", "key", "in", "all_keys", "if", "key", "not", "in", "returned_keys", "]", "return", "_not" ]
Apply logical not operator to expression.
[ "Apply", "logical", "not", "operator", "to", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L51-L61
adewes/blitzdb
blitzdb/backends/file/queries.py
comparison_operator_query
def comparison_operator_query(comparison_operator): """Generate comparison operator checking function.""" def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression return [ store_key for value, store_keys in index.get_index().items() if comparison_operator(value, ev) for store_key in store_keys ] return _apply_comparison_operator return _comparison_operator_query
python
def comparison_operator_query(comparison_operator): """Generate comparison operator checking function.""" def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression return [ store_key for value, store_keys in index.get_index().items() if comparison_operator(value, ev) for store_key in store_keys ] return _apply_comparison_operator return _comparison_operator_query
[ "def", "comparison_operator_query", "(", "comparison_operator", ")", ":", "def", "_comparison_operator_query", "(", "expression", ")", ":", "\"\"\"Apply binary operator to expression.\"\"\"", "def", "_apply_comparison_operator", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "ev", "=", "expression", "(", ")", "if", "callable", "(", "expression", ")", "else", "expression", "return", "[", "store_key", "for", "value", ",", "store_keys", "in", "index", ".", "get_index", "(", ")", ".", "items", "(", ")", "if", "comparison_operator", "(", "value", ",", "ev", ")", "for", "store_key", "in", "store_keys", "]", "return", "_apply_comparison_operator", "return", "_comparison_operator_query" ]
Generate comparison operator checking function.
[ "Generate", "comparison", "operator", "checking", "function", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L64-L79
adewes/blitzdb
blitzdb/backends/file/queries.py
exists_query
def exists_query(expression): """Check that documents have a key that satisfies expression.""" def _exists(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression if ev: return [ store_key for store_keys in index.get_index().values() for store_key in store_keys ] else: return index.get_undefined_keys() return _exists
python
def exists_query(expression): """Check that documents have a key that satisfies expression.""" def _exists(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression if ev: return [ store_key for store_keys in index.get_index().values() for store_key in store_keys ] else: return index.get_undefined_keys() return _exists
[ "def", "exists_query", "(", "expression", ")", ":", "def", "_exists", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "ev", "=", "expression", "(", ")", "if", "callable", "(", "expression", ")", "else", "expression", "if", "ev", ":", "return", "[", "store_key", "for", "store_keys", "in", "index", ".", "get_index", "(", ")", ".", "values", "(", ")", "for", "store_key", "in", "store_keys", "]", "else", ":", "return", "index", ".", "get_undefined_keys", "(", ")", "return", "_exists" ]
Check that documents have a key that satisfies expression.
[ "Check", "that", "documents", "have", "a", "key", "that", "satisfies", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L82-L97
adewes/blitzdb
blitzdb/backends/file/queries.py
regex_query
def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys in index.get_index().items() if (isinstance(value, six.string_types) and re.match(pattern, value)) for store_key in store_keys ] return _regex
python
def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys in index.get_index().items() if (isinstance(value, six.string_types) and re.match(pattern, value)) for store_key in store_keys ] return _regex
[ "def", "regex_query", "(", "expression", ")", ":", "def", "_regex", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "pattern", "=", "re", ".", "compile", "(", "expression", ")", "return", "[", "store_key", "for", "value", ",", "store_keys", "in", "index", ".", "get_index", "(", ")", ".", "items", "(", ")", "if", "(", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "and", "re", ".", "match", "(", "pattern", ",", "value", ")", ")", "for", "store_key", "in", "store_keys", "]", "return", "_regex" ]
Apply regular expression to result of expression.
[ "Apply", "regular", "expression", "to", "result", "of", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L100-L114
adewes/blitzdb
blitzdb/backends/file/queries.py
all_query
def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except TypeError: raise AttributeError('$all argument must be an iterable!') hashed_ev = [index.get_hash_for(v) for v in ev] store_keys = set() if len(hashed_ev) == 0: return [] store_keys = set(index.get_keys_for(hashed_ev[0])) for value in hashed_ev[1:]: store_keys &= set(index.get_keys_for(value)) return list(store_keys) return _all
python
def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except TypeError: raise AttributeError('$all argument must be an iterable!') hashed_ev = [index.get_hash_for(v) for v in ev] store_keys = set() if len(hashed_ev) == 0: return [] store_keys = set(index.get_keys_for(hashed_ev[0])) for value in hashed_ev[1:]: store_keys &= set(index.get_keys_for(value)) return list(store_keys) return _all
[ "def", "all_query", "(", "expression", ")", ":", "def", "_all", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "ev", "=", "expression", "(", ")", "if", "callable", "(", "expression", ")", "else", "expression", "try", ":", "iter", "(", "ev", ")", "except", "TypeError", ":", "raise", "AttributeError", "(", "'$all argument must be an iterable!'", ")", "hashed_ev", "=", "[", "index", ".", "get_hash_for", "(", "v", ")", "for", "v", "in", "ev", "]", "store_keys", "=", "set", "(", ")", "if", "len", "(", "hashed_ev", ")", "==", "0", ":", "return", "[", "]", "store_keys", "=", "set", "(", "index", ".", "get_keys_for", "(", "hashed_ev", "[", "0", "]", ")", ")", "for", "value", "in", "hashed_ev", "[", "1", ":", "]", ":", "store_keys", "&=", "set", "(", "index", ".", "get_keys_for", "(", "value", ")", ")", "return", "list", "(", "store_keys", ")", "return", "_all" ]
Match arrays that contain all elements in the query.
[ "Match", "arrays", "that", "contain", "all", "elements", "in", "the", "query", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L117-L137
adewes/blitzdb
blitzdb/backends/file/queries.py
in_query
def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except TypeError: raise AttributeError('$in argument must be an iterable!') hashed_ev = [index.get_hash_for(v) for v in ev] store_keys = set() for value in hashed_ev: store_keys |= set(index.get_keys_for(value)) return list(store_keys) return _in
python
def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except TypeError: raise AttributeError('$in argument must be an iterable!') hashed_ev = [index.get_hash_for(v) for v in ev] store_keys = set() for value in hashed_ev: store_keys |= set(index.get_keys_for(value)) return list(store_keys) return _in
[ "def", "in_query", "(", "expression", ")", ":", "def", "_in", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "ev", "=", "expression", "(", ")", "if", "callable", "(", "expression", ")", "else", "expression", "try", ":", "iter", "(", "ev", ")", "except", "TypeError", ":", "raise", "AttributeError", "(", "'$in argument must be an iterable!'", ")", "hashed_ev", "=", "[", "index", ".", "get_hash_for", "(", "v", ")", "for", "v", "in", "ev", "]", "store_keys", "=", "set", "(", ")", "for", "value", "in", "hashed_ev", ":", "store_keys", "|=", "set", "(", "index", ".", "get_keys_for", "(", "value", ")", ")", "return", "list", "(", "store_keys", ")", "return", "_in" ]
Match any of the values that exist in an array specified in query.
[ "Match", "any", "of", "the", "values", "that", "exist", "in", "an", "array", "specified", "in", "query", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L150-L167
adewes/blitzdb
blitzdb/backends/file/queries.py
compile_query
def compile_query(query): """Compile each expression in query recursively.""" if isinstance(query, dict): expressions = [] for key, value in query.items(): if key.startswith('$'): if key not in query_funcs: raise AttributeError('Invalid operator: {}'.format(key)) expressions.append(query_funcs[key](value)) else: expressions.append(filter_query(key, value)) if len(expressions) > 1: return boolean_operator_query(operator.and_)(expressions) else: return ( expressions[0] if len(expressions) else lambda query_function: query_function(None, None) ) else: return query
python
def compile_query(query): """Compile each expression in query recursively.""" if isinstance(query, dict): expressions = [] for key, value in query.items(): if key.startswith('$'): if key not in query_funcs: raise AttributeError('Invalid operator: {}'.format(key)) expressions.append(query_funcs[key](value)) else: expressions.append(filter_query(key, value)) if len(expressions) > 1: return boolean_operator_query(operator.and_)(expressions) else: return ( expressions[0] if len(expressions) else lambda query_function: query_function(None, None) ) else: return query
[ "def", "compile_query", "(", "query", ")", ":", "if", "isinstance", "(", "query", ",", "dict", ")", ":", "expressions", "=", "[", "]", "for", "key", ",", "value", "in", "query", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'$'", ")", ":", "if", "key", "not", "in", "query_funcs", ":", "raise", "AttributeError", "(", "'Invalid operator: {}'", ".", "format", "(", "key", ")", ")", "expressions", ".", "append", "(", "query_funcs", "[", "key", "]", "(", "value", ")", ")", "else", ":", "expressions", ".", "append", "(", "filter_query", "(", "key", ",", "value", ")", ")", "if", "len", "(", "expressions", ")", ">", "1", ":", "return", "boolean_operator_query", "(", "operator", ".", "and_", ")", "(", "expressions", ")", "else", ":", "return", "(", "expressions", "[", "0", "]", "if", "len", "(", "expressions", ")", "else", "lambda", "query_function", ":", "query_function", "(", "None", ",", "None", ")", ")", "else", ":", "return", "query" ]
Compile each expression in query recursively.
[ "Compile", "each", "expression", "in", "query", "recursively", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L169-L189
seantis/suitable
suitable/module_runner.py
ansible_verbosity
def ansible_verbosity(verbosity): """ Temporarily changes the ansible verbosity. Relies on a single display instance being referenced by the __main__ module. This is setup when suitable is imported, though Ansible could already be imported beforehand, in which case the output might not be as verbose as expected. To be sure, import suitable before importing ansible. ansible. """ previous = display.verbosity display.verbosity = verbosity yield display.verbosity = previous
python
def ansible_verbosity(verbosity): """ Temporarily changes the ansible verbosity. Relies on a single display instance being referenced by the __main__ module. This is setup when suitable is imported, though Ansible could already be imported beforehand, in which case the output might not be as verbose as expected. To be sure, import suitable before importing ansible. ansible. """ previous = display.verbosity display.verbosity = verbosity yield display.verbosity = previous
[ "def", "ansible_verbosity", "(", "verbosity", ")", ":", "previous", "=", "display", ".", "verbosity", "display", ".", "verbosity", "=", "verbosity", "yield", "display", ".", "verbosity", "=", "previous" ]
Temporarily changes the ansible verbosity. Relies on a single display instance being referenced by the __main__ module. This is setup when suitable is imported, though Ansible could already be imported beforehand, in which case the output might not be as verbose as expected. To be sure, import suitable before importing ansible. ansible.
[ "Temporarily", "changes", "the", "ansible", "verbosity", ".", "Relies", "on", "a", "single", "display", "instance", "being", "referenced", "by", "the", "__main__", "module", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L32-L46
seantis/suitable
suitable/module_runner.py
environment_variable
def environment_variable(key, value): """ Temporarily overrides an environment variable. """ if key not in os.environ: previous = None else: previous = os.environ[key] os.environ[key] = value yield if previous is None: del os.environ[key] else: os.environ[key] = previous
python
def environment_variable(key, value): """ Temporarily overrides an environment variable. """ if key not in os.environ: previous = None else: previous = os.environ[key] os.environ[key] = value yield if previous is None: del os.environ[key] else: os.environ[key] = previous
[ "def", "environment_variable", "(", "key", ",", "value", ")", ":", "if", "key", "not", "in", "os", ".", "environ", ":", "previous", "=", "None", "else", ":", "previous", "=", "os", ".", "environ", "[", "key", "]", "os", ".", "environ", "[", "key", "]", "=", "value", "yield", "if", "previous", "is", "None", ":", "del", "os", ".", "environ", "[", "key", "]", "else", ":", "os", ".", "environ", "[", "key", "]", "=", "previous" ]
Temporarily overrides an environment variable.
[ "Temporarily", "overrides", "an", "environment", "variable", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L50-L65
seantis/suitable
suitable/module_runner.py
host_key_checking
def host_key_checking(enable): """ Temporarily disables host_key_checking, which is set globally. """ def as_string(b): return b and 'True' or 'False' with environment_variable('ANSIBLE_HOST_KEY_CHECKING', as_string(enable)): previous = ansible.constants.HOST_KEY_CHECKING ansible.constants.HOST_KEY_CHECKING = enable yield ansible.constants.HOST_KEY_CHECKING = previous
python
def host_key_checking(enable): """ Temporarily disables host_key_checking, which is set globally. """ def as_string(b): return b and 'True' or 'False' with environment_variable('ANSIBLE_HOST_KEY_CHECKING', as_string(enable)): previous = ansible.constants.HOST_KEY_CHECKING ansible.constants.HOST_KEY_CHECKING = enable yield ansible.constants.HOST_KEY_CHECKING = previous
[ "def", "host_key_checking", "(", "enable", ")", ":", "def", "as_string", "(", "b", ")", ":", "return", "b", "and", "'True'", "or", "'False'", "with", "environment_variable", "(", "'ANSIBLE_HOST_KEY_CHECKING'", ",", "as_string", "(", "enable", ")", ")", ":", "previous", "=", "ansible", ".", "constants", ".", "HOST_KEY_CHECKING", "ansible", ".", "constants", ".", "HOST_KEY_CHECKING", "=", "enable", "yield", "ansible", ".", "constants", ".", "HOST_KEY_CHECKING", "=", "previous" ]
Temporarily disables host_key_checking, which is set globally.
[ "Temporarily", "disables", "host_key_checking", "which", "is", "set", "globally", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L69-L80
seantis/suitable
suitable/module_runner.py
ModuleRunner.hookup
def hookup(self, api): """ Hooks this module up to the given api. """ assert not hasattr(api, self.module_name), """ '{}' conflicts with existing attribute """.format(self.module_name) self.api = api setattr(api, self.module_name, self.execute)
python
def hookup(self, api): """ Hooks this module up to the given api. """ assert not hasattr(api, self.module_name), """ '{}' conflicts with existing attribute """.format(self.module_name) self.api = api setattr(api, self.module_name, self.execute)
[ "def", "hookup", "(", "self", ",", "api", ")", ":", "assert", "not", "hasattr", "(", "api", ",", "self", ".", "module_name", ")", ",", "\"\"\"\n '{}' conflicts with existing attribute\n \"\"\"", ".", "format", "(", "self", ".", "module_name", ")", "self", ".", "api", "=", "api", "setattr", "(", "api", ",", "self", ".", "module_name", ",", "self", ".", "execute", ")" ]
Hooks this module up to the given api.
[ "Hooks", "this", "module", "up", "to", "the", "given", "api", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L119-L128
seantis/suitable
suitable/module_runner.py
ModuleRunner.execute
def execute(self, *args, **kwargs): """ Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result. """ assert self.is_hooked_up, "the module should be hooked up to the api" if set_global_context: set_global_context(self.api.options) # legacy key=value pairs shorthand approach if args: self.module_args = module_args = self.get_module_args(args, kwargs) else: self.module_args = module_args = kwargs loader = DataLoader() inventory_manager = SourcelessInventoryManager(loader=loader) for host, port in self.api.hosts_with_ports: inventory_manager._inventory.add_host(host, group='all', port=port) for key, value in self.api.options.extra_vars.items(): inventory_manager._inventory.set_variable('all', key, value) variable_manager = VariableManager( loader=loader, inventory=inventory_manager) play_source = { 'name': "Suitable Play", 'hosts': 'all', 'gather_facts': 'no', 'tasks': [{ 'action': { 'module': self.module_name, 'args': module_args, }, 'environment': self.api.environment, }] } try: play = Play.load( play_source, variable_manager=variable_manager, loader=loader, ) if self.api.strategy: play.strategy = self.api.strategy log.info( u'running {}'.format(u'- {module_name}: {module_args}'.format( module_name=self.module_name, module_args=module_args )) ) start = datetime.utcnow() task_queue_manager = None callback = SilentCallbackModule() # ansible uses various levels of verbosity (from -v to -vvvvvv) # offering various amounts of debug information # # we keep it a bit simpler by activating all of it during debug, # and falling back to the default of 0 otherwise verbosity = self.api.options.verbosity == logging.DEBUG and 6 or 0 with ansible_verbosity(verbosity): # host_key_checking is special, since not each connection # plugin handles it the same way, we need to apply both # environment variable and Ansible constant when running a # command in the runner to be successful with host_key_checking(self.api.host_key_checking): kwargs = dict( inventory=inventory_manager, variable_manager=variable_manager, loader=loader, options=self.api.options, passwords=getattr(self.api.options, 'passwords', {}), stdout_callback=callback ) if set_global_context: del kwargs['options'] task_queue_manager = TaskQueueManager(**kwargs) try: task_queue_manager.run(play) except SystemExit: # Mitogen forks our process and exits it in one # instance before returning # # This is fine, but it does lead to a very messy exit # by py.test which will essentially return with a test # that is first successful and then failed as each # forked process dies. # # To avoid this we commit suicide if we are run inside # a pytest session. Normally this would just result # in a exit code of zero, which is good. if 'pytest' in sys.modules: try: atexit._run_exitfuncs() except Exception: pass os.kill(os.getpid(), signal.SIGKILL) raise finally: if task_queue_manager is not None: task_queue_manager.cleanup() if set_global_context: # Ansible 2.8 introduces a global context which persists # during the lifetime of the process - for Suitable this # singleton/cache needs to be cleared after each call # to make sure that API calls do not carry over state. # # The docs hint at a future inclusion of local contexts, which # would of course be preferable. from ansible.utils.context_objects import GlobalCLIArgs GlobalCLIArgs._Singleton__instance = None log.debug(u'took {} to complete'.format(datetime.utcnow() - start)) return self.evaluate_results(callback)
python
def execute(self, *args, **kwargs): """ Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result. """ assert self.is_hooked_up, "the module should be hooked up to the api" if set_global_context: set_global_context(self.api.options) # legacy key=value pairs shorthand approach if args: self.module_args = module_args = self.get_module_args(args, kwargs) else: self.module_args = module_args = kwargs loader = DataLoader() inventory_manager = SourcelessInventoryManager(loader=loader) for host, port in self.api.hosts_with_ports: inventory_manager._inventory.add_host(host, group='all', port=port) for key, value in self.api.options.extra_vars.items(): inventory_manager._inventory.set_variable('all', key, value) variable_manager = VariableManager( loader=loader, inventory=inventory_manager) play_source = { 'name': "Suitable Play", 'hosts': 'all', 'gather_facts': 'no', 'tasks': [{ 'action': { 'module': self.module_name, 'args': module_args, }, 'environment': self.api.environment, }] } try: play = Play.load( play_source, variable_manager=variable_manager, loader=loader, ) if self.api.strategy: play.strategy = self.api.strategy log.info( u'running {}'.format(u'- {module_name}: {module_args}'.format( module_name=self.module_name, module_args=module_args )) ) start = datetime.utcnow() task_queue_manager = None callback = SilentCallbackModule() # ansible uses various levels of verbosity (from -v to -vvvvvv) # offering various amounts of debug information # # we keep it a bit simpler by activating all of it during debug, # and falling back to the default of 0 otherwise verbosity = self.api.options.verbosity == logging.DEBUG and 6 or 0 with ansible_verbosity(verbosity): # host_key_checking is special, since not each connection # plugin handles it the same way, we need to apply both # environment variable and Ansible constant when running a # command in the runner to be successful with host_key_checking(self.api.host_key_checking): kwargs = dict( inventory=inventory_manager, variable_manager=variable_manager, loader=loader, options=self.api.options, passwords=getattr(self.api.options, 'passwords', {}), stdout_callback=callback ) if set_global_context: del kwargs['options'] task_queue_manager = TaskQueueManager(**kwargs) try: task_queue_manager.run(play) except SystemExit: # Mitogen forks our process and exits it in one # instance before returning # # This is fine, but it does lead to a very messy exit # by py.test which will essentially return with a test # that is first successful and then failed as each # forked process dies. # # To avoid this we commit suicide if we are run inside # a pytest session. Normally this would just result # in a exit code of zero, which is good. if 'pytest' in sys.modules: try: atexit._run_exitfuncs() except Exception: pass os.kill(os.getpid(), signal.SIGKILL) raise finally: if task_queue_manager is not None: task_queue_manager.cleanup() if set_global_context: # Ansible 2.8 introduces a global context which persists # during the lifetime of the process - for Suitable this # singleton/cache needs to be cleared after each call # to make sure that API calls do not carry over state. # # The docs hint at a future inclusion of local contexts, which # would of course be preferable. from ansible.utils.context_objects import GlobalCLIArgs GlobalCLIArgs._Singleton__instance = None log.debug(u'took {} to complete'.format(datetime.utcnow() - start)) return self.evaluate_results(callback)
[ "def", "execute", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "is_hooked_up", ",", "\"the module should be hooked up to the api\"", "if", "set_global_context", ":", "set_global_context", "(", "self", ".", "api", ".", "options", ")", "# legacy key=value pairs shorthand approach", "if", "args", ":", "self", ".", "module_args", "=", "module_args", "=", "self", ".", "get_module_args", "(", "args", ",", "kwargs", ")", "else", ":", "self", ".", "module_args", "=", "module_args", "=", "kwargs", "loader", "=", "DataLoader", "(", ")", "inventory_manager", "=", "SourcelessInventoryManager", "(", "loader", "=", "loader", ")", "for", "host", ",", "port", "in", "self", ".", "api", ".", "hosts_with_ports", ":", "inventory_manager", ".", "_inventory", ".", "add_host", "(", "host", ",", "group", "=", "'all'", ",", "port", "=", "port", ")", "for", "key", ",", "value", "in", "self", ".", "api", ".", "options", ".", "extra_vars", ".", "items", "(", ")", ":", "inventory_manager", ".", "_inventory", ".", "set_variable", "(", "'all'", ",", "key", ",", "value", ")", "variable_manager", "=", "VariableManager", "(", "loader", "=", "loader", ",", "inventory", "=", "inventory_manager", ")", "play_source", "=", "{", "'name'", ":", "\"Suitable Play\"", ",", "'hosts'", ":", "'all'", ",", "'gather_facts'", ":", "'no'", ",", "'tasks'", ":", "[", "{", "'action'", ":", "{", "'module'", ":", "self", ".", "module_name", ",", "'args'", ":", "module_args", ",", "}", ",", "'environment'", ":", "self", ".", "api", ".", "environment", ",", "}", "]", "}", "try", ":", "play", "=", "Play", ".", "load", "(", "play_source", ",", "variable_manager", "=", "variable_manager", ",", "loader", "=", "loader", ",", ")", "if", "self", ".", "api", ".", "strategy", ":", "play", ".", "strategy", "=", "self", ".", "api", ".", "strategy", "log", ".", "info", "(", "u'running {}'", ".", "format", "(", "u'- {module_name}: {module_args}'", ".", "format", "(", "module_name", "=", "self", ".", "module_name", ",", "module_args", "=", "module_args", ")", ")", ")", "start", "=", "datetime", ".", "utcnow", "(", ")", "task_queue_manager", "=", "None", "callback", "=", "SilentCallbackModule", "(", ")", "# ansible uses various levels of verbosity (from -v to -vvvvvv)", "# offering various amounts of debug information", "#", "# we keep it a bit simpler by activating all of it during debug,", "# and falling back to the default of 0 otherwise", "verbosity", "=", "self", ".", "api", ".", "options", ".", "verbosity", "==", "logging", ".", "DEBUG", "and", "6", "or", "0", "with", "ansible_verbosity", "(", "verbosity", ")", ":", "# host_key_checking is special, since not each connection", "# plugin handles it the same way, we need to apply both", "# environment variable and Ansible constant when running a", "# command in the runner to be successful", "with", "host_key_checking", "(", "self", ".", "api", ".", "host_key_checking", ")", ":", "kwargs", "=", "dict", "(", "inventory", "=", "inventory_manager", ",", "variable_manager", "=", "variable_manager", ",", "loader", "=", "loader", ",", "options", "=", "self", ".", "api", ".", "options", ",", "passwords", "=", "getattr", "(", "self", ".", "api", ".", "options", ",", "'passwords'", ",", "{", "}", ")", ",", "stdout_callback", "=", "callback", ")", "if", "set_global_context", ":", "del", "kwargs", "[", "'options'", "]", "task_queue_manager", "=", "TaskQueueManager", "(", "*", "*", "kwargs", ")", "try", ":", "task_queue_manager", ".", "run", "(", "play", ")", "except", "SystemExit", ":", "# Mitogen forks our process and exits it in one", "# instance before returning", "#", "# This is fine, but it does lead to a very messy exit", "# by py.test which will essentially return with a test", "# that is first successful and then failed as each", "# forked process dies.", "#", "# To avoid this we commit suicide if we are run inside", "# a pytest session. Normally this would just result", "# in a exit code of zero, which is good.", "if", "'pytest'", "in", "sys", ".", "modules", ":", "try", ":", "atexit", ".", "_run_exitfuncs", "(", ")", "except", "Exception", ":", "pass", "os", ".", "kill", "(", "os", ".", "getpid", "(", ")", ",", "signal", ".", "SIGKILL", ")", "raise", "finally", ":", "if", "task_queue_manager", "is", "not", "None", ":", "task_queue_manager", ".", "cleanup", "(", ")", "if", "set_global_context", ":", "# Ansible 2.8 introduces a global context which persists", "# during the lifetime of the process - for Suitable this", "# singleton/cache needs to be cleared after each call", "# to make sure that API calls do not carry over state.", "#", "# The docs hint at a future inclusion of local contexts, which", "# would of course be preferable.", "from", "ansible", ".", "utils", ".", "context_objects", "import", "GlobalCLIArgs", "GlobalCLIArgs", ".", "_Singleton__instance", "=", "None", "log", ".", "debug", "(", "u'took {} to complete'", ".", "format", "(", "datetime", ".", "utcnow", "(", ")", "-", "start", ")", ")", "return", "self", ".", "evaluate_results", "(", "callback", ")" ]
Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result.
[ "Puts", "args", "and", "kwargs", "in", "a", "way", "ansible", "can", "understand", ".", "Calls", "ansible", "and", "interprets", "the", "result", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L140-L271
seantis/suitable
suitable/module_runner.py
ModuleRunner.ignore_further_calls_to_server
def ignore_further_calls_to_server(self, server): """ Takes a server out of the list. """ log.error(u'ignoring further calls to {}'.format(server)) self.api.servers.remove(server)
python
def ignore_further_calls_to_server(self, server): """ Takes a server out of the list. """ log.error(u'ignoring further calls to {}'.format(server)) self.api.servers.remove(server)
[ "def", "ignore_further_calls_to_server", "(", "self", ",", "server", ")", ":", "log", ".", "error", "(", "u'ignoring further calls to {}'", ".", "format", "(", "server", ")", ")", "self", ".", "api", ".", "servers", ".", "remove", "(", "server", ")" ]
Takes a server out of the list.
[ "Takes", "a", "server", "out", "of", "the", "list", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L273-L276
seantis/suitable
suitable/module_runner.py
ModuleRunner.evaluate_results
def evaluate_results(self, callback): """ prepare the result of runner call for use with RunnerResults. """ for server, result in callback.unreachable.items(): log.error(u'{} could not be reached'.format(server)) log.debug(u'ansible-output =>\n{}'.format(pformat(result))) if self.api.ignore_unreachable: continue self.trigger_event(server, 'on_unreachable_host', ( self, server )) for server, answer in callback.contacted.items(): success = answer['success'] result = answer['result'] # none of the modules in our tests hit the 'failed' result # codepath (which seems to not be implemented by all modules) # seo we ignore this branch since it's rather trivial if result.get('failed'): # pragma: no cover success = False if 'rc' in result: if self.api.is_valid_return_code(result['rc']): success = True if not success: log.error(u'{} failed on {}'.format(self, server)) log.debug(u'ansible-output =>\n{}'.format(pformat(result))) if self.api.ignore_errors: continue self.trigger_event(server, 'on_module_error', ( self, server, result )) # XXX this is a weird structure because RunnerResults still works # like it did with Ansible 1.x, where the results where structured # like this return RunnerResults({ 'contacted': { server: answer['result'] for server, answer in callback.contacted.items() } })
python
def evaluate_results(self, callback): """ prepare the result of runner call for use with RunnerResults. """ for server, result in callback.unreachable.items(): log.error(u'{} could not be reached'.format(server)) log.debug(u'ansible-output =>\n{}'.format(pformat(result))) if self.api.ignore_unreachable: continue self.trigger_event(server, 'on_unreachable_host', ( self, server )) for server, answer in callback.contacted.items(): success = answer['success'] result = answer['result'] # none of the modules in our tests hit the 'failed' result # codepath (which seems to not be implemented by all modules) # seo we ignore this branch since it's rather trivial if result.get('failed'): # pragma: no cover success = False if 'rc' in result: if self.api.is_valid_return_code(result['rc']): success = True if not success: log.error(u'{} failed on {}'.format(self, server)) log.debug(u'ansible-output =>\n{}'.format(pformat(result))) if self.api.ignore_errors: continue self.trigger_event(server, 'on_module_error', ( self, server, result )) # XXX this is a weird structure because RunnerResults still works # like it did with Ansible 1.x, where the results where structured # like this return RunnerResults({ 'contacted': { server: answer['result'] for server, answer in callback.contacted.items() } })
[ "def", "evaluate_results", "(", "self", ",", "callback", ")", ":", "for", "server", ",", "result", "in", "callback", ".", "unreachable", ".", "items", "(", ")", ":", "log", ".", "error", "(", "u'{} could not be reached'", ".", "format", "(", "server", ")", ")", "log", ".", "debug", "(", "u'ansible-output =>\\n{}'", ".", "format", "(", "pformat", "(", "result", ")", ")", ")", "if", "self", ".", "api", ".", "ignore_unreachable", ":", "continue", "self", ".", "trigger_event", "(", "server", ",", "'on_unreachable_host'", ",", "(", "self", ",", "server", ")", ")", "for", "server", ",", "answer", "in", "callback", ".", "contacted", ".", "items", "(", ")", ":", "success", "=", "answer", "[", "'success'", "]", "result", "=", "answer", "[", "'result'", "]", "# none of the modules in our tests hit the 'failed' result", "# codepath (which seems to not be implemented by all modules)", "# seo we ignore this branch since it's rather trivial", "if", "result", ".", "get", "(", "'failed'", ")", ":", "# pragma: no cover", "success", "=", "False", "if", "'rc'", "in", "result", ":", "if", "self", ".", "api", ".", "is_valid_return_code", "(", "result", "[", "'rc'", "]", ")", ":", "success", "=", "True", "if", "not", "success", ":", "log", ".", "error", "(", "u'{} failed on {}'", ".", "format", "(", "self", ",", "server", ")", ")", "log", ".", "debug", "(", "u'ansible-output =>\\n{}'", ".", "format", "(", "pformat", "(", "result", ")", ")", ")", "if", "self", ".", "api", ".", "ignore_errors", ":", "continue", "self", ".", "trigger_event", "(", "server", ",", "'on_module_error'", ",", "(", "self", ",", "server", ",", "result", ")", ")", "# XXX this is a weird structure because RunnerResults still works", "# like it did with Ansible 1.x, where the results where structured", "# like this", "return", "RunnerResults", "(", "{", "'contacted'", ":", "{", "server", ":", "answer", "[", "'result'", "]", "for", "server", ",", "answer", "in", "callback", ".", "contacted", ".", "items", "(", ")", "}", "}", ")" ]
prepare the result of runner call for use with RunnerResults.
[ "prepare", "the", "result", "of", "runner", "call", "for", "use", "with", "RunnerResults", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L288-L336
seantis/suitable
suitable/api.py
install_strategy_plugins
def install_strategy_plugins(directories): """ Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's probably not something we'd ever have much of a use for. Call this function before using custom strategies on the :class:`Api` class. """ if isinstance(directories, str): directories = directories.split(':') for directory in directories: strategy_loader.add_directory(directory)
python
def install_strategy_plugins(directories): """ Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's probably not something we'd ever have much of a use for. Call this function before using custom strategies on the :class:`Api` class. """ if isinstance(directories, str): directories = directories.split(':') for directory in directories: strategy_loader.add_directory(directory)
[ "def", "install_strategy_plugins", "(", "directories", ")", ":", "if", "isinstance", "(", "directories", ",", "str", ")", ":", "directories", "=", "directories", ".", "split", "(", "':'", ")", "for", "directory", "in", "directories", ":", "strategy_loader", ".", "add_directory", "(", "directory", ")" ]
Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's probably not something we'd ever have much of a use for. Call this function before using custom strategies on the :class:`Api` class.
[ "Loads", "the", "given", "strategy", "plugins", "which", "is", "a", "list", "of", "directories", "a", "string", "with", "a", "single", "directory", "or", "a", "string", "with", "multiple", "directories", "separated", "by", "colon", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/api.py#L298-L315
seantis/suitable
suitable/api.py
Api.valid_return_codes
def valid_return_codes(self, *codes): """ Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log') """ previous_codes = self._valid_return_codes self._valid_return_codes = codes yield self._valid_return_codes = previous_codes
python
def valid_return_codes(self, *codes): """ Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log') """ previous_codes = self._valid_return_codes self._valid_return_codes = codes yield self._valid_return_codes = previous_codes
[ "def", "valid_return_codes", "(", "self", ",", "*", "codes", ")", ":", "previous_codes", "=", "self", ".", "_valid_return_codes", "self", ".", "_valid_return_codes", "=", "codes", "yield", "self", ".", "_valid_return_codes", "=", "previous_codes" ]
Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log')
[ "Sets", "codes", "which", "are", "considered", "valid", "when", "returned", "from", "command", "modules", ".", "The", "default", "is", "(", "0", ")", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/api.py#L280-L295
nielstron/pysyncthru
pysyncthru/__init__.py
construct_url
def construct_url(ip_address: str) -> str: """Construct the URL with a given IP address.""" if 'http://' not in ip_address and 'https://' not in ip_address: ip_address = '{}{}'.format('http://', ip_address) if ip_address[-1] == '/': ip_address = ip_address[:-1] return ip_address
python
def construct_url(ip_address: str) -> str: """Construct the URL with a given IP address.""" if 'http://' not in ip_address and 'https://' not in ip_address: ip_address = '{}{}'.format('http://', ip_address) if ip_address[-1] == '/': ip_address = ip_address[:-1] return ip_address
[ "def", "construct_url", "(", "ip_address", ":", "str", ")", "->", "str", ":", "if", "'http://'", "not", "in", "ip_address", "and", "'https://'", "not", "in", "ip_address", ":", "ip_address", "=", "'{}{}'", ".", "format", "(", "'http://'", ",", "ip_address", ")", "if", "ip_address", "[", "-", "1", "]", "==", "'/'", ":", "ip_address", "=", "ip_address", "[", ":", "-", "1", "]", "return", "ip_address" ]
Construct the URL with a given IP address.
[ "Construct", "the", "URL", "with", "a", "given", "IP", "address", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L12-L18
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.update
async def update(self) -> None: """ Retrieve the data from the printer. Throws ValueError if host does not support SyncThru """ url = '{}{}'.format(self.url, ENDPOINT) try: async with self._session.get(url) as response: json_dict = demjson.decode(await response.text(), strict=False) except aiohttp.ClientError: json_dict = {'status': {'status1': SyncThru.OFFLINE}} except demjson.JSONDecodeError: raise ValueError("Invalid host, does not support SyncThru.") self.data = json_dict
python
async def update(self) -> None: """ Retrieve the data from the printer. Throws ValueError if host does not support SyncThru """ url = '{}{}'.format(self.url, ENDPOINT) try: async with self._session.get(url) as response: json_dict = demjson.decode(await response.text(), strict=False) except aiohttp.ClientError: json_dict = {'status': {'status1': SyncThru.OFFLINE}} except demjson.JSONDecodeError: raise ValueError("Invalid host, does not support SyncThru.") self.data = json_dict
[ "async", "def", "update", "(", "self", ")", "->", "None", ":", "url", "=", "'{}{}'", ".", "format", "(", "self", ".", "url", ",", "ENDPOINT", ")", "try", ":", "async", "with", "self", ".", "_session", ".", "get", "(", "url", ")", "as", "response", ":", "json_dict", "=", "demjson", ".", "decode", "(", "await", "response", ".", "text", "(", ")", ",", "strict", "=", "False", ")", "except", "aiohttp", ".", "ClientError", ":", "json_dict", "=", "{", "'status'", ":", "{", "'status1'", ":", "SyncThru", ".", "OFFLINE", "}", "}", "except", "demjson", ".", "JSONDecodeError", ":", "raise", "ValueError", "(", "\"Invalid host, does not support SyncThru.\"", ")", "self", ".", "data", "=", "json_dict" ]
Retrieve the data from the printer. Throws ValueError if host does not support SyncThru
[ "Retrieve", "the", "data", "from", "the", "printer", ".", "Throws", "ValueError", "if", "host", "does", "not", "support", "SyncThru" ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L35-L49
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.model
def model(self): """Return the model name of the printer.""" try: return self.data.get('identity').get('model_name') except (KeyError, AttributeError): return self.device_status_simple('')
python
def model(self): """Return the model name of the printer.""" try: return self.data.get('identity').get('model_name') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "model", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'model_name'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_status_simple", "(", "''", ")" ]
Return the model name of the printer.
[ "Return", "the", "model", "name", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L66-L71
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.location
def location(self): """Return the location of the printer.""" try: return self.data.get('identity').get('location') except (KeyError, AttributeError): return self.device_status_simple('')
python
def location(self): """Return the location of the printer.""" try: return self.data.get('identity').get('location') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "location", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'location'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_status_simple", "(", "''", ")" ]
Return the location of the printer.
[ "Return", "the", "location", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L73-L78
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.serial_number
def serial_number(self): """Return the serial number of the printer.""" try: return self.data.get('identity').get('serial_num') except (KeyError, AttributeError): return self.device_status_simple('')
python
def serial_number(self): """Return the serial number of the printer.""" try: return self.data.get('identity').get('serial_num') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "serial_number", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'serial_num'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_status_simple", "(", "''", ")" ]
Return the serial number of the printer.
[ "Return", "the", "serial", "number", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L80-L85
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.hostname
def hostname(self): """Return the hostname of the printer.""" try: return self.data.get('identity').get('host_name') except (KeyError, AttributeError): return self.device_status_simple('')
python
def hostname(self): """Return the hostname of the printer.""" try: return self.data.get('identity').get('host_name') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "hostname", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'host_name'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_status_simple", "(", "''", ")" ]
Return the hostname of the printer.
[ "Return", "the", "hostname", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L87-L92
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.device_status
def device_status(self): """Return the status of the device as string.""" try: return self.device_status_simple( self.data.get('status').get('status1')) except (KeyError, AttributeError): return self.device_status_simple('')
python
def device_status(self): """Return the status of the device as string.""" try: return self.device_status_simple( self.data.get('status').get('status1')) except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "device_status", "(", "self", ")", ":", "try", ":", "return", "self", ".", "device_status_simple", "(", "self", ".", "data", ".", "get", "(", "'status'", ")", ".", "get", "(", "'status1'", ")", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_status_simple", "(", "''", ")" ]
Return the status of the device as string.
[ "Return", "the", "status", "of", "the", "device", "as", "string", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L94-L100
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.capability
def capability(self) -> Dict[str, Any]: """Return the capabilities of the printer.""" try: return self.data.get('capability', {}) except (KeyError, AttributeError): return {}
python
def capability(self) -> Dict[str, Any]: """Return the capabilities of the printer.""" try: return self.data.get('capability', {}) except (KeyError, AttributeError): return {}
[ "def", "capability", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'capability'", ",", "{", "}", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "{", "}" ]
Return the capabilities of the printer.
[ "Return", "the", "capabilities", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L102-L107
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.toner_status
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NAMES: try: toner_stat = self.data.get( '{}_{}'.format(SyncThru.TONER, color), {}) if filter_supported and toner_stat.get('opt', 0) == 0: continue else: toner_status[color] = toner_stat except (KeyError, AttributeError): toner_status[color] = {} return toner_status
python
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NAMES: try: toner_stat = self.data.get( '{}_{}'.format(SyncThru.TONER, color), {}) if filter_supported and toner_stat.get('opt', 0) == 0: continue else: toner_status[color] = toner_stat except (KeyError, AttributeError): toner_status[color] = {} return toner_status
[ "def", "toner_status", "(", "self", ",", "filter_supported", ":", "bool", "=", "True", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "toner_status", "=", "{", "}", "for", "color", "in", "self", ".", "COLOR_NAMES", ":", "try", ":", "toner_stat", "=", "self", ".", "data", ".", "get", "(", "'{}_{}'", ".", "format", "(", "SyncThru", ".", "TONER", ",", "color", ")", ",", "{", "}", ")", "if", "filter_supported", "and", "toner_stat", ".", "get", "(", "'opt'", ",", "0", ")", "==", "0", ":", "continue", "else", ":", "toner_status", "[", "color", "]", "=", "toner_stat", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "toner_status", "[", "color", "]", "=", "{", "}", "return", "toner_status" ]
Return the state of all toners cartridges.
[ "Return", "the", "state", "of", "all", "toners", "cartridges", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L116-L129
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.input_tray_status
def input_tray_status(self, filter_supported: bool = True) -> Dict[int, Any]: """Return the state of all input trays.""" tray_status = {} for i in range(1, 5): try: tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {}) if filter_supported and tray_stat.get('opt', 0) == 0: continue else: tray_status[i] = tray_stat except (KeyError, AttributeError): tray_status[i] = {} return tray_status
python
def input_tray_status(self, filter_supported: bool = True) -> Dict[int, Any]: """Return the state of all input trays.""" tray_status = {} for i in range(1, 5): try: tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {}) if filter_supported and tray_stat.get('opt', 0) == 0: continue else: tray_status[i] = tray_stat except (KeyError, AttributeError): tray_status[i] = {} return tray_status
[ "def", "input_tray_status", "(", "self", ",", "filter_supported", ":", "bool", "=", "True", ")", "->", "Dict", "[", "int", ",", "Any", "]", ":", "tray_status", "=", "{", "}", "for", "i", "in", "range", "(", "1", ",", "5", ")", ":", "try", ":", "tray_stat", "=", "self", ".", "data", ".", "get", "(", "'{}{}'", ".", "format", "(", "SyncThru", ".", "TRAY", ",", "i", ")", ",", "{", "}", ")", "if", "filter_supported", "and", "tray_stat", ".", "get", "(", "'opt'", ",", "0", ")", "==", "0", ":", "continue", "else", ":", "tray_status", "[", "i", "]", "=", "tray_stat", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "tray_status", "[", "i", "]", "=", "{", "}", "return", "tray_status" ]
Return the state of all input trays.
[ "Return", "the", "state", "of", "all", "input", "trays", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L131-L144
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.output_tray_status
def output_tray_status(self) -> Dict[int, Dict[str, str]]: """Return the state of all output trays.""" tray_status = {} try: tray_stat = self.data.get('outputTray', []) for i, stat in enumerate(tray_stat): tray_status[i] = { 'name': stat[0], 'capacity': stat[1], 'status': stat[2], } except (KeyError, AttributeError): tray_status = {} return tray_status
python
def output_tray_status(self) -> Dict[int, Dict[str, str]]: """Return the state of all output trays.""" tray_status = {} try: tray_stat = self.data.get('outputTray', []) for i, stat in enumerate(tray_stat): tray_status[i] = { 'name': stat[0], 'capacity': stat[1], 'status': stat[2], } except (KeyError, AttributeError): tray_status = {} return tray_status
[ "def", "output_tray_status", "(", "self", ")", "->", "Dict", "[", "int", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "tray_status", "=", "{", "}", "try", ":", "tray_stat", "=", "self", ".", "data", ".", "get", "(", "'outputTray'", ",", "[", "]", ")", "for", "i", ",", "stat", "in", "enumerate", "(", "tray_stat", ")", ":", "tray_status", "[", "i", "]", "=", "{", "'name'", ":", "stat", "[", "0", "]", ",", "'capacity'", ":", "stat", "[", "1", "]", ",", "'status'", ":", "stat", "[", "2", "]", ",", "}", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "tray_status", "=", "{", "}", "return", "tray_status" ]
Return the state of all output trays.
[ "Return", "the", "state", "of", "all", "output", "trays", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L146-L159
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.drum_status
def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all drums.""" drum_status = {} for color in self.COLOR_NAMES: try: drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color), {}) if filter_supported and drum_stat.get('opt', 0) == 0: continue else: drum_status[color] = drum_stat except (KeyError, AttributeError): drum_status[color] = {} return drum_status
python
def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all drums.""" drum_status = {} for color in self.COLOR_NAMES: try: drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color), {}) if filter_supported and drum_stat.get('opt', 0) == 0: continue else: drum_status[color] = drum_stat except (KeyError, AttributeError): drum_status[color] = {} return drum_status
[ "def", "drum_status", "(", "self", ",", "filter_supported", ":", "bool", "=", "True", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "drum_status", "=", "{", "}", "for", "color", "in", "self", ".", "COLOR_NAMES", ":", "try", ":", "drum_stat", "=", "self", ".", "data", ".", "get", "(", "'{}_{}'", ".", "format", "(", "SyncThru", ".", "DRUM", ",", "color", ")", ",", "{", "}", ")", "if", "filter_supported", "and", "drum_stat", ".", "get", "(", "'opt'", ",", "0", ")", "==", "0", ":", "continue", "else", ":", "drum_status", "[", "color", "]", "=", "drum_stat", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "drum_status", "[", "color", "]", "=", "{", "}", "return", "drum_status" ]
Return the state of all drums.
[ "Return", "the", "state", "of", "all", "drums", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L161-L174
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
pdb_run
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None: """ Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger. """ # noinspection PyBroadException try: func(*args, **kwargs) except: # nopep8 type_, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
python
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None: """ Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger. """ # noinspection PyBroadException try: func(*args, **kwargs) except: # nopep8 type_, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
[ "def", "pdb_run", "(", "func", ":", "Callable", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "# noinspection PyBroadException", "try", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "# nopep8", "type_", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "traceback", ".", "print_exc", "(", ")", "pdb", ".", "post_mortem", "(", "tb", ")" ]
Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger.
[ "Calls", "func", "(", "*", "args", "**", "kwargs", ")", ";", "if", "it", "raises", "an", "exception", "break", "into", "the", "pdb", "debugger", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L48-L59
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
get_class_name_from_frame
def get_class_name_from_frame(fr: FrameType) -> Optional[str]: """ A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It returns ``None`` otherwise. """ # http://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object # noqa args, _, _, value_dict = inspect.getargvalues(fr) # we check the first parameter for the frame function is named 'self' if len(args) and args[0] == 'self': # in that case, 'self' will be referenced in value_dict instance = value_dict.get('self', None) if instance: # return its class cls = getattr(instance, '__class__', None) if cls: return cls.__name__ return None # return None otherwise return None
python
def get_class_name_from_frame(fr: FrameType) -> Optional[str]: """ A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It returns ``None`` otherwise. """ # http://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object # noqa args, _, _, value_dict = inspect.getargvalues(fr) # we check the first parameter for the frame function is named 'self' if len(args) and args[0] == 'self': # in that case, 'self' will be referenced in value_dict instance = value_dict.get('self', None) if instance: # return its class cls = getattr(instance, '__class__', None) if cls: return cls.__name__ return None # return None otherwise return None
[ "def", "get_class_name_from_frame", "(", "fr", ":", "FrameType", ")", "->", "Optional", "[", "str", "]", ":", "# http://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object # noqa", "args", ",", "_", ",", "_", ",", "value_dict", "=", "inspect", ".", "getargvalues", "(", "fr", ")", "# we check the first parameter for the frame function is named 'self'", "if", "len", "(", "args", ")", "and", "args", "[", "0", "]", "==", "'self'", ":", "# in that case, 'self' will be referenced in value_dict", "instance", "=", "value_dict", ".", "get", "(", "'self'", ",", "None", ")", "if", "instance", ":", "# return its class", "cls", "=", "getattr", "(", "instance", ",", "'__class__'", ",", "None", ")", "if", "cls", ":", "return", "cls", ".", "__name__", "return", "None", "# return None otherwise", "return", "None" ]
A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It returns ``None`` otherwise.
[ "A", "frame", "contains", "information", "about", "a", "specific", "call", "in", "the", "Python", "call", "stack", ";", "see", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "3", "/", "library", "/", "inspect", ".", "html", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L74-L95
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
get_caller_name
def get_caller_name(back: int = 0) -> str: """ Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_name def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("I am: " + who_am_i()) print("I was called by: " + get_caller_name()) print("That was called by: " + get_caller_name(back=1)) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() will produce: .. code-block:: none I am: MyClass.classfunc I was called by: f2 That was called by: f1 """ # http://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback # noqa try: # noinspection PyProtectedMember frame = sys._getframe(back + 2) except ValueError: # Stack isn't deep enough. return '?' function_name = frame.f_code.co_name class_name = get_class_name_from_frame(frame) if class_name: return "{}.{}".format(class_name, function_name) return function_name
python
def get_caller_name(back: int = 0) -> str: """ Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_name def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("I am: " + who_am_i()) print("I was called by: " + get_caller_name()) print("That was called by: " + get_caller_name(back=1)) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() will produce: .. code-block:: none I am: MyClass.classfunc I was called by: f2 That was called by: f1 """ # http://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback # noqa try: # noinspection PyProtectedMember frame = sys._getframe(back + 2) except ValueError: # Stack isn't deep enough. return '?' function_name = frame.f_code.co_name class_name = get_class_name_from_frame(frame) if class_name: return "{}.{}".format(class_name, function_name) return function_name
[ "def", "get_caller_name", "(", "back", ":", "int", "=", "0", ")", "->", "str", ":", "# http://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback # noqa", "try", ":", "# noinspection PyProtectedMember", "frame", "=", "sys", ".", "_getframe", "(", "back", "+", "2", ")", "except", "ValueError", ":", "# Stack isn't deep enough.", "return", "'?'", "function_name", "=", "frame", ".", "f_code", ".", "co_name", "class_name", "=", "get_class_name_from_frame", "(", "frame", ")", "if", "class_name", ":", "return", "\"{}.{}\"", ".", "format", "(", "class_name", ",", "function_name", ")", "return", "function_name" ]
Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_name def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("I am: " + who_am_i()) print("I was called by: " + get_caller_name()) print("That was called by: " + get_caller_name(back=1)) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() will produce: .. code-block:: none I am: MyClass.classfunc I was called by: f2 That was called by: f1
[ "Return", "details", "about", "the", "CALLER", "OF", "THE", "CALLER", "(", "plus", "n", "calls", "further", "back", ")", "of", "this", "function", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L98-L151