def copydb(self, sourcedb, destslab, destdbname=None, progresscb=None):
    destdb = destslab.initdb(destdbname, sourcedb.dupsort)
    statdict = destslab.stat(db=destdb)
    if (statdict['entries'] > 0):
        raise s_exc.DataAlreadyExists()
    rowcount = 0
    for chunk in s_common.chunks(self.scanByFull(db=sourcedb), COPY_CHUNKSIZE):
        (ccount, acount) = destslab.putmulti(chunk, dupdata=True, append=True, db=destdb)
        if ((ccount != len(chunk)) or (acount != len(chunk))):
            raise s_exc.BadCoreStore(mesg='Unexpected number of values written')
        rowcount += len(chunk)
        if ((progresscb is not None) and (0 == (rowcount % PROGRESS_PERIOD))):
            progresscb(rowcount)
    return rowcount

Copy an entire database in this slab to a new database in potentially another slab.

Args:
        sourcedb (LmdbDatabase): which database in this slab to copy rows from
        destslab (LmdbSlab): which slab to copy rows to
        destdbname (str): the name of the database to copy rows to in destslab
        progresscb (Callable[int]):  if not None, this function will be periodically called with the number of rows
                                    completed

Returns:
        (int): the number of rows copied

Note:
        If any rows already exist in the target database, this method returns an error.  This means that one cannot
        use destdbname=None unless there are no explicit databases in the destination slab.


def infer_distribution_parameters(data, distribution, params=None):
    if (params is None):
        params = dict()
    elif (not isinstance(params, dict)):
        raise TypeError('params must be a dictionary object, see great_expectations documentation')
    if ('mean' not in params.keys()):
        params['mean'] = data.mean()
    if ('std_dev' not in params.keys()):
        params['std_dev'] = data.std()
    if (distribution == 'beta'):
        if ('alpha' not in params.keys()):
            params['alpha'] = ((params['mean'] ** 2) * (((1 - params['mean']) / (params['std_dev'] ** 2)) - (1 / params['mean'])))
        if ('beta' not in params.keys()):
            params['beta'] = (params['alpha'] * ((1 / params['mean']) - 1))
    elif (distribution == 'gamma'):
        if ('alpha' not in params.keys()):
            params['alpha'] = (params['mean'] / params.get('scale', 1))
    elif (distribution == 'uniform'):
        if ('min' not in params.keys()):
            if ('loc' in params.keys()):
                params['min'] = params['loc']
            else:
                params['min'] = min(data)
        if ('max' not in params.keys()):
            if ('scale' in params.keys()):
                params['max'] = params['scale']
            else:
                params['max'] = (max(data) - params['min'])
    elif (distribution == 'chi2'):
        if ('df' not in params.keys()):
            params['df'] = params['mean']
    elif (distribution is not 'norm'):
        raise AttributeError('Unsupported distribution type. Please refer to Great Expectations Documentation')
    params['loc'] = params.get('loc', 0)
    params['scale'] = params.get('scale', 1)
    return params

Convenience method for determining the shape parameters of a given distribution

Args:
        data (list-like): The data to build shape parameters from.
        distribution (string): Scipy distribution, determines which parameters to build.
        params (dict or None): The known parameters. Parameters given here will not be altered. \
                            Keep as None to infer all necessary parameters from the data data.

Returns:
        A dictionary of named parameters::

        {
            "mean": (float),
            "std_dev": (float),
            "loc": (float),
            "scale": (float),
            "alpha": (float),
            "beta": (float),
            "min": (float),
            "max": (float),
            "df": (float)
        }

        See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest


def create(self, ip_dest, next_hop, **kwargs):
    return self._set_route(ip_dest, next_hop, **kwargs)

Create a static route

Args:
        ip_dest (string): The ip address of the destination in the
            form of A.B.C.D/E
        next_hop (string): The next hop interface or ip address
        **kwargs['next_hop_ip'] (string): The next hop address on
            destination interface
        **kwargs['distance'] (string): Administrative distance for this
            route
        **kwargs['tag'] (string): Route tag
        **kwargs['route_name'] (string): Route name

Returns:
        True if the operation succeeds, otherwise False.


def run_shell_command(state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs):
    command = make_command(command, **command_kwargs)
    logger.debug('--> Running command on localhost: {0}'.format(command))
    if print_output:
        print('{0}>>> {1}'.format(host.print_prefix, command))
    process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
    stdout_reader = gevent.spawn(read_buffer, process.stdout, print_output=print_output, print_func=(lambda line: '{0}{1}'.format(host.print_prefix, line)))
    stderr_reader = gevent.spawn(read_buffer, process.stderr, print_output=print_output, print_func=(lambda line: '{0}{1}'.format(host.print_prefix, click.style(line, 'red'))))
    greenlets = gevent.wait((stdout_reader, stderr_reader), timeout=timeout)
    if (len(greenlets) != 2):
        stdout_reader.kill()
        stderr_reader.kill()
        raise timeout_error()
    stdout = stdout_reader.get()
    stderr = stderr_reader.get()
    logger.debug('--> Waiting for exit status...')
    process.wait()
    process.stdout.close()
    logger.debug('--> Command exit status: {0}'.format(process.returncode))
    return ((process.returncode == 0), stdout, stderr)

Execute a command on the local machine.

Args:
        state (``pyinfra.api.State`` obj): state object for this command
        hostname (string): hostname of the target
        command (string): actual command to execute
        sudo (boolean): whether to wrap the command with sudo
        sudo_user (string): user to sudo to
        get_pty (boolean): whether to get a PTY before executing the command
        env (dict): envrionment variables to set
        timeout (int): timeout for this command to complete before erroring

Returns:
        tuple: (exit_code, stdout, stderr)
        stdout and stderr are both lists of strings from each buffer.


def issubset(self, other):
    other = self._cast_to_frameset(other)
    if (other is NotImplemented):
        return NotImplemented
    return (self.items <= other.items)

Check if the contents of `self` is a subset of the contents of
    `other.`

Args:
        other (:class:`FrameSet`):

Returns:
        bool:
        :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`


def peek_native(make):

    def peek(service, container, _stack=None):
        return make(service.peekNative(container))
    return peek

Deserializer factory for types which state can be natively serialized.

Args:
        make (callable): type constructor.

Returns:
        callable: deserializer (`peek` routine)


def enroll_user_in_course(self, username, course_id, mode, cohort=None):
    return self.client.enrollment.post({'user': username, 'course_details': {'course_id': course_id}, 'mode': mode, 'cohort': cohort})

Call the enrollment API to enroll the user in the course specified by course_id.

Args:
        username (str): The username by which the user goes on the OpenEdX platform
        course_id (str): The string value of the course's unique identifier
        mode (str): The enrollment mode which should be used for the enrollment
        cohort (str): Add the user to this named cohort

Returns:
        dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.


def _decode_exp(self, access_token=None):
    c = self.get_credentials()
    jwt = (access_token or c.access_token)
    x = self.decode_jwt_payload(jwt)
    if ('exp' in x):
        try:
            exp = int(x['exp'])
        except ValueError:
            raise PanCloudError('Expiration time (exp) must be an integer')
        else:
            self.jwt_exp = exp
            return exp
    else:
        raise PanCloudError('No exp field found in payload')

Extract exp field from access token.

Args:
        access_token (str): Access token to decode. Defaults to ``None``.

Returns:
        int: JWT expiration in epoch seconds.


def with_subject(self, subject):
    return self.__class__(self._signer, service_account_email=self._service_account_email, scopes=self._scopes, token_uri=self._token_uri, subject=subject, project_id=self._project_id, additional_claims=self._additional_claims.copy())

Create a copy of these credentials with the specified subject.

Args:
        subject (str): The subject claim.

Returns:
        google.auth.service_account.Credentials: A new credentials
            instance.


def predict_undirected_graph(self, data):
    graph = Graph()
    for (idx_i, i) in enumerate(data.columns):
        for (idx_j, j) in enumerate(data.columns[(idx_i + 1):]):
            score = self.predict(data[i].values, data[j].values)
            if (abs(score) > 0.001):
                graph.add_edge(i, j, weight=score)
    return graph

Build a skeleton using a pairwise independence criterion.

Args:
        data (pandas.DataFrame): Raw data table

Returns:
        networkx.Graph: Undirected graph representing the skeleton.


def compare_modules(file_, imports):
    modules = parse_requirements(file_)
    imports = [imports[i]['name'] for i in range(len(imports))]
    modules = [modules[i]['name'] for i in range(len(modules))]
    modules_not_imported = (set(modules) - set(imports))
    return modules_not_imported

Compare modules in a file to imported modules in a project.

Args:
        file_ (str): File to parse for modules to be compared.
        imports (tuple): Modules being imported in the project.

Returns:
        tuple: The modules not imported in the project, but do exist in the
            specified file.


def create_ingress_rule(self, app, rule):
    if isinstance(rule, dict):
        start_port = rule.get('start_port')
        end_port = rule.get('end_port')
        protocol = rule.get('protocol', 'tcp')
        requested_cross_account = rule.get('env', self.env)
        if (self.env == requested_cross_account):
            cross_account_env = None
            cross_account_vpc_id = None
        else:
            cross_account_env = requested_cross_account
            cross_account_vpc_id = get_vpc_id(cross_account_env, self.region)
    else:
        start_port = rule
        end_port = rule
        protocol = 'tcp'
        cross_account_env = None
        cross_account_vpc_id = None
    created_rule = {'app': app, 'start_port': start_port, 'end_port': end_port, 'protocol': protocol, 'cross_account_env': cross_account_env, 'cross_account_vpc_id': cross_account_vpc_id}
    self.log.debug('Normalized ingress rule: %s', created_rule)
    return created_rule

Create a normalized ingress rule.

Args:
        app (str): Application name
        rule (dict or int): Allowed Security Group ports and protocols.

Returns:
        dict: Contains app, start_port, end_port, protocol, cross_account_env and cross_account_vpc_id


def split_columns(text, n_columns):
    if ((n_columns <= 0) or (n_columns > len(text))):
        raise ValueError('n_columns must be within the bounds of 1 and text length')
    return [text[i::n_columns] for i in range(n_columns)]

Split ``text`` into ``n_columns`` many columns.

Example:
        >>> split_columns("example", 2)
        ['eape', 'xml']

Args:
        text (str): The text to split
        n_columns (int): The number of columns to create

Returns:
        List of columns

Raises:
        ValueError: If n_cols is <= 0 or >= len(text)


def get_contacts(self, issue):
    if (not issue.resource):
        return []
    account_contacts = issue.resource.account.contacts
    try:
        resource_owners = issue.resource.get_owner_emails()
        if (type(resource_owners) is list):
            for resource_owner in resource_owners:
                account_contacts.append({'type': 'email', 'value': resource_owner})
    except AttributeError:
        pass
    return account_contacts

Returns a list of contacts for an issue

Args:
        issue (:obj:`RequiredTagsIssue`): Issue record

Returns:
        `list` of `dict`


def update(self, identity, params=None, headers=None):
    path = self._sub_url_params('/payments/:identity', {'identity': identity})
    if (params is not None):
        params = {self._envelope_key(): params}
    response = self._perform_request('PUT', path, params, headers, retry_failures=True)
    return self._resource_for(response)

Update a payment.

    Updates a payment object. This accepts only the metadata parameter.

Args:
        identity (string): Unique identifier, beginning with "PM".
        params (dict, optional): Request body.

Returns:
        ListResponse of Payment instances


def inject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=1):
    noinject(module_name, module_prefix, DEBUG, module, N=N)
    module = _get_module(module_name, module)
    rrr = make_module_reload_func(None, module_prefix, module)
    profile_ = make_module_profile_func(None, module_prefix, module)
    print_funcs = inject_print_functions(None, module_prefix, DEBUG, module)
    (print, print_, printDBG) = print_funcs
    return (print, print_, printDBG, rrr, profile_)

Injects your module with utool magic

    Utool magic is not actually magic. It just turns your ``print`` statments into
    logging statments, allows for your module to be used with the utool.Indent
    context manager and the and utool.indent_func decorator. ``printDBG`` will soon
    be deprecated as will ``print_``. The function rrr is a developer convinience for
    reloading the module dynamically durring runtime. The profile decorator is
    a no-op if not using kernprof.py, otherwise it is kernprof.py's profile
    decorator.

Args:
        module_name (str): the __name__ varaible in your module
        module_prefix (str): a user defined module prefix
        DEBUG (bool):
        module (None): the actual module (optional)

Returns:
        tuple : (print, print_, printDBG, rrr, profile_)

Example:
        >>> # DISABLE_DOCTEST
        >>> from utool.util_inject import *  # NOQA
        >>> from __future__ import absolute_import, division, print_function, unicode_literals
        >>> from util.util_inject import inject
        >>> print, rrr, profile = inject2(__name__, '[mod]')


def sign(self, private_keys):
    if ((private_keys is None) or (not isinstance(private_keys, list))):
        raise TypeError('`private_keys` must be a list instance')

    def gen_public_key(private_key):
        public_key = private_key.get_verifying_key().encode()
        return public_key.decode()
    key_pairs = {gen_public_key(PrivateKey(private_key)): PrivateKey(private_key) for private_key in private_keys}
    tx_dict = self.to_dict()
    tx_dict = Transaction._remove_signatures(tx_dict)
    tx_serialized = Transaction._to_str(tx_dict)
    for (i, input_) in enumerate(self.inputs):
        self.inputs[i] = self._sign_input(input_, tx_serialized, key_pairs)
    self._hash()
    return self

Fulfills a previous Transaction's Output by signing Inputs.

Note:
        This method works only for the following Cryptoconditions
        currently:
            - Ed25519Fulfillment
            - ThresholdSha256
        Furthermore, note that all keys required to fully sign the
        Transaction have to be passed to this method. A subset of all
        will cause this method to fail.

Args:
        private_keys (:obj:`list` of :obj:`str`): A complete list of
            all private keys needed to sign all Fulfillments of this
            Transaction.

Returns:
        :class:`~bigchaindb.common.transaction.Transaction`


def _starts_with(field, filter_value):
    valid = False
    if field.startswith(filter_value):
        valid = True
    return valid

Validate field starts with provided value.

Args:
        filter_value (string): A string or list of values.

Returns:
        (boolean): Results of validation


def frame(self, frame):
    try:
        zframe = str(int(frame)).zfill(self._zfill)
    except ValueError:
        zframe = frame
    if (self._zfill == 0):
        zframe = ''
    return ''.join((self._dir, self._base, zframe, self._ext))

Return a path go the given frame in the sequence.  Integer or string
    digits are treated as a frame number and padding is applied, all other
    values are passed though.

Example:
        >>> seq.frame(1)
        /foo/bar.0001.exr
        >>> seq.frame("#")
        /foo/bar.#.exr

Args:
        frame (int or str): the desired frame number or a char to pass
            through (ie. #)

Returns:
        str:


def get_structures(self, primitive=True):
    structures = []
    for d in self._cif.data.values():
        try:
            s = self._get_structure(d, primitive)
            if s:
                structures.append(s)
        except (KeyError, ValueError) as exc:
            self.errors.append(str(exc))
            warnings.warn(str(exc))
    if self.errors:
        warnings.warn('Issues encountered while parsing CIF:')
        for error in self.errors:
            warnings.warn(error)
    if (len(structures) == 0):
        raise ValueError('Invalid cif file with no structures!')
    return structures

Return list of structures in CIF file. primitive boolean sets whether a
    conventional cell structure or primitive cell structure is returned.

Args:
        primitive (bool): Set to False to return conventional unit cells.
            Defaults to True. With magnetic CIF files, will return primitive
            magnetic cell which may be larger than nuclear primitive cell.

Returns:
        List of Structures.


def state_invariant_scope(self, state: Sequence[tf.Tensor]):
    scope = {}
    scope.update(self.non_fluents_scope())
    scope.update(self.state_scope(state))
    return scope

Returns the state invariant fluent scope for the current `state`.

Args:
        state (Sequence[tf.Tensor]): The current state fluents.

Returns:
        A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`.


