Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def find_implementations(interface, recurse, abstract, result): for item in MetaComponent.implementations: if (item['interface'] == interface and (abstract or not item['abstract'])): extend_unique(result, [item['class']]) if recurse: ...
[ "Find implementations of an interface or of one of its descendants and\n extend result with the classes found." ]
Please provide a description of the function:def get_queryset(self): queryset = self.model.objects.all() analysis_uuid = self.request.query_params.get('analysis', None) item_uuid = self.request.query_params.get('item', None) if analysis_uuid is not None: queryset = q...
[ "\n Optionally restricts the returned purchases analysis track to\n a given analysis and/or a given item,\n by filtering against `analysis` and `item` query parameters in the URL.\n The query parameters values should be the uuid of the analysis or of the item\n " ]
Please provide a description of the function:def process(self, frames, eod, spec_range=120.0): samples = frames[:, 0] nsamples = len(frames[:, 0]) if nsamples != self.blocksize: self.window = self.window_function(nsamples) samples *= self.window while nsamp...
[ " Returns a tuple containing the spectral centroid and\n the spectrum (dB scales) of the input audio frames.\n FFT window sizes are adatable to the input frame size." ]
Please provide a description of the function:def draw_peaks(self, x, peaks, line_color): y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5 y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5 if self.previous_y: self.draw.line( ...
[ "Draw 2 peaks at x" ]
Please provide a description of the function:def draw_peaks_inverted(self, x, peaks, line_color): y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5 y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5 if self.previous_y and x < self.image_width...
[ "Draw 2 inverted peaks at x" ]
Please provide a description of the function:def draw_anti_aliased_pixels(self, x, y1, y2, color): y_max = max(y1, y2) y_max_int = int(y_max) alpha = y_max - y_max_int if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height: current_pix = self.pixel[in...
[ " vertical anti-aliasing at y1 and y2 " ]
Please provide a description of the function:def post_process(self): self.image.putdata(self.pixels) self.image = self.image.transpose(Image.ROTATE_90)
[ " Apply last 2D transforms" ]
Please provide a description of the function:def write_metadata(self): import mutagen from mutagen import id3 id3 = id3.ID3(self.filename) for tag in self.metadata.keys(): value = self.metadata[tag] frame = mutagen.id3.Frames[tag](3, value) t...
[ "Write all ID3v2.4 tags to file from self.metadata" ]
Please provide a description of the function:def get_completerlib(): #----------------------------------------------------------------------------- # Copyright (C) 2010-2011 The IPython Development Team. # # Distributed under the terms of the BSD License. # # The full license is in the f...
[ "Implementations for various useful completers.\n\n These are all loaded by default by IPython.\n ", "\n Return the list containing the names of the modules available in the given\n folder.\n ", "\n Returns a list containing the names of all the modules available in the\n ...
Please provide a description of the function:def check_backends(title): path = os.path.dirname(fulltext.backends.__file__) errs = [] for name in os.listdir(path): if not name.endswith('.py'): continue if name == '__init__.py': continue mod_name = "fullte...
[ "Invoke test() for all backends and fail (raise) if some dep\n is missing.\n " ]
Please provide a description of the function:def main(args=sys.argv[1:]): opt = docopt(main.__doc__.strip(), args, options_first=True) config_logging(opt['--verbose']) if opt['check']: check_backends(opt['--title']) elif opt['extract']: handler = fulltext.get if opt['--fi...
[ "Extract text from a file.\n\n Commands:\n extract - extract text from path\n check - make sure all deps are installed\n\n Usage:\n fulltext extract [-v] [-f] <path>...\n fulltext check [-t]\n\n Options:\n -f, --file Open file first.\n -t, --title ...
Please provide a description of the function:def register_backend(mimetype, module, extensions=None): if mimetype in MIMETYPE_TO_BACKENDS: warn("overwriting %r mimetype which was already set" % mimetype) MIMETYPE_TO_BACKENDS[mimetype] = module if extensions is None: try: ext...
[ "Register a backend.\n `mimetype`: a mimetype string (e.g. 'text/plain')\n `module`: an import string (e.g. path.to.my.module)\n `extensions`: a list of extensions (e.g. ['txt', 'text'])\n " ]
Please provide a description of the function:def is_binary(f): # NOTE: order matters here. We don't bail on Python 2 just yet. Both # codecs.open() and io.open() can open in text mode, both set the encoding # attribute. We must do that check first. # If it has a decoding attribute with a value, it...
[ "Return True if binary mode." ]
Please provide a description of the function:def handle_path(backend_inst, path, **kwargs): if callable(getattr(backend_inst, 'handle_path', None)): # Prefer handle_path() if present. LOGGER.debug("using handle_path") return backend_inst.handle_path(path) elif callable(getattr(back...
[ "\n Handle a path.\n\n Called by `get()` when provided a path. This function will prefer the\n backend's `handle_path()` if one is provided Otherwise, it will open the\n given path then use `handle_fobj()`.\n " ]
Please provide a description of the function:def handle_fobj(backend, f, **kwargs): if not is_binary(f): raise AssertionError('File must be opened in binary mode.') if callable(getattr(backend, 'handle_fobj', None)): # Prefer handle_fobj() if present. LOGGER.debug("using handle_fob...
[ "\n Handle a file-like object.\n\n Called by `get()` when provided a file-like. This function will prefer the\n backend's `handle_fobj()` if one is provided. Otherwise, it will write the\n data to a temporary file and call `handle_path()`.\n " ]
Please provide a description of the function:def backend_from_mime(mime): try: mod_name = MIMETYPE_TO_BACKENDS[mime] except KeyError: msg = "No handler for %r, defaulting to %r" % (mime, DEFAULT_MIME) if 'FULLTEXT_TESTING' in os.environ: warn(msg) else: ...
[ "Determine backend module object from a mime string." ]
Please provide a description of the function:def backend_from_fname(name): ext = splitext(name)[1] try: mime = EXTS_TO_MIMETYPES[ext] except KeyError: try: f = open(name, 'rb') except IOError as e: # The file may not exist, we are being asked to determ...
[ "Determine backend module object from a file name." ]
Please provide a description of the function:def backend_from_fobj(f): if magic is None: warn("magic lib is not installed; assuming mime type %r" % ( DEFAULT_MIME)) return backend_from_mime(DEFAULT_MIME) else: offset = f.tell() try: f.seek(0) ...
[ "Determine backend module object from a file object." ]
Please provide a description of the function:def backend_inst_from_mod(mod, encoding, encoding_errors, kwargs): kw = dict(encoding=encoding, encoding_errors=encoding_errors, kwargs=kwargs) try: klass = getattr(mod, "Backend") except AttributeError: raise AttributeError("%r...
[ "Given a mod and a set of opts return an instantiated\n Backend class.\n " ]
Please provide a description of the function:def get(path_or_file, default=SENTINAL, mime=None, name=None, backend=None, encoding=None, encoding_errors=None, kwargs=None, _wtitle=False): try: text, title = _get( path_or_file, default=default, mime=mime, name=name, ...
[ "\n Get document full text.\n\n Accepts a path or file-like object.\n * If given, `default` is returned instead of an error.\n * `backend` is either a module object or a string specifying which\n default backend to use (e.g. \"doc\"); take a look at backends\n directory to see a list of de...
Please provide a description of the function:def memoize(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items()))) try: return cache[key] except KeyError: ret = cache[key] = fun(*args, **kwargs) retu...
[ "A simple memoize decorator for functions supporting (hashable)\n positional arguments.\n It also provides a cache_clear() function for clearing the cache:\n\n >>> @memoize\n ... def foo()\n ... return 1\n ...\n >>> foo()\n 1\n >>> foo.cache_clear()\n >>>\n ", "Clear cache...
Please provide a description of the function:def hilite(s, ok=True, bold=False): if not term_supports_colors(): return s attr = [] if ok is None: # no color pass elif ok: # green attr.append('32') else: # red attr.append('31') if bold: attr.appen...
[ "Return an highlighted version of 'string'." ]
Please provide a description of the function:def fobj_to_tempfile(f, suffix=''): with tempfile.NamedTemporaryFile( dir=TEMPDIR, suffix=suffix, delete=False) as t: shutil.copyfileobj(f, t) try: yield t.name finally: os.remove(t.name)
[ "Context manager which copies a file object to disk and return its\n name. When done the file is deleted.\n " ]
Please provide a description of the function:def safe_print(text, file=sys.stdout, flush=False): if not isinstance(text, basestring): return print(text, file=file) try: file.write(text) except UnicodeEncodeError: bytes_string = text.encode(file.encoding, 'backslashreplace') ...
[ "Prints a (unicode) string to the console, encoded depending on\n the stdout/file encoding (eg. cp437 on Windows). This is to avoid\n encoding errors in case of funky path names.\n Works with Python 2 and 3.\n " ]
Please provide a description of the function:def rm(pattern): paths = glob.glob(pattern) for path in paths: if path.startswith('.git/'): continue if os.path.isdir(path): def onerror(fun, path, excinfo): exc = excinfo[1] if exc.errno !=...
[ "Recursively remove a file or dir by pattern." ]
Please provide a description of the function:def help(): safe_print('Run "make [-p <PYTHON>] <target>" where <target> is one of:') for name in sorted(_cmds): safe_print( " %-20s %s" % (name.replace('_', '-'), _cmds[name] or '')) sys.exit(1)
[ "Print this help" ]
Please provide a description of the function:def clean(): rm("$testfn*") rm("*.bak") rm("*.core") rm("*.egg-info") rm("*.orig") rm("*.pyc") rm("*.pyd") rm("*.pyo") rm("*.rej") rm("*.so") rm("*.~") rm("*__pycache__") rm(".coverage") rm(".tox") rm(".coverag...
[ "Deletes dev files" ]
Please provide a description of the function:def lint(): py_files = subprocess.check_output("git ls-files") if PY3: py_files = py_files.decode() py_files = [x for x in py_files.split() if x.endswith('.py')] py_files = ' '.join(py_files) sh("%s -m flake8 %s" % (PYTHON, py_files), nolog=T...
[ "Run flake8 against all py files" ]
Please provide a description of the function:def coverage(): # Note: coverage options are controlled by .coveragerc file install() test_setup() sh("%s -m coverage run %s" % (PYTHON, TEST_SCRIPT)) sh("%s -m coverage report" % PYTHON) sh("%s -m coverage html" % PYTHON) sh("%s -m webbrowse...
[ "Run coverage tests." ]
Please provide a description of the function:def venv(): try: import virtualenv # NOQA except ImportError: sh("%s -m pip install virtualenv" % PYTHON) if not os.path.isdir("venv"): sh("%s -m virtualenv venv" % PYTHON) sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TX...
[ "Install venv + deps." ]
Please provide a description of the function:def compute_transformed(context): key_composite = compute_key_composite( password=context._._.password, keyfile=context._._.keyfile ) kdf_parameters = context._.header.value.dynamic_header.kdf_parameters.data.dict if context._._.transfo...
[ "Compute transformed key for opening database" ]
Please provide a description of the function:def compute_header_hmac_hash(context): return hmac.new( hashlib.sha512( b'\xff' * 8 + hashlib.sha512( context._.header.value.dynamic_header.master_seed.data + context.transformed_key + ...
[ "Compute HMAC-SHA256 hash of header.\n Used to prevent header tampering." ]
Please provide a description of the function:def compute_payload_block_hash(this): return hmac.new( hashlib.sha512( struct.pack('<Q', this._index) + hashlib.sha512( this._._.header.value.dynamic_header.master_seed.data + this._.transformed_key + ...
[ "Compute hash of each payload block.\n Used to prevent payload corruption and tampering." ]
Please provide a description of the function:def compute_transformed(context): if context._._.transformed_key is not None: transformed_key = context._._transformed_key else: transformed_key = aes_kdf( context._.header.value.dynamic_header.transform_seed.data, contex...
[ "Compute transformed key for opening database" ]
Please provide a description of the function:def set_key(self, key): key_len = len(key) if key_len not in [16, 24, 32]: # XXX: add padding? raise KeyError("key must be 16, 24 or 32 bytes") if key_len % 4: # XXX: add padding? raise KeyErro...
[ "Init." ]
Please provide a description of the function:def decrypt(self, block): if len(block) % 16: raise ValueError("block size must be a multiple of 16") plaintext = b'' while block: a, b, c, d = struct.unpack("<4L", block[:16]) temp = [a, b, c, d] ...
[ "Decrypt blocks." ]
Please provide a description of the function:def encrypt(self, block): if len(block) % 16: raise ValueError("block size must be a multiple of 16") ciphertext = b'' while block: a, b, c, d = struct.unpack("<4L", block[0:16]) temp = [a, b, c, d] ...
[ "Encrypt blocks." ]
Please provide a description of the function:def aes_kdf(key, rounds, password=None, keyfile=None): cipher = AES.new(key, AES.MODE_ECB) key_composite = compute_key_composite( password=password, keyfile=keyfile ) # get the number of rounds from the header and transform the key_comp...
[ "Set up a context for AES128-ECB encryption to find transformed_key" ]
Please provide a description of the function:def compute_key_composite(password=None, keyfile=None): # hash the password if password: password_composite = hashlib.sha256(password.encode('utf-8')).digest() else: password_composite = b'' # hash the keyfile if keyfile: # t...
[ "Compute composite key.\n Used in header verification and payload decryption." ]
Please provide a description of the function:def compute_master(context): # combine the transformed key with the header master seed to find the master_key master_key = hashlib.sha256( context._.header.value.dynamic_header.master_seed.data + context.transformed_key).digest() return mast...
[ "Computes master key from transformed key and master seed.\n Used in payload decryption." ]
Please provide a description of the function:def Unprotect(protected_stream_id, protected_stream_key, subcon): return Switch( protected_stream_id, {'arcfourvariant': ARCFourVariantStream(protected_stream_key, subcon), 'salsa20': Salsa20Stream(protected_stream_key, subcon), 'c...
[ "Select stream cipher based on protected_stream_id" ]
Please provide a description of the function:def encrypt(self,plaintext,n=''): #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('e',None) # makes sure you don't encrypt with a cipher that has started dec...
[ "Encrypt some plaintext\n\n plaintext = a string of binary data\n n = the 'tweak' value when the chaining mode is XTS\n\n The encrypt function will encrypt the supplied plaintext.\n The behavior varies slightly depending on the chaining mode.\n\n ECB, CBC:\n ...
Please provide a description of the function:def decrypt(self,ciphertext,n=''): #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('d',None) # makes sure you don't decrypt with a cipher that has started enc...
[ "Decrypt some ciphertext\n\n ciphertext = a string of binary data\n n = the 'tweak' value when the chaining mode is XTS\n\n The decrypt function will decrypt the supplied ciphertext.\n The behavior varies slightly depending on the chaining mode.\n\n ECB, CBC:\n ...
Please provide a description of the function:def final(self,style='pkcs7'): # TODO: after calling final, reset the IV? so the cipher is as good as new? assert self.mode not in (MODE_XTS, MODE_CMAC) # finalizing (=padding) doesn't make sense when in XTS or CMAC mode if self.ed == b'e': ...
[ "Finalizes the encryption by padding the cache\n\n padfct = padding function\n import from CryptoPlus.Util.padding\n\n For ECB, CBC: the remaining bytes in the cache will be padded and\n encrypted.\n For OFB,CFB, CTR: an encrypted padding will be ret...
Please provide a description of the function:def update(self, data, ed): if ed == 'e': encrypted_blocks = b'' self.cache += data if len(self.cache) < self.blocksize: return b'' for i in range(0, len(self.cache)-self.blocksize+1, self.block...
[ "Processes the given ciphertext/plaintext\n\n Inputs:\n data: raw string of any length\n ed: 'e' for encryption, 'd' for decryption\n Output:\n processed raw string block(s), if any\n\n When the supplied data is not a multiple of the blocksize\n of th...
Please provide a description of the function:def _datetime_to_utc(self, dt): if not dt.tzinfo: dt = dt.replace(tzinfo=tz.gettz()) return dt.astimezone(tz.gettz('UTC'))
[ "Convert naive datetimes to UTC" ]
Please provide a description of the function:def _encode_time(self, value): if self._kp.version >= (4, 0): diff_seconds = int( ( self._datetime_to_utc(value) - datetime( year=1, month=1,...
[ "Convert datetime to base64 or plaintext string" ]
Please provide a description of the function:def _decode_time(self, text): if self._kp.version >= (4, 0): # decode KDBX4 date from b64 format try: return ( datetime(year=1, month=1, day=1, tzinfo=tz.gettz('UTC')) + timedel...
[ "Convert base64 time or plaintext time to datetime" ]
Please provide a description of the function:def fromrdd(rdd, dims=None, nrecords=None, dtype=None, labels=None, ordered=False): from .images import Images from bolt.spark.array import BoltArraySpark if dims is None or dtype is None: item = rdd.values().first() dtype = item.dtype ...
[ "\n Load images from a Spark RDD.\n\n Input RDD must be a collection of key-value pairs\n where keys are singleton tuples indexing images,\n and values are 2d or 3d ndarrays.\n\n Parameters\n ----------\n rdd : SparkRDD\n An RDD containing the images.\n\n dims : tuple or array, option...
Please provide a description of the function:def fromarray(values, labels=None, npartitions=None, engine=None): from .images import Images import bolt if isinstance(values, bolt.spark.array.BoltArraySpark): return Images(values) values = asarray(values) if values.ndim < 2: ra...
[ "\n Load images from an array.\n\n First dimension will be used to index images,\n so remaining dimensions after the first should\n be the dimensions of the images,\n e.g. (3, 100, 200) for 3 x (100, 200) images\n\n Parameters\n ----------\n values : array-like\n The array of images. ...
Please provide a description of the function:def fromlist(items, accessor=None, keys=None, dims=None, dtype=None, labels=None, npartitions=None, engine=None): if spark and isinstance(engine, spark): nrecords = len(items) if keys: items = zip(keys, items) else: ke...
[ "\n Load images from a list of items using the given accessor.\n\n Parameters\n ----------\n accessor : function\n Apply to each item from the list to yield an image.\n\n keys : list, optional, default=None\n An optional list of keys.\n\n dims : tuple, optional, default=None\n ...
Please provide a description of the function:def frompath(path, accessor=None, ext=None, start=None, stop=None, recursive=False, npartitions=None, dims=None, dtype=None, labels=None, recount=False, engine=None, credentials=None): from thunder.readers import get_parallel_reader reader = get_parallel_reader(...
[ "\n Load images from a path using the given accessor.\n\n Supports both local and remote filesystems.\n\n Parameters\n ----------\n accessor : function\n Apply to each item after loading to yield an image.\n\n ext : str, optional, default=None\n File extension.\n\n npartitions : i...
Please provide a description of the function:def frombinary(path, shape=None, dtype=None, ext='bin', start=None, stop=None, recursive=False, nplanes=None, npartitions=None, labels=None, conf='conf.json', order='C', engine=None, credentials=None): import json from thunder.readers import get_file_reader, Fil...
[ "\n Load images from flat binary files.\n\n Assumes one image per file, each with the shape and ordering as given\n by the input arguments.\n\n Parameters\n ----------\n path : str\n Path to data files or directory, specified as either a local filesystem path\n or in a URI-like forma...
Please provide a description of the function:def fromtif(path, ext='tif', start=None, stop=None, recursive=False, nplanes=None, npartitions=None, labels=None, engine=None, credentials=None, discard_extra=False): from tifffile import TiffFile if nplanes is not None and nplanes <= 0: raise ValueErro...
[ "\n Loads images from single or multi-page TIF files.\n\n Parameters\n ----------\n path : str\n Path to data files or directory, specified as either a local filesystem path\n or in a URI-like format, including scheme. May include a single '*' wildcard character.\n\n ext : string, optio...
Please provide a description of the function:def frompng(path, ext='png', start=None, stop=None, recursive=False, npartitions=None, labels=None, engine=None, credentials=None): from scipy.misc import imread def getarray(idx_buffer_filename): idx, buf, _ = idx_buffer_filename fbuf = BytesIO...
[ "\n Load images from PNG files.\n\n Parameters\n ----------\n path : str\n Path to data files or directory, specified as either a local filesystem path\n or in a URI-like format, including scheme. May include a single '*' wildcard character.\n\n ext : string, optional, default = 'tif'\n...
Please provide a description of the function:def fromrandom(shape=(10, 50, 50), npartitions=1, seed=42, engine=None): seed = hash(seed) def generate(v): random.seed(seed + v) return random.randn(*shape[1:]) return fromlist(range(shape[0]), accessor=generate, npartitions=npartitions, e...
[ "\n Generate random image data.\n\n Parameters\n ----------\n shape : tuple, optional, default=(10, 50, 50)\n Dimensions of images.\n\n npartitions : int, optional, default=1\n Number of partitions.\n\n seed : int, optional, default=42\n Random seed.\n " ]
Please provide a description of the function:def fromexample(name=None, engine=None): datasets = ['mouse', 'fish'] if name is None: print('Availiable example image datasets') for d in datasets: print('- ' + d) return check_options(name, datasets) path = 's3n:/...
[ "\n Load example image data.\n\n Data are downloaded from S3, so this method requires an internet connection.\n\n Parameters\n ----------\n name : str\n Name of dataset, if not specified will print options.\n\n engine : object, default = None\n Computational engine (e.g. a SparkConte...
Please provide a description of the function:def first(self): return self.values[tuple(zeros(len(self.values.shape)))]
[ "\n First chunk\n " ]
Please provide a description of the function:def unchunk(self): if self.padding != len(self.shape)*(0,): shape = self.values.shape arr = empty(shape, dtype=object) for inds in product(*[arange(s) for s in shape]): slices = [] for i, p,...
[ "\n Reconstitute the chunked array back into a full ndarray.\n\n Returns\n -------\n ndarray\n " ]
Please provide a description of the function:def chunk(arr, chunk_size="150", padding=None): plan, _ = LocalChunks.getplan(chunk_size, arr.shape[1:], arr.dtype) plan = r_[arr.shape[0], plan] if padding is None: pad = arr.ndim*(0,) elif isinstance(padding, int): ...
[ "\n Created a chunked array from a full array and a chunk size.\n\n Parameters\n ----------\n array : ndarray\n Array that will be broken into chunks\n\n chunk_size : string or tuple, default = '150'\n Size of each image chunk.\n If a str, size of ...
Please provide a description of the function:def compute(self): if self.mode == 'spark': self.values.tordd().count() else: notsupported(self.mode)
[ "\n Force lazy computations to execute for datasets backed by Spark (Spark only).\n " ]
Please provide a description of the function:def coalesce(self, npartitions): if self.mode == 'spark': current = self.values.tordd().getNumPartitions() if npartitions > current: raise Exception('Trying to increase number of partitions (from %g to %g), ' ...
[ "\n Coalesce data (Spark only).\n\n Parameters\n ----------\n npartitions : int\n Number of partitions after coalescing.\n " ]
Please provide a description of the function:def cache(self): if self.mode == 'spark': self.values.cache() return self else: notsupported(self.mode)
[ "\n Enable in-memory caching (Spark only).\n " ]
Please provide a description of the function:def uncache(self): if self.mode == 'spark': self.values.unpersist() return self else: notsupported(self.mode)
[ "\n Disable in-memory caching (Spark only).\n " ]
Please provide a description of the function:def iscached(self): if self.mode == 'spark': return self.tordd().is_cached else: notsupported(self.mode)
[ "\n Get whether object is cached (Spark only).\n " ]
Please provide a description of the function:def npartitions(self): if self.mode == 'spark': return self.tordd().getNumPartitions() else: notsupported(self.mode)
[ "\n Get number of partitions (Spark only).\n " ]
Please provide a description of the function:def repartition(self, npartitions): if self.mode == 'spark': return self._constructor(self.values.repartition(npartitions)).__finalize__(self) else: notsupported(self.mode)
[ "\n Repartition data (Spark only).\n\n Parameters\n ----------\n npartitions : int\n Number of partitions after repartitions.\n " ]
Please provide a description of the function:def astype(self, dtype, casting='unsafe'): return self._constructor( self.values.astype(dtype=dtype, casting=casting)).__finalize__(self)
[ "\n Cast values to the specified type.\n \n Parameters\n ----------\n dtype : str or dtype\n Typecode or data-type to which the array is cast.\n casting : ['no', 'equiv', 'safe', 'same_kind', 'unsafe'], optional\n Controld what kind of data casting may...
Please provide a description of the function:def filter(self, func): if self.mode == 'local': reshaped = self._align(self.baseaxes) filtered = asarray(list(filter(func, reshaped))) if self.labels is not None: mask = asarray(list(map(func, reshaped))...
[ "\n Filter array along an axis.\n\n Applies a function which should evaluate to boolean,\n along a single axis or multiple axes. Array will be\n aligned so that the desired set of axes are in the\n keys, which may require a transpose/reshape.\n\n Parameters\n -------...
Please provide a description of the function:def map(self, func, value_shape=None, dtype=None, with_keys=False): axis = self.baseaxes if self.mode == 'local': axes = sorted(tupleize(axis)) key_shape = [self.shape[axis] for axis in axes] reshaped = self._alig...
[ "\n Apply an array -> array function across an axis.\n\n Array will be aligned so that the desired set of axes\n are in the keys, which may require a transpose/reshape.\n\n Parameters\n ----------\n func : function\n Function of a single array to apply. If with_k...
Please provide a description of the function:def _reduce(self, func, axis=0): if self.mode == 'local': axes = sorted(tupleize(axis)) # if the function is a ufunc, it can automatically handle reducing over multiple axes if isinstance(func, ufunc): ins...
[ "\n Reduce an array along an axis.\n\n Applies an associative/commutative function of two arguments\n cumulatively to all arrays along an axis. Array will be aligned\n so that the desired set of axes are in the keys, which may\n require a transpose/reshape.\n\n Parameters\n...
Please provide a description of the function:def element_wise(self, other, op): if not isscalar(other) and not self.shape == other.shape: raise ValueError("shapes %s and %s must be equal" % (self.shape, other.shape)) if not isscalar(other) and isinstance(other, Data) and not self.m...
[ "\n Apply an elementwise operation to data.\n\n Both self and other data must have the same mode.\n If self is in local mode, other can also be a numpy array.\n Self and other must have the same shape, or other must be a scalar.\n\n Parameters\n ----------\n other : ...
Please provide a description of the function:def clip(self, min=None, max=None): return self._constructor( self.values.clip(min=min, max=max)).__finalize__(self)
[ "\n Clip values above and below.\n\n Parameters\n ----------\n min : scalar or array-like\n Minimum value. If array, will be broadcasted\n\n max : scalar or array-like\n Maximum value. If array, will be broadcasted.\n " ]
Please provide a description of the function:def fromrdd(rdd, nrecords=None, shape=None, index=None, labels=None, dtype=None, ordered=False): from .series import Series from bolt.spark.array import BoltArraySpark if index is None or dtype is None: item = rdd.values().first() if index is N...
[ "\n Load series data from a Spark RDD.\n\n Assumes keys are tuples with increasing and unique indices,\n and values are 1d ndarrays. Will try to infer properties\n that are not explicitly provided.\n\n Parameters\n ----------\n rdd : SparkRDD\n An RDD containing series data.\n\n shape...
Please provide a description of the function:def fromarray(values, index=None, labels=None, npartitions=None, engine=None): from .series import Series import bolt if isinstance(values, bolt.spark.array.BoltArraySpark): return Series(values) values = asarray(values) if values.ndim < 2...
[ "\n Load series data from an array.\n\n Assumes that all but final dimension index the records,\n and the size of the final dimension is the length of each record,\n e.g. a (2, 3, 4) array will be treated as 2 x 3 records of size (4,)\n\n Parameters\n ----------\n values : array-like\n A...
Please provide a description of the function:def fromlist(items, accessor=None, index=None, labels=None, dtype=None, npartitions=None, engine=None): if spark and isinstance(engine, spark): if dtype is None: dtype = accessor(items[0]).dtype if accessor else items[0].dtype nrecords = ...
[ "\n Load series data from a list with an optional accessor function.\n\n Will call accessor function on each item from the list,\n providing a generic interface for data loading.\n\n Parameters\n ----------\n items : list\n A list of items to load.\n\n accessor : function, optional, defa...
Please provide a description of the function:def fromtext(path, ext='txt', dtype='float64', skip=0, shape=None, index=None, labels=None, npartitions=None, engine=None, credentials=None): from thunder.readers import normalize_scheme, get_parallel_reader path = normalize_scheme(path, ext) if spark and i...
[ "\n Loads series data from text files.\n\n Assumes data are formatted as rows, where each record is a row\n of numbers separated by spaces e.g. 'v v v v v'. You can\n optionally specify a fixed number of initial items per row to skip / discard.\n\n Parameters\n ----------\n path : string\n ...
Please provide a description of the function:def frombinary(path, ext='bin', conf='conf.json', dtype=None, shape=None, skip=0, index=None, labels=None, engine=None, credentials=None): shape, dtype = _binaryconfig(path, conf, dtype, shape, credentials) from thunder.readers import normalize_scheme, get_para...
[ "\n Load series data from flat binary files.\n\n Parameters\n ----------\n path : string URI or local filesystem path\n Directory to load from, can be a URI string with scheme\n (e.g. 'file://', 's3n://', or 'gs://'), or a single file,\n or a directory, or a directory with a single ...
Please provide a description of the function:def _binaryconfig(path, conf, dtype=None, shape=None, credentials=None): import json from thunder.readers import get_file_reader, FileNotFoundError reader = get_file_reader(path)(credentials=credentials) try: buf = reader.read(path, filename=con...
[ "\n Collects parameters to use for binary series loading.\n " ]
Please provide a description of the function:def fromexample(name=None, engine=None): import os import tempfile import shutil from boto.s3.connection import S3Connection datasets = ['iris', 'mouse', 'fish'] if name is None: print('Availiable example series datasets') for d...
[ "\n Load example series data.\n\n Data are downloaded from S3, so this method requires an internet connection.\n\n Parameters\n ----------\n name : str\n Name of dataset, options include 'iris' | 'mouse' | 'fish'.\n If not specified will print options.\n\n engine : object, default = ...
Please provide a description of the function:def tobinary(series, path, prefix='series', overwrite=False, credentials=None): from six import BytesIO from thunder.utils import check_path from thunder.writers import get_parallel_writer if not overwrite: check_path(path, credentials=credentia...
[ "\n Writes out data to binary format.\n\n Parameters\n ----------\n series : Series\n The data to write\n\n path : string path or URI to directory to be created\n Output files will be written underneath path.\n Directory will be created as a result of this call.\n\n prefix : s...
Please provide a description of the function:def write_config(path, shape=None, dtype=None, name="conf.json", overwrite=True, credentials=None): import json from thunder.writers import get_file_writer writer = get_file_writer(path) conf = {'shape': shape, 'dtype': str(dtype)} confwriter = wri...
[ "\n Write a conf.json file with required information to load Series binary data.\n " ]
Please provide a description of the function:def first(self): if self.mode == 'local': return self.values[0] if self.mode == 'spark': return self.values.first().toarray()
[ "\n Return the first element.\n " ]
Please provide a description of the function:def toblocks(self, chunk_size='auto', padding=None): from thunder.blocks.blocks import Blocks from thunder.blocks.local import LocalChunks if self.mode == 'spark': if chunk_size is 'auto': chunk_size = str(max([in...
[ "\n Convert to blocks which represent subdivisions of the images data.\n\n Parameters\n ----------\n chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'\n String interpreted as memory size (in kilobytes, e.g. '64').\n The exceptio...
Please provide a description of the function:def toseries(self, chunk_size='auto'): from thunder.series.series import Series if chunk_size is 'auto': chunk_size = str(max([int(1e5/self.shape[0]), 1])) n = len(self.shape) - 1 index = arange(self.shape[0]) i...
[ "\n Converts to series data.\n\n This method is equivalent to images.toblocks(size).toSeries().\n\n Parameters\n ----------\n chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'\n String interpreted as memory size (in kilobytes, e.g. ...
Please provide a description of the function:def tolocal(self): from thunder.images.readers import fromarray if self.mode == 'local': logging.getLogger('thunder').warn('images already in local mode') pass return fromarray(self.toarray())
[ "\n Convert to local mode.\n " ]
Please provide a description of the function:def tospark(self, engine=None): from thunder.images.readers import fromarray if self.mode == 'spark': logging.getLogger('thunder').warn('images already in spark mode') pass if engine is None: raise ValueE...
[ "\n Convert to distributed spark mode.\n " ]
Please provide a description of the function:def foreach(self, func): if self.mode == 'spark': self.values.tordd().map(lambda kv: (kv[0][0], kv[1])).foreach(func) else: [func(kv) for kv in enumerate(self.values)]
[ "\n Execute a function on each image.\n\n Functions can have side effects. There is no return value.\n " ]
Please provide a description of the function:def sample(self, nsamples=100, seed=None): if nsamples < 1: raise ValueError("Number of samples must be larger than 0, got '%g'" % nsamples) if seed is None: seed = random.randint(0, 2 ** 32) if self.mode == 'spark':...
[ "\n Extract a random sample of images.\n\n Parameters\n ----------\n nsamples : int, optional, default = 100\n The number of data points to sample.\n\n seed : int, optional, default = None\n Random seed.\n " ]
Please provide a description of the function:def var(self): return self._constructor(self.values.var(axis=0, keepdims=True))
[ "\n Compute the variance across images.\n " ]
Please provide a description of the function:def std(self): return self._constructor(self.values.std(axis=0, keepdims=True))
[ "\n Compute the standard deviation across images.\n " ]
Please provide a description of the function:def squeeze(self): axis = tuple(range(1, len(self.shape) - 1)) if prod(self.shape[1:]) == 1 else None return self.map(lambda x: x.squeeze(axis=axis))
[ "\n Remove single-dimensional axes from images.\n " ]
Please provide a description of the function:def reshape(self, *shape): if prod(self.shape) != prod(shape): raise ValueError("Reshaping must leave the number of elements unchanged") if self.shape[0] != shape[0]: raise ValueError("Reshaping cannot change the number of im...
[ "\n Reshape images\n\n Parameters\n ----------\n shape: one or more ints\n New shape\n " ]
Please provide a description of the function:def max_projection(self, axis=2): if axis >= size(self.value_shape): raise Exception('Axis for projection (%s) exceeds ' 'image dimensions (%s-%s)' % (axis, 0, size(self.value_shape)-1)) new_value_shape = list...
[ "\n Compute maximum projections of images along a dimension.\n\n Parameters\n ----------\n axis : int, optional, default = 2\n Which axis to compute projection along.\n " ]
Please provide a description of the function:def max_min_projection(self, axis=2): if axis >= size(self.value_shape): raise Exception('Axis for projection (%s) exceeds ' 'image dimensions (%s-%s)' % (axis, 0, size(self.value_shape)-1)) new_value_shape = ...
[ "\n Compute maximum-minimum projection along a dimension.\n\n This computes the sum of the maximum and minimum values.\n\n Parameters\n ----------\n axis : int, optional, default = 2\n Which axis to compute projection along.\n " ]
Please provide a description of the function:def subsample(self, factor): value_shape = self.value_shape ndims = len(value_shape) if not hasattr(factor, '__len__'): factor = [factor] * ndims factor = [int(sf) for sf in factor] if any((sf <= 0 for sf in facto...
[ "\n Downsample images by an integer factor.\n\n Parameters\n ----------\n factor : positive int or tuple of positive ints\n Stride to use in subsampling. If a single int is passed,\n each dimension of the image will be downsampled by this factor.\n If a t...
Please provide a description of the function:def gaussian_filter(self, sigma=2, order=0): from scipy.ndimage.filters import gaussian_filter return self.map(lambda v: gaussian_filter(v, sigma, order), value_shape=self.value_shape)
[ "\n Spatially smooth images with a gaussian filter.\n\n Filtering will be applied to every image in the collection.\n\n Parameters\n ----------\n sigma : scalar or sequence of scalars, default = 2\n Size of the filter size as standard deviation in pixels.\n A...
Please provide a description of the function:def _image_filter(self, filter=None, size=2): from numpy import isscalar from scipy.ndimage.filters import median_filter, uniform_filter FILTERS = { 'median': median_filter, 'uniform': uniform_filter } ...
[ "\n Generic function for maping a filtering operation over images.\n\n Parameters\n ----------\n filter : string\n Which filter to use.\n\n size : int or tuple\n Size parameter for filter.\n " ]
Please provide a description of the function:def localcorr(self, size=2): from thunder.images.readers import fromarray, fromrdd from numpy import corrcoef, concatenate nimages = self.shape[0] # spatially average the original image set over the specified neighborhood b...
[ "\n Correlate every pixel in an image sequence to the average of its local neighborhood.\n\n This algorithm computes, for every pixel, the correlation coefficient\n between the sequence of values for that pixel, and the average of all pixels\n in a local neighborhood. It does this by blu...
Please provide a description of the function:def subtract(self, val): if isinstance(val, ndarray): if val.shape != self.value_shape: raise Exception('Cannot subtract image with dimensions %s ' 'from images with dimension %s' % (str(val.shape),...
[ "\n Subtract a constant value or an image from all images.\n\n Parameters\n ----------\n val : int, float, or ndarray\n Value to subtract.\n " ]