def createThread(parent, worker, deleteWorkerLater=False):
    thread = QtCore.QThread(parent)
    thread.started.connect(worker.doWork)
    worker.finished.connect(thread.quit)
    if deleteWorkerLater:
        thread.finished.connect(worker.deleteLater)
    worker.moveToThread(thread)
    worker.setParent(parent)
    return thread

Create a new thread for given worker.

Args:
        parent (QObject): parent of thread and worker.
        worker (ProgressWorker): worker to use in thread.
        deleteWorkerLater (bool, optional): delete the worker if thread finishes.

Returns:
        QThread


def get_available_servers(self, **kwargs):
    uri = self._helper.build_uri_with_query_string(kwargs, '/available-servers')
    return self._helper.do_get(uri)

Retrieves the list of available servers.

Args:
        enclosureGroupUri (str): The URI of the enclosure group associated with the resource.
        serverHardwareTypeUri (str): The URI of the server hardware type associated with the resource.
        profileUri (str): The URI of the server profile resource.
        scopeUris (str): An expression to restrict the resources returned according to
        the scopes to which they are assigned.
        filter (list or str): A general filter/query string to narrow the list of items returned.
        The default is no filter, all resources are returned.

Returns:
        list: Available servers.


def validate_with_tags(self, tags, confidence):
    result = {'intent_type': self.name}
    intent_confidence = 0.0
    local_tags = tags[:]
    used_tags = []
    for (require_type, attribute_name) in self.requires:
        (required_tag, canonical_form, confidence) = find_first_tag(local_tags, require_type)
        if (not required_tag):
            result['confidence'] = 0.0
            return (result, [])
        result[attribute_name] = canonical_form
        if (required_tag in local_tags):
            local_tags.remove(required_tag)
        used_tags.append(required_tag)
        intent_confidence += confidence
    if (len(self.at_least_one) > 0):
        best_resolution = resolve_one_of(tags, self.at_least_one)
        if (not best_resolution):
            result['confidence'] = 0.0
            return (result, [])
        else:
            for key in best_resolution:
                result[key] = best_resolution[key][0].get('key')
                intent_confidence += 1.0
            used_tags.append(best_resolution)
            if (best_resolution in local_tags):
                local_tags.remove(best_resolution)
    for (optional_type, attribute_name) in self.optional:
        (optional_tag, canonical_form, conf) = find_first_tag(local_tags, optional_type)
        if ((not optional_tag) or (attribute_name in result)):
            continue
        result[attribute_name] = canonical_form
        if (optional_tag in local_tags):
            local_tags.remove(optional_tag)
        used_tags.append(optional_tag)
        intent_confidence += 1.0
    total_confidence = ((intent_confidence / len(tags)) * confidence)
    (target_client, canonical_form, confidence) = find_first_tag(local_tags, CLIENT_ENTITY_NAME)
    result['target'] = (target_client.get('key') if target_client else None)
    result['confidence'] = total_confidence
    return (result, used_tags)

Validate weather tags has required entites for this intent to fire

Args:
        tags(list): Tags and Entities used for validation
        confidence(float): ?

Returns:
        intent, tags: Returns intent and tags used by the intent on
            falure to meat required entities then returns intent with confidence
            of 0.0 and an empty list for tags.


def _scale_size(size, scale):
    (w, h) = size
    return (int(((w * float(scale)) + 0.5)), int(((h * float(scale)) + 0.5)))

Rescale a size by a ratio.

Args:
        size (tuple): w, h.
        scale (float): Scaling factor.

Returns:
        tuple[int]: scaled size.


def load_dict(self, db_key: str, hierarchical: bool=False) -> dict:
    if (not hierarchical):
        db_values = self._db.hgetall(db_key)
        for (_key, _value) in db_values.items():
            if isinstance(_value, str):
                db_values[_key] = ast.literal_eval(_value)
        my_dict = db_values
    else:
        my_dict = self._load_dict_hierarchical(db_key)
    return my_dict

Load the dictionary at the specified key.

    Hierarchically stored dictionaries use a ':' separator to expand
    the dictionary into a set of Redis hashes.

Args:
        db_key (str): Key at which the dictionary is stored in the db.
        hierarchical (bool): If True, expect the dictionary to have been
            stored hierarchically. If False, expect the dictionary to have
            been stored flat.

Returns:
        dict, the dictionary stored at key


def find_dependency_wheels(tile):
    return [os.path.join(x.folder, 'python', x.support_wheel) for x in _iter_dependencies(tile) if x.has_wheel]

Return a list of all python wheel objects created by dependencies of this tile

Args:
        tile (IOTile): Tile that we should scan for dependencies

Returns:
        list: A list of paths to dependency wheels


def ctype_to_dtype(cl_type, mot_float_type='float'):
    if is_vector_ctype(cl_type):
        (raw_type, vector_length) = split_vector_ctype(cl_type)
        if (raw_type == 'mot_float_type'):
            if is_vector_ctype(mot_float_type):
                (raw_type, _) = split_vector_ctype(mot_float_type)
            else:
                raw_type = mot_float_type
        vector_type = (raw_type + str(vector_length))
        return getattr(cl_array.vec, vector_type)
    else:
        if (cl_type == 'mot_float_type'):
            cl_type = mot_float_type
        data_types = [('char', np.int8), ('uchar', np.uint8), ('short', np.int16), ('ushort', np.uint16), ('int', np.int32), ('uint', np.uint32), ('long', np.int64), ('ulong', np.uint64), ('float', np.float32), ('double', np.float64)]
        for (ctype, dtype) in data_types:
            if (ctype == cl_type):
                return dtype

Get the numpy dtype of the given cl_type string.

Args:
        cl_type (str): the CL data type to match, for example 'float' or 'float4'.
        mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively.

Returns:
        dtype: the numpy datatype


def prepare_capstone(syntax=AsmSyntax.att, target=None):
    if (not HAVE_CAPSTONE):
        raise NotImplementedError('pwnypack requires capstone to disassemble to AT&T and Intel syntax')
    if (target is None):
        target = pwnypack.target.target
    if (target.arch == pwnypack.target.Target.Arch.x86):
        if (target.bits is pwnypack.target.Target.Bits.bits_32):
            md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
        else:
            md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
    elif (target.arch == pwnypack.target.Target.Arch.arm):
        mode = 0
        if (target.bits is pwnypack.target.Target.Bits.bits_32):
            arch = capstone.CS_ARCH_ARM
            if (target.mode and pwnypack.target.Target.Mode.arm_thumb):
                mode = capstone.CS_MODE_THUMB
            else:
                mode = capstone.CS_MODE_ARM
                if (target.mode and pwnypack.target.Target.Mode.arm_m_class):
                    mode |= capstone.CS_MODE_MCLASS
            if (target.mode and pwnypack.target.Target.Mode.arm_v8):
                mode |= capstone.CS_MODE_V8
        else:
            arch = capstone.CS_ARCH_ARM64
        if (target.endian is pwnypack.target.Target.Endian.little):
            mode |= capstone.CS_MODE_LITTLE_ENDIAN
        else:
            mode |= capstone.CS_MODE_BIG_ENDIAN
        md = capstone.Cs(arch, mode)
    else:
        raise NotImplementedError('Only x86 is currently supported.')
    md.skipdata = True
    if (syntax is AsmSyntax.att):
        md.syntax = capstone.CS_OPT_SYNTAX_ATT
    elif (syntax is AsmSyntax.intel):
        md.skipdata_setup(('db', None, None))
    else:
        raise NotImplementedError('capstone engine only implements AT&T and Intel syntax.')
    return md

Prepare a capstone disassembler instance for a given target and syntax.

Args:
        syntax(AsmSyntax): The assembler syntax (Intel or AT&T).
        target(~pwnypack.target.Target): The target to create a disassembler
            instance for. The global target is used if this argument is
            ``None``.

Returns:
        An instance of the capstone disassembler.

Raises:
        NotImplementedError: If the specified target isn't supported.


def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window:
    if (size is None):
        (width, height) = (1280, 720)
    else:
        (width, height) = size
    if ((samples < 0) or ((samples & (samples - 1)) != 0)):
        raise Exception(('Invalid number of samples: %d' % samples))
    window = Window.__new__(Window)
    window.wnd = glwnd.create_window(width, height, samples, fullscreen, title, threaded)
    return window

Create the main window.

Args:
        size (tuple): The width and height of the window.
        samples (int): The number of samples.

    Keyword Args:
        fullscreen (bool): Fullscreen?
        title (bool): The title of the window.
        threaded (bool): Threaded?

Returns:
        Window: The main window.


def numbafy(fn, args, compiler='jit', **nbkws):
    kwargs = {}
    if (not isinstance(args, (tuple, list))):
        args = (args,)
    if isinstance(compiler, six.string_types):
        compiler_ = getattr(nb, compiler, None)
        if (compiler is None):
            raise AttributeError('No numba function with name {}.'.format(compiler))
        compiler = compiler_
    if (compiler in (nb.jit, nb.njit, nb.autojit)):
        kwargs.update(jitkwargs)
        sig = nbkws.pop('signature', None)
    else:
        kwargs.update(veckwargs)
        sig = nbkws.pop('signatures', None)
        if (sig is None):
            warn("Vectorization without 'signatures' can lead to wrong results!")
    kwargs.update(nbkws)
    if isinstance(fn, sy.Expr):
        fn = sy.expand_func(fn)
    func = sy.lambdify(args, fn, modules='numpy')
    if (sig is None):
        try:
            func = compiler(**kwargs)(func)
        except RuntimeError:
            kwargs['cache'] = False
            func = compiler(**kwargs)(func)
    else:
        try:
            func = compiler(sig, **kwargs)(func)
        except RuntimeError:
            kwargs['cache'] = False
            func = compiler(sig, **kwargs)(func)
    return func

Compile a string, sympy expression or symengine expression using numba.

    Not all functions are supported by Python's numerical package (numpy). For
    difficult cases, valid Python code (as string) may be more suitable than
    symbolic expressions coming from sympy, symengine, etc. When compiling
    vectorized functions, include valid signatures (see `numba`_ documentation).

Args:
        fn: Symbolic expression as sympy/symengine expression or string
        args (iterable): Symbolic arguments
        compiler: String name or callable numba compiler
        nbkws: Compiler keyword arguments (if none provided, smart defaults are used)

Returns:
        func: Compiled function

    Warning:
        For vectorized functions, valid signatures are (almost always) required.


def subproc_call(cmd, timeout=None):
    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout)
        return (output, 0)
    except subprocess.TimeoutExpired as e:
        logger.warn("Command '{}' timeout!".format(cmd))
        logger.warn(e.output.decode('utf-8'))
        return (e.output, (- 1))
    except subprocess.CalledProcessError as e:
        logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode))
        logger.warn(e.output.decode('utf-8'))
        return (e.output, e.returncode)
    except Exception:
        logger.warn("Command '{}' failed to run.".format(cmd))
        return ('', (- 2))

Execute a command with timeout, and return STDOUT and STDERR

Args:
        cmd(str): the command to execute.
        timeout(float): timeout in seconds.

Returns:
        output(bytes), retcode(int). If timeout, retcode is -1.


def get_hosted_zone_by_name(client, zone_name):
    p = client.get_paginator('list_hosted_zones')
    for i in p.paginate():
        for zone in i['HostedZones']:
            if (zone['Name'] == zone_name):
                return parse_zone_id(zone['Id'])
    return None

Get the zone id of an existing zone by name.

Args:
        client (:class:`botocore.client.Route53`): The connection used to
            interact with Route53's API.
        zone_name (string): The name of the DNS hosted zone to create.

Returns:
        string: The Id of the Hosted Zone.


def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):
    if (bai_field_variation not in (FieldVariations.search, FieldVariations.raw)):
        raise ValueError('Non supported field variation "{}".'.format(bai_field_variation))
    normalized_author_name = normalize_name(node_value).strip('.')
    if (ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and ElasticSearchVisitor.BAI_REGEX.match(node_value)):
        return [((ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.') + bai_field_variation)]
    elif ((not whitespace.search(normalized_author_name)) and query_bai_field_if_dots_in_name and ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and ('.' in normalized_author_name)):
        return ([((ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.') + bai_field_variation)] + force_list(ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author']))
    else:
        return None

Generates new fieldnames in case of BAI query.

Args:
        node_value (six.text_type): The node's value (i.e. author name).
        bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').
        query_bai_field_if_dots_in_name (bool): Whether to query BAI field (in addition to author's name field)
            if dots exist in the name and name contains no whitespace.

Returns:
        list: Fieldnames to query on, in case of BAI query or None, otherwise.

Raises:
        ValueError, if ``field_variation`` is not one of ('search', 'raw').


def set_shutter_level(self, level=0.0):
    data = {'channelIndex': 1, 'deviceId': self.id, 'shutterLevel': level}
    return self._restCall('device/control/setShutterLevel', body=json.dumps(data))

sets the shutter level

Args:
        level(float): the new level of the shutter. 0.0 = open, 1.0 = closed

Returns:
        the result of the _restCall


def _parse_domain_id(self, config):
    match = re.search('domain-id (.+)$', config)
    value = (match.group(1) if match else None)
    return dict(domain_id=value)

Scans the config block and parses the domain-id value

Args:
        config (str): The config block to scan

Returns:
        dict: A dict object that is intended to be merged into the
            resource dict


def from_file(cls, filename, *, strict=True):
    config = cls()
    config.load_from_file(filename, strict=strict)
    return config

Create a new Config object from a configuration file.

Args:
        filename (str): The location and name of the configuration file.
        strict (bool): If true raises a ConfigLoadError when the configuration
            cannot be found.

Returns:
        An instance of the Config class.

Raises:
        ConfigLoadError: If the configuration cannot be found.


def autorotate(image, orientation=None):
    orientation_value = (orientation if orientation else image._getexif().get(EXIF_KEYS.get('Orientation')))
    if (orientation_value is None):
        raise ImDirectException('No orientation available in Exif tag or given explicitly.')
    if (orientation_value in (1, 2)):
        i = image
    elif (orientation_value in (3, 4)):
        i = image.transpose(Image.ROTATE_180)
    elif (orientation_value in (5, 6)):
        i = image.transpose(Image.ROTATE_270)
    elif (orientation_value in (7, 8)):
        i = image.transpose(Image.ROTATE_90)
    else:
        i = image
    if (orientation_value in (2, 4, 5, 7)):
        i = i.transpose(Image.FLIP_LEFT_RIGHT)
    return i

Rotate and return an image according to its Exif information.

    ROTATION_NEEDED = {
        1: 0,
        2: 0 (Mirrored),
        3: 180,
        4: 180 (Mirrored),
        5: -90 (Mirrored),
        6: -90,
        7: 90 (Mirrored),
        8: 90,
    }

Args:
        image (PIL.Image.Image): PIL image to rotate
        orientation (): Optional orientation value in [1, 8]

Returns:
        A :py:class:`~PIL.Image.Image` image.


def column(self, index_or_label):
    if (isinstance(index_or_label, str) and (index_or_label not in self.labels)):
        raise ValueError('The column "{}" is not in the table. The table contains these columns: {}'.format(index_or_label, ', '.join(self.labels)))
    if (isinstance(index_or_label, int) and (not (0 <= index_or_label < len(self.labels)))):
        raise ValueError('The index {} is not in the table. Only indices between 0 and {} are valid'.format(index_or_label, (len(self.labels) - 1)))
    return self._columns[self._as_label(index_or_label)]

Return the values of a column as an array.

    table.column(label) is equivalent to table[label].

    >>> tiles = Table().with_columns(
    ...     'letter', make_array('c', 'd'),
    ...     'count',  make_array(2, 4),
    ... )

    >>> list(tiles.column('letter'))
    ['c', 'd']
    >>> tiles.column(1)
    array([2, 4])

Args:
        label (int or str): The index or label of a column

Returns:
        An instance of ``numpy.array``.

Raises:
        ``ValueError``: When the ``index_or_label`` is not in the table.


def events(config):
    celery_app = create_app(config)
    for event in event_stream(celery_app, filter_by_prefix='task'):
        try:
            (yield create_event_model(event))
        except JobEventTypeUnsupported:
            pass

Return a generator that yields workflow events.

    For every workflow event that is sent from celery this generator yields an event
    object.

Args:
        config (Config): Reference to the configuration object from which the
            settings are retrieved.

Returns:
        generator: A generator that returns workflow events.


def bind_parameters(self, value_dict):
    new_circuit = self.copy()
    if (value_dict.keys() > self.parameters):
        raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format([str(p) for p in (value_dict.keys() - self.parameters)]))
    for (parameter, value) in value_dict.items():
        new_circuit._bind_parameter(parameter, value)
    for parameter in value_dict:
        del new_circuit._parameter_table[parameter]
    return new_circuit

Assign parameters to values yielding a new circuit.

Args:
        value_dict (dict): {parameter: value, ...}

Raises:
        QiskitError: If value_dict contains parameters not present in the circuit

Returns:
        QuantumCircuit: copy of self with assignment substitution.


def load_hdf5(path):
    with h5py.File(path, 'r') as f:
        is_sparse = f['issparse'][...]
        if is_sparse:
            shape = tuple(f['shape'][...])
            data = f['data'][...]
            indices = f['indices'][...]
            indptr = f['indptr'][...]
            X = sparse.csr_matrix((data, indices, indptr), shape=shape)
        else:
            X = f['data'][...]
        y = f['target'][...]
    return (X, y)

Load data from a HDF5 file.

Args:
        path (str): A path to the HDF5 format file containing data.
        dense (boolean): An optional variable indicating if the return matrix
                        should be dense.  By default, it is false.

Returns:
        Data matrix X and target vector y


def get_mnemonic(self, mnemonic, alias=None):
    alias = (alias or {})
    aliases = alias.get(mnemonic, [mnemonic])
    for a in aliases:
        if (a in self.data):
            return a
    return None

Instead of picking curves by name directly from the data dict, you
    can pick them up with this method, which takes account of the alias
    dict you pass it. If you do not pass an alias dict, then you get the
    curve you asked for, if it exists, or None. NB Wells do not have alias
    dicts, but Projects do.

Args:
        mnemonic (str): the name of the curve you want.
        alias (dict): an alias dictionary, mapping mnemonics to lists of
            mnemonics.

Returns:
        Curve.


def _getsize_from_header(self, header):
    for key in self._SIZE_KEYS:
        try:
            return int(header.pop(key))
        except KeyError:
            continue
    else:
        raise UnsupportedOperation('getsize')

Return the size from header

Args:
        header (dict): Object header.

Returns:
        int: Size in bytes.


def dumpfile(item, path):
    with io.open(path, 'wb') as fd:
        fd.write(en(item))

Dump an object to a file by path.

Args:
        item (object): The object to serialize.
        path (str): The file path to save.

Returns:
        None


def get(self, name):
    return self.prepare_model(self.client.api.inspect_plugin(name))

Gets a plugin.

Args:
        name (str): The name of the plugin.

Returns:
        (:py:class:`Plugin`): The plugin.

Raises:
        :py:class:`docker.errors.NotFound` If the plugin does not
        exist.
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def _FormatMessageShort(self, event):
    (_, message_short) = self._output_mediator.GetFormattedMessages(event)
    if (message_short is None):
        data_type = getattr(event, 'data_type', 'UNKNOWN')
        raise errors.NoFormatterFound('Unable to find event formatter for: {0:s}.'.format(data_type))
    return message_short

Formats the short message.

Args:
        event (EventObject): event.

Returns:
        str: short message field.

Raises:
        NoFormatterFound: if no event formatter can be found to match the data
        type in the event.


def get_firmware_version(self, cached=True):
    if (cached and (self.firmware_version != 'unknown')):
        return self.firmware_version
    firmware_version = self.get_characteristic_handle_from_uuid(UUID_FIRMWARE_REVISION)
    if (firmware_version is None):
        logger.warn('Failed to find handle for firmware version')
        return None
    self.firmware_version = self.dongle._read_attribute(self.conn_handle, firmware_version)
    return self.firmware_version

Returns the SK8 device firmware version.

Args:
        cached (bool): if True, returns the locally cached copy of the firmware version.
            If this is set to False, or the version is not cached, it will read from
            the device instead.

Returns:
        str. The current firmware version string. May be `None` if an error occurs.


def wc(filename, contents, parsed=None, is_jekyll=False):
    if is_jekyll:
        fmt = 'jekyll'
    else:
        fmt = 'md/txt'
    body = (parsed.strip() if parsed else contents.strip())
    words = re.sub('\\s+', ' ', body, re.MULTILINE)
    for punctuation in INTERSTITIAL_PUNCTUATION:
        words = re.sub(punctuation, ' ', words)
    punct = re.compile('[^\\w\\s]', re.U)
    words = punct.sub('', words)
    real_characters = re.sub('\\s', '', words)
    paragraphs = [(1 if (len(x) == 0) else 0) for x in contents.strip().splitlines()]
    for (index, paragraph) in enumerate(paragraphs):
        if ((paragraph == 1) and (paragraphs[(index + 1)] == 1)):
            paragraphs[index] = 0
    return {'counts': {'file': filename, 'type': fmt, 'paragraphs': (sum(paragraphs) + 1), 'words': len(re.split('\\s+', words)), 'characters_real': len(real_characters), 'characters_total': len(words)}}

Count the words, characters, and paragraphs in a string.

Args:
        contents: the original string to count
        filename (optional): the filename as provided to the CLI
        parsed (optional): a parsed string, expected to be plaintext only
        is_jekyll: whether the original contents were from a Jekyll file

Returns:
        An object containing the various counts


def has_no_unchecked_field(self, locator, **kwargs):
    kwargs['checked'] = False
    return self.has_no_selector('field', locator, **kwargs)

Checks if the page or current node has no radio button or checkbox with the given label,
    value, or id, that is currently unchecked.

Args:
        locator (str): The label, name, or id of an unchecked field.
        **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Returns:
        bool: Whether it doesn't exist.


def GetAttributeContainerByIndex(self, index):
    if (index < 0):
        raise IndexError('Unsupported negative index value: {0:d}.'.format(index))
    if (index < len(self._list)):
        return self._list[index]
    return None

Retrieves a specific serialized attribute container from the list.

Args:
        index (int): attribute container index.

Returns:
        bytes: serialized attribute container data or None if not available.

Raises:
        IndexError: if the index is less than zero.


def delete_resource_group(access_token, subscription_id, rgname):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '?api-version=', RESOURCE_API])
    return do_delete(endpoint, access_token)

Delete the named resource group.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        rgname (str): Azure resource group name.

Returns:
        HTTP response.


def check_missing(self, args):
    return [opt.name for opt in self if ((opt.name not in args) and (opt.default is None))]

Returns the names of all options that are required but were not specified.

    All options that don't have a default value are required in order to run the
    workflow.

Args:
        args (dict): A dictionary of the provided arguments that is checked for
                    missing options.

Returns:
        list: A list with the names of the options that are missing from the
            provided arguments.


def array_to_npy(array_like):
    buffer = BytesIO()
    np.save(buffer, array_like)
    return buffer.getvalue()

Convert an array like object to the NPY format.

    To understand better what an array like object is see:
    https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays

Args:
        array_like (np.array or Iterable or int or float): array like object to be converted to NPY.

Returns:
        (obj): NPY array.


def prepare(self, variables):
    initializedsteps = []
    if (variables is None):
        variables = dict()
    for (step, params, _resources, _files) in self.steps:
        new_params = _complete_parameters(params, variables)
        initializedsteps.append(step(new_params))
    return initializedsteps

Initialize all steps in this recipe using their parameters.

Args:
        variables (dict): A dictionary of global variable definitions
            that may be used to replace or augment the parameters given
            to each step.

Returns:
        list of RecipeActionObject like instances: The list of instantiated
            steps that can be used to execute this recipe.


def user_has_access(self, user):
    if (ROLE_ADMIN in user.roles):
        return True
    if self.enabled:
        if (not self.required_roles):
            return True
        for role in self.required_roles:
            if (role in user.roles):
                return True
    return False

Check if a user has access to view information for the account

Args:
        user (:obj:`User`): User object to check

Returns:
        True if user has access to the account, else false


def FromDictionary(cls, msg_dict):
    level = msg_dict.get('level')
    msg = msg_dict.get('message')
    now = msg_dict.get('now_time')
    created = msg_dict.get('created_time')
    count = msg_dict.get('count', 1)
    msg_id = msg_dict.get('id', 0)
    new_msg = ServiceMessage(level, msg, msg_id, created, now)
    if (count > 1):
        new_msg.count = count
    return new_msg

Create from a dictionary with kv pairs.

Args:
        msg_dict (dict): A dictionary with information as created by to_dict()

Returns:
        ServiceMessage: the converted message


def gmeta_pop(gmeta, info=False):
    if (type(gmeta) is GlobusHTTPResponse):
        gmeta = json.loads(gmeta.text)
    elif (type(gmeta) is str):
        gmeta = json.loads(gmeta)
    elif (type(gmeta) is not dict):
        raise TypeError('gmeta must be dict, GlobusHTTPResponse, or JSON string')
    results = []
    for res in gmeta['gmeta']:
        for con in res['content']:
            results.append(con)
    if info:
        fyi = {'total_query_matches': gmeta.get('total')}
        return (results, fyi)
    else:
        return results

Remove GMeta wrapping from a Globus Search result.
    This function can be called on the raw GlobusHTTPResponse that Search returns,
    or a string or dictionary representation of it.

Args:
        gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to unwrap.
        info (bool): If ``False``, will return a list of the results
                and discard the metadata. If ``True``, will return a tuple containing
                the results list, and other information about the query.
                **Default**: ``False``.

Returns:
        list (if ``info=False``): The unwrapped results.
        tuple (if ``info=True``): The unwrapped results, and a dictionary of query information.


def get_detail(self, course_id):
    resp = self._requester.get(urljoin(self._base_url, '/api/courses/v1/courses/{course_key}/'.format(course_key=course_id)))
    resp.raise_for_status()
    return CourseDetail(resp.json())

Fetches course details.

Args:
        course_id (str): An edx course id.

Returns:
        CourseDetail


def parse_matches(patient_id, match_objs):
    LOG.info('Parsing MatchMaker matches for patient {}'.format(patient_id))
    parsed_matches = []
    for match_obj in match_objs:
        milliseconds_date = match_obj['created']['$date']
        mdate = datetime.datetime.fromtimestamp((milliseconds_date / 1000.0))
        match_type = 'external'
        matching_patients = []
        parsed_match = {'match_oid': match_obj['_id']['$oid'], 'match_date': mdate}
        if (match_obj['data']['patient']['id'] == patient_id):
            match_results = match_obj['results']
            for node_result in match_results:
                if (match_obj['match_type'] == 'internal'):
                    match_type = 'internal'
                for patient in node_result['patients']:
                    match_patient = {'patient_id': patient['patient']['id'], 'score': patient['score'], 'patient': patient['patient'], 'node': node_result['node']}
                    matching_patients.append(match_patient)
        else:
            m_patient = match_obj['data']['patient']
            contact_institution = m_patient['contact'].get('institution')
            if (contact_institution and ('Scout software user' in contact_institution)):
                match_type = 'internal'
            score = None
            for res in match_obj['results']:
                for patient in res['patients']:
                    LOG.info('Looping in else, patient:{}'.format(patient['patient']['id']))
                    if (patient['patient']['id'] == patient_id):
                        score = patient['score']
                        match_patient = {'patient_id': m_patient['id'], 'score': score, 'patient': m_patient, 'node': res['node']}
                        matching_patients.append(match_patient)
        parsed_match['match_type'] = match_type
        parsed_match['patients'] = matching_patients
        parsed_matches.append(parsed_match)
    parsed_matches = sorted(parsed_matches, key=(lambda k: k['match_date']), reverse=True)
    return parsed_matches

Parse a list of matchmaker matches objects and returns
    a readable list of matches to display in matchmaker matches view.

Args:
    patient_id(str): id of a mme patient
    match_objs(list): list of match objs returned by MME server for the patient
            # match_objs looks like this:
                [
                    {
                        'node' : { id : node_id , label: node_label},
                        'patients' : [
                            { 'patient': {patient1_data} },
                            { 'patient': {patient2_data} },
                            ..
                        ]
                    },
                    ..
                ]

Returns:
    parsed_matches(list): a list of parsed match objects


def from_node(cls, node):
    if (not isinstance(node, aioxmpp.stanza.Message)):
        raise AttributeError('node must be a aioxmpp.stanza.Message instance')
    msg = cls()
    msg._to = node.to
    msg._sender = node.from_
    if (None in node.body):
        msg.body = node.body[None]
    else:
        for key in node.body.keys():
            msg.body = node.body[key]
            break
    for data in node.xep0004_data:
        if (data.title == SPADE_X_METADATA):
            for field in data.fields:
                if (field.var != '_thread_node'):
                    msg.set_metadata(field.var, field.values[0])
                else:
                    msg.thread = field.values[0]
    return msg

Creates a new spade.message.Message from an aixoxmpp.stanza.Message

Args:
        node (aioxmpp.stanza.Message): an aioxmpp Message

Returns:
        spade.message.Message: a new spade Message


def download_hrrr_for_gssha(main_directory, forecast_start_date_string, forecast_start_hour_string, leftlon=(- 180), rightlon=180, toplat=90, bottomlat=(- 90)):
    out_directory = path.join(main_directory, forecast_start_date_string)
    try:
        mkdir(out_directory)
    except OSError:
        pass
    forecast_timestep_hour_string_array = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18']
    downloaded_file_list = []
    for forecast_timestep_hour_string in forecast_timestep_hour_string_array:
        file_name = 'hrrr.t{0}z.wrfsfcf{1}.grib2'.format(forecast_start_hour_string, forecast_timestep_hour_string)
        payload = {'file': file_name, 'lev_10_m_above_ground': 'on', 'lev_2_m_above_ground': 'on', 'lev_entire_atmosphere': 'on', 'lev_surface': 'on', 'var_DSWRF': 'on', 'var_PRATE': 'on', 'var_PRES': 'on', 'var_RH': 'on', 'var_TMP': 'on', 'var_UGRD': 'on', 'var_VGRD': 'on', 'var_TCDC': 'on', 'subregion': '', 'leftlon': str(leftlon), 'rightlon': str(rightlon), 'toplat': str(toplat), 'bottomlat': str(bottomlat), 'dir': '/hrrr.{0}'.format(forecast_start_date_string)}
        r = requests.get('http://nomads.ncep.noaa.gov/cgi-bin/filter_hrrr_2d.pl', params=payload, stream=True)
        if (r.status_code == requests.codes.ok):
            out_file = path.join(out_directory, file_name)
            downloaded_file_list.append(out_file)
            with open(out_file, 'wb') as fd:
                for chunk in r.iter_content(chunk_size=1024):
                    fd.write(chunk)
        else:
            log.error('Problem downloading {0}'.format(file_name))
            for filename in downloaded_file_list:
                try:
                    remove(filename)
                except OSError:
                    pass
            downloaded_file_list = []
            break
    return downloaded_file_list

Function to download HRRR data for GSSHA

    URL:
        http://nomads.ncep.noaa.gov/cgi-bin/filter_hrrr_2d.pl

Args:
        main_directory(str): Location of the output for the forecast data.
        forecast_start_date_string(str): String for day of forecast. Ex. '20160913'
        forecast_start_hour_string(str): String for hour of forecast start. Ex. '02'
        leftlon(Optional[double,int]): Left bound for longitude. Default is -180.
        rightlon(Optional[double,int]): Right bound for longitude. Default is 180.
        toplat(Optional[double,int]): Top bound for latitude. Default is 90.
        bottomlat(Optional[double,int]): Bottom bound for latitude. Default is -90.

Returns:
        downloaded_file_list(list): List of paths to downloaded files.

    Example::

        from gsshapy.grid.hrrr_to_gssha import download_hrrr_for_gssha

        hrrr_folder = '/HRRR'
        leftlon = -95
        rightlon = -75
        toplat = 35
        bottomlat = 30
        downloaded_file_list = download_hrrr_for_gssha(hrrr_folder,'20160914','01',
                                                    leftlon,rightlon,toplat,bottomlat)


def reflection(normal, origin=(0, 0, 0)):
    n = (np.array(normal, dtype=float) / np.linalg.norm(normal))
    (u, v, w) = n
    translation = np.eye(4)
    translation[(0:3, 3)] = (- np.array(origin))
    xx = (1 - (2 * (u ** 2)))
    yy = (1 - (2 * (v ** 2)))
    zz = (1 - (2 * (w ** 2)))
    xy = (((- 2) * u) * v)
    xz = (((- 2) * u) * w)
    yz = (((- 2) * v) * w)
    mirror_mat = [[xx, xy, xz, 0], [xy, yy, yz, 0], [xz, yz, zz, 0], [0, 0, 0, 1]]
    if (np.linalg.norm(origin) > 1e-06):
        mirror_mat = np.dot(np.linalg.inv(translation), np.dot(mirror_mat, translation))
    return SymmOp(mirror_mat)

Returns reflection symmetry operation.

Args:
        normal (3x1 array): Vector of the normal to the plane of
            reflection.
        origin (3x1 array): A point in which the mirror plane passes
            through.

Returns:
        SymmOp for the reflection about the plane


def token_to_id(self, token):
    token = self.process_token(token)
    return self._token2id.get(token, (len(self._token2id) - 1))

Get the token_id of given token.

Args:
        token (str): token from vocabulary.

Returns:
        int: int id of token.


def load_configuration(config_file, config_dir, service_file):
    config_files = [config_file]
    config = configparser.ConfigParser()
    config.read_dict(DEFAULT_OPTIONS)
    if (not os.path.isfile(config_file)):
        raise ValueError("{f} configuration file either isn't readable or doesn't exist".format(f=config_file))
    if (service_file is not None):
        if (not os.path.isfile(service_file)):
            raise ValueError("{f} configuration file for a service check doesn't exist".format(f=service_file))
        else:
            config_files.append(service_file)
    elif (config_dir is not None):
        if (not os.path.isdir(config_dir)):
            raise ValueError("{d} directory with configuration files for service checks doesn't exist".format(d=config_dir))
        else:
            config_files.extend(glob.glob(os.path.join(config_dir, '*.conf')))
    try:
        config.read(config_files)
    except configparser.Error as exc:
        raise ValueError(exc)
    configuration_check(config)
    bird_configuration = build_bird_configuration(config)
    create_bird_config_files(bird_configuration)
    return (config, bird_configuration)

Build configuration objects.

    If all sanity checks against daemon and service check settings are passed
    then it builds a ConfigParser object which holds all our configuration
    and a dictionary data structure which holds Bird configuration per IP
    protocol version.

Args:
        config_file (str): The file name which holds daemon settings
        config_dir (str): The directory name which has configuration files
        for each service check
        service_file (str): A file which contains configuration for a single
        service check

Returns:
        A tuple with 1st element a ConfigParser object and 2nd element
        a dictionary.

Raises:
        ValueError if a sanity check fails.


def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''):
    log.info('Get latest data for sensors. Stop with Ctrl+C.')
    log.info('Stops automatically in %ss', search_duratio_sec)
    log.info('MACs: %s', macs)
    datas = dict()
    for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device):
        datas[new_data[0]] = new_data[1]
    return datas

Get lates data for sensors in the MAC's list.

Args:
        macs (array): MAC addresses
        search_duratio_sec (int): Search duration in seconds. Default 5
        bt_device (string): Bluetooth device id

Returns:
        dict: MAC and state of found sensors


def transform_to_mods_mono(marc_xml, uuid, url):
    marc_xml = _read_content_or_path(marc_xml)
    transformed = xslt_transformation(marc_xml, _absolute_template_path('MARC21slim2MODS3-4-NDK.xsl'))
    return _apply_postprocessing(marc_xml=marc_xml, xml=transformed, func=mods_postprocessor.postprocess_monograph, uuid=uuid, url=url)

Convert `marc_xml` to MODS data format.

Args:
        marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
                        filename.
        uuid (str): UUID string giving the package ID.
        url (str): URL of the publication (public or not).

Returns:
        list: Collection of transformed xml strings.


def write_int8(self, value, little_endian=True):
    if little_endian:
        endian = '<'
    else:
        endian = '>'
    return self.pack(('%sb' % endian), value)

Pack the value as a signed byte and write 1 byte to the stream.

Args:
        value:
        little_endian (bool): specify the endianness. (Default) Little endian.

Returns:
        int: the number of bytes written.


def _ConvertValueBinaryDataToUBInt64(self, value):
    if (not value):
        return None
    integer_map = self._GetDataTypeMap('uint64be')
    try:
        return self._ReadStructureFromByteStream(value, 0, integer_map)
    except (ValueError, errors.ParseError) as exception:
        raise errors.ParseError('Unable to parse integer value with error: {0!s}'.format(exception))

Converts a binary data value into an integer.

Args:
        value (bytes): binary data value containing an unsigned 64-bit big-endian
        integer.

Returns:
        int: integer representation of binary data value or None if value is
        not set.

Raises:
        ParseError: if the integer value cannot be parsed.


def get_stream_action_type(stream_arn):
    stream_type_map = {'kinesis': awacs.kinesis.Action, 'dynamodb': awacs.dynamodb.Action}
    stream_type = stream_arn.split(':')[2]
    try:
        return stream_type_map[stream_type]
    except KeyError:
        raise ValueError(("Invalid stream type '%s' in arn '%s'" % (stream_type, stream_arn)))

Returns the awacs Action for a stream type given an arn

Args:
        stream_arn (str): The Arn of the stream.

Returns:
        :class:`awacs.aws.Action`: The appropriate stream type awacs Action
            class

Raises:
        ValueError: If the stream type doesn't match kinesis or dynamodb.


def GetEventFormatter(self, event):
    data_type = getattr(event, 'data_type', None)
    if (not data_type):
        return None
    return formatters_manager.FormattersManager.GetFormatterObject(event.data_type)

Retrieves the event formatter for a specific event type.

Args:
        event (EventObject): event.

Returns:
        EventFormatter: event formatter or None.


def _GetComparable(self, sub_comparable_string=''):
    string_parts = []
    string_parts.append(getattr(self.parent, 'comparable', ''))
    string_parts.append('type: {0:s}'.format(self.type_indicator))
    if sub_comparable_string:
        string_parts.append(', {0:s}'.format(sub_comparable_string))
    string_parts.append('\n')
    return ''.join(string_parts)

Retrieves the comparable representation.

    This is a convenience function for constructing comparables.

Args:
        sub_comparable_string (str): sub comparable string.

Returns:
        str: comparable representation of the path specification.


def state_scope(self, state_fluents: Sequence[tf.Tensor]) -> Dict[(str, TensorFluent)]:
    return dict(zip(self.rddl.domain.state_fluent_ordering, state_fluents))

Returns a partial scope with current state-fluents.

Args:
        state_fluents (Sequence[tf.Tensor]): The current state fluents.

Returns:
        A mapping from state fluent names to :obj:`rddl2tf.fluent.TensorFluent`.


def add_network(self, network, netmask, area=0):
    if ((network == '') or (netmask == '')):
        raise ValueError('network and mask values may not be empty')
    cmd = 'network {}/{} area {}'.format(network, netmask, area)
    return self.configure_ospf(cmd)

Adds a network to be advertised by OSPF

Args:
        network (str):  The network to be advertised in dotted decimal
                        notation
        netmask (str):  The netmask to configure
        area (str):  The area the network belongs to.
                    By default this value is 0

Returns:
        bool: True if the command completes successfully
    Exception:
        ValueError: This will get raised if network or netmask
                    are not passed to the method


def CreateTask(self, session_identifier):
    task = tasks.Task(session_identifier)
    logger.debug('Created task: {0:s}.'.format(task.identifier))
    with self._lock:
        self._tasks_queued[task.identifier] = task
        self._total_number_of_tasks += 1
        self.SampleTaskStatus(task, 'created')
    return task

Creates a task.

Args:
        session_identifier (str): the identifier of the session the task is
        part of.

Returns:
        Task: task attribute container.


def GetDecrypter(cls, encryption_method, **kwargs):
    encryption_method = encryption_method.lower()
    decrypter = cls._decrypters.get(encryption_method, None)
    if (not decrypter):
        return None
    return decrypter(**kwargs)

Retrieves the decrypter object for a specific encryption method.

Args:
        encryption_method (str): encryption method identifier.
        kwargs (dict): keyword arguments depending on the decrypter.

Returns:
        Decrypter: decrypter or None if the encryption method does not exists.

Raises:
        CredentialError: if the necessary credentials are missing.


def case(self, case):
    LOG.debug('Getting case {0} from database'.format(case.get('case_id')))
    case_id = case['case_id']
    return self.db.case.find_one({'case_id': case_id})

Get a case from the database

    Search the cases with the case id

Args:
        case (dict): A case dictionary

Returns:
        mongo_case (dict): A mongo case dictionary


def _fetch(self, method, url=None, post_data=None, parse_data=True, key=None, parameters=None, listener=None, full_return=False):
    headers = self.get_headers()
    headers['Content-Type'] = 'application/json'
    handlers = []
    debuglevel = int(self._settings['debug'])
    handlers.append(urllib2.HTTPHandler(debuglevel=debuglevel))
    if hasattr(httplib, 'HTTPS'):
        handlers.append(urllib2.HTTPSHandler(debuglevel=debuglevel))
    handlers.append(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
    password_url = self._get_password_url()
    if (password_url and ('Authorization' not in headers)):
        pwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
        pwd_manager.add_password(None, password_url, self._settings['user'], self._settings['password'])
        handlers.append(HTTPBasicAuthHandler(pwd_manager))
    opener = urllib2.build_opener(*handlers)
    if (post_data is not None):
        post_data = json.dumps(post_data)
    uri = self._url(url, parameters)
    request = RESTRequest(uri, method=method, headers=headers)
    if (post_data is not None):
        request.add_data(post_data)
    response = None
    try:
        response = opener.open(request)
        body = response.read()
        if (password_url and (password_url not in self._settings['authorizations']) and request.has_header('Authorization')):
            self._settings['authorizations'][password_url] = request.get_header('Authorization')
    except urllib2.HTTPError as e:
        if (e.code == 401):
            raise AuthenticationError(('Access denied while trying to access %s' % uri))
        elif (e.code == 404):
            raise ConnectionError(('URL not found: %s' % uri))
        else:
            raise
    except urllib2.URLError as e:
        raise ConnectionError(('Error while fetching from %s: %s' % (uri, e)))
    finally:
        if response:
            response.close()
        opener.close()
    data = None
    if parse_data:
        if (not key):
            key = string.split(url, '/')[0]
        data = self.parse(body, key)
    if full_return:
        info = (response.info() if response else None)
        status = (int(string.split(info['status'])[0]) if (info and ('status' in info)) else None)
        return {'success': ((status >= 200) and (status < 300)), 'data': data, 'info': info, 'body': body}
    return data

Issue a request.

Args:
        method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None

    Kwargs:
        url (str): Destination URL
        post_data (str): A string of what to POST
        parse_data (bool): If true, parse response data
        key (string): If parse_data==True, look for this key when parsing data
        parameters (dict): Additional GET parameters to append to the URL
        listener (func): callback called when uploading a file
        full_return (bool): If set to True, get a full response (with success, data, info, body)

Returns:
        dict. Response. If full_return==True, a dict with keys: success, data, info, body, otherwise the parsed data

Raises:
        AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError


def execute_plan(plan):
    results = [action() for action in plan]
    return [result for result in results if actns.step_has_failed(result)]

Execute the plan.

Args:
        plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute.

Returns:
        (:obj:`list` of :obj:`actions.Step`): A list of failed actions.


def get_file(self, url, path_or_file=None, headers=None, filename=None):
    path_or_file = (path_or_file or filename)
    if self.debug:
        print(('GET FILE: %s, headers=%s' % (url, headers)))
    self.headers = self._get_default_headers()
    if (headers is not None):
        self.headers.update(headers)
    response = requests.get(url, headers=self.headers, auth=self.auth, verify=self.verify_ssl)
    self.http_status_code = response.status_code
    try:
        self._check_error(response)
        try:
            path_or_file.write(response.content)
        except AttributeError:
            fd = os.open(path_or_file, (os.O_CREAT | os.O_RDWR))
            with os.fdopen(fd, 'w+b') as f:
                f.write(response.content)
    except:
        return False
    return True

Get a file from a url and save it as `filename`

Args:
        url (str): URL to send the request to

        path_or_file (str or file): A writable File-like object or a path to save the file to.

        filename (str): [DEPRECATED] File name to save the file as, this can be either
            a full path or a relative path

        headers (str, optional): custom headers

Returns:
        True if file is downloaded and written successfully, False
        otherwise.


def base_name_from_image(image):
    m = re.match('^(.+/)?([^:/]+)(:[^:]+)?$', image)
    algo_name = (m.group(2) if m else image)
    return algo_name

Extract the base name of the image to use as the 'algorithm name' for the job.

Args:
        image (str): Image name.

Returns:
        str: Algorithm name, as extracted from the image name.


def _get_nan_block_id(partition_class, n_row=1, n_col=1, transpose=False):
    global _NAN_BLOCKS
    if transpose:
        (n_row, n_col) = (n_col, n_row)
    shape = (n_row, n_col)
    if (shape not in _NAN_BLOCKS):
        arr = np.tile(np.array(np.NaN), shape)
        _NAN_BLOCKS[shape] = partition_class.put(pandas.DataFrame(data=arr))
    return _NAN_BLOCKS[shape]

A memory efficient way to get a block of NaNs.

Args:
        partition_class (BaseFramePartition): The class to use to put the object
            in the remote format.
        n_row(int): The number of rows.
        n_col(int): The number of columns.
        transpose(bool): If true, swap rows and columns.

Returns:
        ObjectID of the NaN block.


def create_graph_from_data(self, data, **kwargs):
    self.arguments['{SCORE}'] = self.scores[self.score]
    self.arguments['{CUTOFF}'] = str(self.cutoff)
    self.arguments['{VARSEL}'] = str(self.variablesel).upper()
    self.arguments['{SELMETHOD}'] = self.var_selection[self.selmethod]
    self.arguments['{PRUNING}'] = str(self.pruning).upper()
    self.arguments['{PRUNMETHOD}'] = self.var_selection[self.prunmethod]
    self.arguments['{NJOBS}'] = str(self.nb_jobs)
    self.arguments['{VERBOSE}'] = str(self.verbose).upper()
    results = self._run_cam(data, verbose=self.verbose)
    return nx.relabel_nodes(nx.DiGraph(results), {idx: i for (idx, i) in enumerate(data.columns)})

Apply causal discovery on observational data using CAM.

Args:
        data (pandas.DataFrame): DataFrame containing the data

Returns:
        networkx.DiGraph: Solution given by the CAM algorithm.


def defaultannotator(self, annotationtype, set=None):
    if (inspect.isclass(annotationtype) or isinstance(annotationtype, AbstractElement)):
        annotationtype = annotationtype.ANNOTATIONTYPE
    if (not set):
        set = self.defaultset(annotationtype)
    try:
        return self.annotationdefaults[annotationtype][set]['annotator']
    except KeyError:
        raise NoDefaultError

Obtain the default annotator for the specified annotation type and set.

Args:
        annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`AnnotationType`, such as ``AnnotationType.POS``.
        set (str): the set, should formally be a URL pointing to the set definition

Returns:
        the set (str)

Raises:
        :class:`NoDefaultError` if the annotation type does not exist or if there is ambiguity (multiple sets for the same type)


def get_nn_info(self, structure, n):
    nns = self.get_voronoi_polyhedra(structure, n)
    return self._extract_nn_info(structure, nns)

Get all near-neighbor sites as well as the associated image locations
    and weights of the site with index n in structure
    using Voronoi decomposition.

Args:
        structure (Structure): input structure.
        n (integer): index of site for which to determine near-neighbor
            sites.

Returns:
        siw (list of tuples (Site, array, float)): tuples, each one
            of which represents a coordinated site, its image location,
            and its weight.


def from_string(cls, model_id, default_project=None):
    (proj, dset, model) = _helpers._parse_3_part_id(model_id, default_project=default_project, property_name='model_id')
    return cls.from_api_repr({'projectId': proj, 'datasetId': dset, 'modelId': model})

Construct a model reference from model ID string.

Args:
        model_id (str):
            A model ID in standard SQL format. If ``default_project``
            is not specified, this must included a project ID, dataset
            ID, and model ID, each separated by ``.``.
        default_project (str):
            Optional. The project ID to use when ``model_id`` does not
            include a project ID.

Returns:
        google.cloud.bigquery.model.ModelReference:
            Model reference parsed from ``model_id``.

Raises:
        ValueError:
            If ``model_id`` is not a fully-qualified table ID in
            standard SQL format.


def load_config_file(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME, fallback_config_instance=None):
    if (not fallback_config_instance):
        fallback_config_instance = backend_config_to_configparser(get_default_backend_config(appdirs))
    config = SafeConfigParser()
    path = get_config_path(appdirs, file_name)
    if (not config.read(path)):
        config = write_config_file(fallback_config_instance, appdirs=appdirs, file_name=file_name)
    return config

Retrieve config information from file at default location.

    If no config file is found a new one will be created either with ``fallback_config_instance``
    as content or if none is provided with the result of ``get_default_backend_config``.

Args:
        appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific
            path information.
        file_name (text_type, optional): Name of the config file. Defaults to
        ``DEFAULT_CONFIG_FILENAME``.
        fallback_config_instance (ConfigParser): Backend config that is to be used to populate the
            config file that is created if no pre-existing one can be found.

Returns:
        SafeConfigParser: Config loaded from file, either from the the  pre-existing config
            file or the one created with fallback values.


def get_groups(self, **kwargs):
    params = {'cultureInfo': util.language_code(kwargs.get('lang'))}
    result = self.make_request('geo', 'get_groups', **params)
    if (not util.check_result(result)):
        return (False, result.get('resultDescription', 'UNKNOWN ERROR'))
    values = util.response_list(result, 'resultValues')
    return (True, [emtype.GeoGroupItem(**a) for a in values])

Obtain line types and details.

Args:
        lang (str): Language code (*es* or *en*).

Returns:
        Status boolean and parsed response (list[GeoGroupItem]), or message
        string in case of error.


def get(self, public_key, spent=None, headers=None):
    return self.transport.forward_request(method='GET', path=self.path, params={'public_key': public_key, 'spent': spent}, headers=headers)

Get transaction outputs by public key. The public_key parameter
    must be a base58 encoded ed25519 public key associated with
    transaction output ownership.

Args:
        public_key (str): Public key for which unfulfilled
            conditions are sought.
        spent (bool): Indicate if the result set should include only spent
            or only unspent outputs. If not specified (``None``) the
            result includes all the outputs (both spent and unspent)
            associated with the public key.
        headers (dict): Optional headers to pass to the request.

Returns:
        :obj:`list` of :obj:`str`: List of unfulfilled conditions.

Example:
        Given a transaction with `id` ``da1b64a907ba54`` having an
        `ed25519` condition (at index ``0``) with alice's public
        key::

            >>> bdb = BigchainDB()
            >>> bdb.outputs.get(alice_pubkey)
            ... ['../transactions/da1b64a907ba54/conditions/0']


def download_archive_artifact_bundle(self, id_or_uri, file_path):
    uri = ((self.BACKUP_ARCHIVE_PATH + '/') + extract_id_from_uri(id_or_uri))
    return self._client.download(uri, file_path)

Downloads an archive for the Artifact Bundle.

Args:
        id_or_uri: ID or URI of the Artifact Bundle.
        file_path(str): Destination file path.

Returns:
        bool: Successfully downloaded.


def _GetCachedEntryDataTypeMap(self, format_type, value_data, cached_entry_offset):
    if (format_type not in self._SUPPORTED_FORMAT_TYPES):
        raise errors.ParseError('Unsupported format type: {0:d}'.format(format_type))
    data_type_map_name = ''
    if (format_type == self._FORMAT_TYPE_XP):
        data_type_map_name = 'appcompatcache_cached_entry_xp_32bit'
    elif (format_type in (self._FORMAT_TYPE_8, self._FORMAT_TYPE_10)):
        data_type_map_name = 'appcompatcache_cached_entry_header_8'
    else:
        cached_entry = self._ParseCommon2003CachedEntry(value_data, cached_entry_offset)
        if ((cached_entry.path_offset_32bit == 0) and (cached_entry.path_offset_64bit != 0)):
            number_of_bits = '64'
        else:
            number_of_bits = '32'
        if (format_type == self._FORMAT_TYPE_2003):
            data_type_map_name = 'appcompatcache_cached_entry_2003_{0:s}bit'.format(number_of_bits)
        elif (format_type == self._FORMAT_TYPE_VISTA):
            data_type_map_name = 'appcompatcache_cached_entry_vista_{0:s}bit'.format(number_of_bits)
        elif (format_type == self._FORMAT_TYPE_7):
            data_type_map_name = 'appcompatcache_cached_entry_7_{0:s}bit'.format(number_of_bits)
    return self._GetDataTypeMap(data_type_map_name)

Determines the cached entry data type map.

Args:
        format_type (int): format type.
        value_data (bytes): value data.
        cached_entry_offset (int): offset of the first cached entry data
        relative to the start of the value data.

Returns:
        dtfabric.DataTypeMap: data type map which contains a data type definition,
        such as a structure, that can be mapped onto binary data or None
        if the data type map is not defined.

Raises:
        ParseError: if the cached entry data type map cannot be determined.


def _use_prototype(self, spec, prototypes):
    prototype = spec['based-on']
    del spec['based-on']
    for attr in prototype:
        if (attr not in spec):
            spec[attr] = copy.deepcopy(prototype[attr])
    return spec

Populates the given spec with the values of it's declared prototype

Args:
        spec (dict): spec to update
        prototypes (dict): Configuration spec containing the prototypes

Returns:
        dict: updated spec


def memoise(cls, func):

    @functools.wraps(func)
    def f(*a):
        for arg in a:
            if isinstance(arg, User):
                user = arg
                break
        else:
            raise ValueError('One position argument must be a User')
        func_key = (func, tuple(a))
        cache = cls.get_cache(user)
        if (func_key not in cache):
            cache[func_key] = func(*a)
        return cache[func_key]
    return f

Decorator that stores the result of the stored function in the
    user's results cache until the batch completes. Keyword arguments are
    not yet supported.

Args:
        func (callable(*a)): The function whose results we want
            to store. The positional arguments, ``a``, are used as cache
            keys.

Returns:
        callable(*a): The memosing version of ``func``.


def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False):
    if (self._dimension != 2):
        raise NotImplementedError('2D is the only supported dimension', 'Current dimension', self._dimension)
    if (ax is None):
        ax = _plot_helpers.new_axis()
    _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges())
    if with_nodes:
        ax.plot(self._nodes[(0, :)], self._nodes[(1, :)], color='black', marker='o', linestyle='None')
    return ax

Plot the current surface.

Args:
        pts_per_edge (int): Number of points to plot per edge.
        color (Optional[Tuple[float, float, float]]): Color as RGB profile.
        ax (Optional[matplotlib.artist.Artist]): matplotlib axis object
            to add plot to.
        with_nodes (Optional[bool]): Determines if the control points
            should be added to the plot. Off by default.

Returns:
        matplotlib.artist.Artist: The axis containing the plot. This
        may be a newly created axis.

Raises:
        NotImplementedError: If the surface's dimension is not ``2``.


def smooth(self, noise, strategy=INVERSE_STRATEGY):
    if (strategy is INVERSE_STRATEGY):
        self.points = with_inverse(self.points, noise)
    elif (strategy is EXTRAPOLATE_STRATEGY):
        self.points = with_extrapolation(self.points, noise, 30)
    elif (strategy is NO_STRATEGY):
        self.points = with_no_strategy(self.points, noise)
    return self

In-place smoothing

    See smooth_segment function

Args:
        noise (float): Noise expected
        strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY
            or smooth.EXTRAPOLATE_STRATEGY

Returns:
        :obj:`Segment`


def get_street_from_xy(self, **kwargs):
    params = {'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs.get('lang'))}
    result = self.make_request('geo', 'get_street_from_xy', **params)
    if (not util.check_result(result, 'site')):
        return (False, 'UNKNOWN ERROR')
    values = util.response_list(result, 'site')
    return (True, [emtype.Street(**a) for a in values])

Obtain a list of streets around the specified point.

Args:
        latitude (double): Latitude in decimal degrees.
        longitude (double): Longitude in decimal degrees.
        radius (int): Radius (in meters) of the search.
        lang (str): Language code (*es* or *en*).

Returns:
        Status boolean and parsed response (list[Street]), or message string
        in case of error.


def log_handler(self, handler):
    if (not self.opened()):
        handler = (handler or util.noop)
        self._log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
        self._dll.JLINKARM_EnableLog(self._log_handler)

Setter for the log handler function.

Args:
        self (JLink): the ``JLink`` instance

Returns:
        ``None``


def builtin(cls, name):
    names = {'nsdoe': LEGEND__NSDOE, 'canstrat': LEGEND__Canstrat, 'nagmdm__6_2': LEGEND__NAGMDM__6_2, 'nagmdm__6_1': LEGEND__NAGMDM__6_1, 'nagmdm__4_3': LEGEND__NAGMDM__4_3, 'sgmc': LEGEND__SGMC}
    return cls.from_csv(text=names[name.lower()])

Generate a default legend.

Args:
        name (str): The name of the legend you want. Not case sensitive.
            'nsdoe': Nova Scotia Dept. of Energy
            'canstrat': Canstrat
            'nagmdm__6_2': USGS N. Am. Geol. Map Data Model 6.2
            'nagmdm__6_1': USGS N. Am. Geol. Map Data Model 6.1
            'nagmdm__4_3': USGS N. Am. Geol. Map Data Model 4.3
            'sgmc': USGS State Geologic Map Compilation

        Default 'nagmdm__6_2'.

Returns:
        Legend: The legend stored in `defaults.py`.


def remove_item(self, item):
    for (idx, _item) in enumerate(self.items):
        if (item == _item):
            del self.items[idx]
            return True
    return False

Remove the specified item from the menu.

Args:
        item (MenuItem): the item to be removed.

Returns:
        bool: True if the item was removed; False otherwise.


def from_json(cls, jsonmsg):
    import json
    msg = json.loads(jsonmsg)
    obj = cls(**msg)
    obj.validate()
    return obj

Create an object directly from a JSON string.

    Applies general validation after creating the
    object to check whether all required fields are
    present.

Args:
        jsonmsg (str): An object encoded as a JSON string

Returns:
        An object of the generated type

Raises:
        ValidationError: if `jsonmsg` does not match the schema
            `cls` was generated from


def rebin(d, n_x, n_y=None):
    if (d.ndim == 2):
        if (n_y is None):
            n_y = 1
        if (n_x is None):
            n_x = 1
        d = d[(:(int((d.shape[0] // n_x)) * n_x), :(int((d.shape[1] // n_y)) * n_y))]
        d = d.reshape(((d.shape[0] // n_x), n_x, (d.shape[1] // n_y), n_y))
        d = d.mean(axis=3)
        d = d.mean(axis=1)
    elif (d.ndim == 1):
        d = d[:(int((d.shape[0] // n_x)) * n_x)]
        d = d.reshape(((d.shape[0] // n_x), n_x))
        d = d.mean(axis=1)
    else:
        raise RuntimeError('Only NDIM <= 2 supported')
    return d

Rebin data by averaging bins together

Args:
    d (np.array): data
    n_x (int): number of bins in x dir to rebin into one
    n_y (int): number of bins in y dir to rebin into one

Returns:
    d: rebinned data with shape (n_x, n_y)


def margin_transfer(self, margin_profile_id, transfer_type, currency, amount):
    params = {'margin_profile_id': margin_profile_id, 'type': transfer_type, 'currency': currency, 'amount': amount}
    return self._send_message('post', '/profiles/margin-transfer', data=json.dumps(params))

Transfer funds between your standard profile and a margin profile.

Args:
        margin_profile_id (str): Margin profile ID to withdraw or deposit
            from.
        transfer_type (str): 'deposit' or 'withdraw'
        currency (str): Currency to transfer (eg. 'USD')
        amount (Decimal): Amount to transfer

Returns:
        dict: Transfer details. Example::
            {
            "created_at": "2017-01-25T19:06:23.415126Z",
            "id": "80bc6b74-8b1f-4c60-a089-c61f9810d4ab",
            "user_id": "521c20b3d4ab09621f000011",
            "profile_id": "cda95996-ac59-45a3-a42e-30daeb061867",
            "margin_profile_id": "45fa9e3b-00ba-4631-b907-8a98cbdf21be",
            "type": "deposit",
            "amount": "2",
            "currency": "USD",
            "account_id": "23035fc7-0707-4b59-b0d2-95d0c035f8f5",
            "margin_account_id": "e1d9862c-a259-4e83-96cd-376352a9d24d",
            "margin_product_id": "BTC-USD",
            "status": "completed",
            "nonce": 25
            }


def build_parameters(self, stack, provider_stack=None):
    resolved = _resolve_parameters(stack.parameter_values, stack.blueprint)
    required_parameters = list(stack.required_parameter_definitions)
    all_parameters = list(stack.all_parameter_definitions)
    parameters = _handle_missing_parameters(resolved, all_parameters, required_parameters, provider_stack)
    param_list = []
    for (key, value) in parameters:
        param_dict = {'ParameterKey': key}
        if (value is UsePreviousParameterValue):
            param_dict['UsePreviousValue'] = True
        else:
            param_dict['ParameterValue'] = str(value)
        param_list.append(param_dict)
    return param_list

Builds the CloudFormation Parameters for our stack.

Args:
        stack (:class:`stacker.stack.Stack`): A stacker stack
        provider_stack (dict): An optional Stacker provider object

Returns:
        dict: The parameters for the given stack


def get_sns_topic_arn(topic_name, account, region):
    if ((topic_name.count(':') == 5) and topic_name.startswith('arn:aws:sns:')):
        return topic_name
    session = boto3.Session(profile_name=account, region_name=region)
    sns_client = session.client('sns')
    topics = sns_client.list_topics()['Topics']
    matched_topic = None
    for topic in topics:
        topic_arn = topic['TopicArn']
        if (topic_name == topic_arn.split(':')[(- 1)]):
            matched_topic = topic_arn
            break
    else:
        LOG.critical('No topic with name %s found.', topic_name)
        raise SNSTopicNotFound('No topic with name {0} found'.format(topic_name))
    return matched_topic

Get SNS topic ARN.

Args:
        topic_name (str): Name of the topic to lookup.
        account (str): Environment, e.g. dev
        region (str): Region name, e.g. us-east-1

Returns:
        str: ARN for requested topic name


def get_cmd_out(command):
    if isinstance(command, list):
        result = sp.check_output(command)
    else:
        result = sp.check_output(command, shell=True)
    return result.decode('utf-8').rstrip()

Get the output of a command.

    Gets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command.

Args:
        command (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`).

Note:
        If ``command`` is a ``str``, it will be evaluated with ``shell=True`` i.e. in the default shell (for example, bash).

Returns:
        str: The ``stdout`` of the command.


def section(self, section):
    if (not isinstance(self._container, ConfigUpdater)):
        raise ValueError('Sections can only be added at section level!')
    if isinstance(section, str):
        section = Section(section, container=self._container)
    elif (not isinstance(section, Section)):
        raise ValueError('Parameter must be a string or Section type!')
    if (section.name in [block.name for block in self._container if isinstance(block, Section)]):
        raise DuplicateSectionError(section.name)
    self._container.structure.insert(self._idx, section)
    self._idx += 1
    return self

Creates a section block

Args:
        section (str or :class:`Section`): name of section or object

Returns:
        self for chaining


def list(self, resource, url_prefix, auth, session, send_opts):
    req = self.get_request(resource, 'GET', 'application/json', url_prefix, auth, proj_list_req=True)
    prep = session.prepare_request(req)
    resp = session.send(prep, **send_opts)
    if (resp.status_code == 200):
        return self._get_resource_list(resp.json())
    err = 'List failed on {}, got HTTP response: ({}) - {}'.format(resource.name, resp.status_code, resp.text)
    raise HTTPError(err, request=req, response=resp)

List all resources of the same type as the given resource.

Args:
        resource (intern.resource.boss.BossResource): List resources of the same type as this..
        url_prefix (string): Protocol + host such as https://api.theboss.io
        auth (string): Token to send in the request header.
        session (requests.Session): HTTP session to use for request.
        send_opts (dictionary): Additional arguments to pass to session.send().

Returns:
        (list): List of resources.  Each resource is a dictionary.

Raises:
        requests.HTTPError on failure.


def PyParseRangeCheck(lower_bound, upper_bound):

    def CheckRange(string, location, tokens):
        'Parse the arguments.\n\n    Args:\n      string (str): original string.\n      location (int): location in the string where the match was made\n      tokens (list[str]): tokens.\n    '
        try:
            check_number = tokens[0]
        except IndexError:
            check_number = (- 1)
        if (check_number < lower_bound):
            raise pyparsing.ParseException('Value: {0:d} precedes lower bound: {1:d}'.format(check_number, lower_bound))
        if (check_number > upper_bound):
            raise pyparsing.ParseException('Value: {0:d} exceeds upper bound: {1:d}'.format(check_number, upper_bound))
    return CheckRange

Verify that a number is within a defined range.

    This is a callback method for pyparsing setParseAction
    that verifies that a read number is within a certain range.

    To use this method it needs to be defined as a callback method
    in setParseAction with the upper and lower bound set as parameters.

Args:
        lower_bound (int): lower bound of the range.
        upper_bound (int): upper bound of the range.

Returns:
        Function: callback method that can be used by pyparsing setParseAction.


def decode_metar(self, metar):
    try:
        from metar import Metar
    except:
        return 'Unable to parse metars. Please install parser from https://github.com/tomp/python-metar.'
    m = Metar.Metar(metar)
    return m.string()

Simple method that decodes a given metar string.

Args:
        metar (str): The metar data

Returns:
        The metar data in readable format

    Example::

        from pyflightdata import FlightData
        f=FlightData()
        f.decode_metar('WSSS 181030Z 04009KT 010V080 9999 FEW018TCU BKN300 29/22 Q1007 NOSIG')


def dependency_of_fetches(fetches, op):
    try:
        from tensorflow.python.client.session import _FetchHandler as FetchHandler
        handler = FetchHandler(op.graph, fetches, {})
        targets = tuple((handler.fetches() + handler.targets()))
    except ImportError:
        if isinstance(fetches, list):
            targets = tuple(fetches)
        elif isinstance(fetches, dict):
            raise ValueError("Don't know how to parse dictionary to fetch list! This is a bug of tensorpack.")
        else:
            targets = (fetches,)
    return dependency_of_targets(targets, op)

Check that op is in the subgraph induced by the dependencies of fetches.
    fetches may have more general structure.

Args:
        fetches: An argument to `sess.run`. Nested structure will affect performance.
        op (tf.Operation or tf.Tensor):

Returns:
        bool: True if any of `fetches` depend on `op`.


def plot(self, num_pts, color=None, alpha=None, ax=None):
    if (self._dimension != 2):
        raise NotImplementedError('2D is the only supported dimension', 'Current dimension', self._dimension)
    s_vals = np.linspace(0.0, 1.0, num_pts)
    points = self.evaluate_multi(s_vals)
    if (ax is None):
        ax = _plot_helpers.new_axis()
    ax.plot(points[(0, :)], points[(1, :)], color=color, alpha=alpha)
    return ax

Plot the current curve.

Args:
        num_pts (int): Number of points to plot.
        color (Optional[Tuple[float, float, float]]): Color as RGB profile.
        alpha (Optional[float]): The alpha channel for the color.
        ax (Optional[matplotlib.artist.Artist]): matplotlib axis object
            to add plot to.

Returns:
        matplotlib.artist.Artist: The axis containing the plot. This
        may be a newly created axis.

Raises:
        NotImplementedError: If the curve's dimension is not ``2``.


def unlock(self, passphrase, encrypted_seed=None):
    wallet = self.resource
    if (not encrypted_seed):
        encrypted_seed = wallet.primary_private_seed
    try:
        if encrypted_seed['nonce']:
            primary_seed = NaclPassphraseBox.decrypt(passphrase, encrypted_seed)
        else:
            primary_seed = PassphraseBox.decrypt(passphrase, encrypted_seed)
    except:
        raise InvalidPassphraseError()
    self.multi_wallet = MultiWallet(private_seeds={'primary': primary_seed}, public={'cosigner': wallet.cosigner_public_seed, 'backup': wallet.backup_public_seed})
    return self

Unlock the Wallet by decrypting the primary_private_seed with the
    supplied passphrase. Once unlocked, the private seed is accessible in
    memory and calls to `account.pay` will succeed. This is a necessary step
    for creating transactions.

Args:
        passphrase (str): The passphrase the User used to encrypt this wallet.
        encrypted_seed (dict): A dictionary of the form
        {'ciphertext': longhexvalue,
        'iterations': integer of pbkdf2 derivations,
        'nonce': 24-byte hex value
        'salt': 16-byte hex value}
        this dict represents an private seed (not a master key) encrypted
        with the `passphrase` using pbkdf2. You can obtain this value with
        wallet.generate. If this value is supplied, it overwrites (locally
        only) the encrypted primary_private_seed value, allowing you to load
        in a primary key that you didn't store with Gem. Note that the key
        MUST match the pubkey that this wallet was created with.

Returns:
        self


def wait_for_job(self, job, poll=5):
    desc = _wait_until_training_done((lambda last_desc: _train_done(self.sagemaker_client, job, last_desc)), None, poll)
    self._check_job_status(job, desc, 'TrainingJobStatus')
    return desc

Wait for an Amazon SageMaker training job to complete.

Args:
        job (str): Name of the training job to wait for.
        poll (int): Polling interval in seconds (default: 5).

Returns:
        (dict): Return value from the ``DescribeTrainingJob`` API.

Raises:
        ValueError: If the training job fails.


def update(self, *args, **kwargs):
    for next_dict in chain(args, (kwargs,)):
        for (k, v) in next_dict.items():
            self[k] = v

Equivalent to the python dict update method.

    Update the dictionary with the key/value pairs from other, overwriting
    existing keys.

Args:
        other (dict): The source of key value pairs to add to headers
    Keyword Args:
        All keyword arguments are stored in header directly

Returns:
        None


def get_structural_variant(self, variant):
    query = {'chrom': variant['chrom'], 'end_chrom': variant['end_chrom'], 'sv_type': variant['sv_type'], '$and': [{'pos_left': {'$lte': variant['pos']}}, {'pos_right': {'$gte': variant['pos']}}]}
    res = self.db.structural_variant.find(query).sort('pos_left', 1)
    match = None
    distance = None
    closest_hit = None
    for hit in res:
        if (hit['end_left'] > variant['end']):
            continue
        if (hit['end_right'] < variant['end']):
            continue
        distance = (abs((variant['pos'] - ((hit['pos_left'] + hit['pos_right']) / 2))) + abs((variant['end'] - ((hit['end_left'] + hit['end_right']) / 2))))
        if (closest_hit is None):
            match = hit
            closest_hit = distance
            continue
        if (distance < closest_hit):
            match = hit
            closest_hit = distance
    return match

Check if there are any overlapping sv clusters

    Search the sv variants with chrom start end_chrom end and sv_type

Args:
        variant (dict): A variant dictionary

Returns:
        variant (dict): A variant dictionary