def get_space_group_info(self, symprec=0.01, angle_tolerance=5.0):
    from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
    a = SpacegroupAnalyzer(self, symprec=symprec, angle_tolerance=angle_tolerance)
    return (a.get_space_group_symbol(), a.get_space_group_number())

Convenience method to quickly get the spacegroup of a structure.

Args:
        symprec (float): Same definition as in SpacegroupAnalyzer.
            Defaults to 1e-2.
        angle_tolerance (float): Same definition as in SpacegroupAnalyzer.
            Defaults to 5 degrees.

Returns:
        spacegroup_symbol, international_number


def _ReadPaddingDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
    if (not is_member):
        error_message = 'data type only supported as member'
        raise errors.DefinitionReaderError(definition_name, error_message)
    definition_object = self._ReadDataTypeDefinition(definitions_registry, definition_values, data_types.PaddingDefinition, definition_name, self._SUPPORTED_DEFINITION_VALUES_PADDING)
    alignment_size = definition_values.get('alignment_size', None)
    if (not alignment_size):
        error_message = 'missing alignment_size'
        raise errors.DefinitionReaderError(definition_name, error_message)
    try:
        int(alignment_size)
    except ValueError:
        error_message = 'unuspported alignment size attribute: {0!s}'.format(alignment_size)
        raise errors.DefinitionReaderError(definition_name, error_message)
    if (alignment_size not in (2, 4, 8, 16)):
        error_message = 'unuspported alignment size value: {0!s}'.format(alignment_size)
        raise errors.DefinitionReaderError(definition_name, error_message)
    definition_object.alignment_size = alignment_size
    return definition_object

Reads a padding data type definition.

Args:
        definitions_registry (DataTypeDefinitionsRegistry): data type definitions
        registry.
        definition_values (dict[str, object]): definition values.
        definition_name (str): name of the definition.
        is_member (Optional[bool]): True if the data type definition is a member
        data type definition.

Returns:
        PaddingtDefinition: padding definition.

Raises:
        DefinitionReaderError: if the definitions values are missing or if
        the format is incorrect.


def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP:
    return Bsp(x, y, w, h)

Create a new BSP instance with the given rectangle.

Args:
        x (int): Rectangle left coordinate.
        y (int): Rectangle top coordinate.
        w (int): Rectangle width.
        h (int): Rectangle height.

Returns:
        BSP: A new BSP instance.

    .. deprecated:: 2.0
        Call the :any:`BSP` class instead.


def get_coordination_sphere(self, index_of_atom, n_sphere=1, give_only_index=False, only_surface=True, exclude=None, use_lookup=None):
    if (use_lookup is None):
        use_lookup = settings['defaults']['use_lookup']
    exclude = (set() if (exclude is None) else exclude)
    bond_dict = self.get_bonds(use_lookup=use_lookup)
    i = index_of_atom
    if (n_sphere != 0):
        visited = (set([i]) | exclude)
        try:
            tmp_bond_dict = {j: (bond_dict[j] - visited) for j in bond_dict[i]}
        except KeyError:
            tmp_bond_dict = {}
        n = 0
        while (tmp_bond_dict and ((n + 1) < n_sphere)):
            new_tmp_bond_dict = {}
            for i in tmp_bond_dict:
                if (i in visited):
                    continue
                visited.add(i)
                for j in tmp_bond_dict[i]:
                    new_tmp_bond_dict[j] = (bond_dict[j] - visited)
            tmp_bond_dict = new_tmp_bond_dict
            n += 1
        if only_surface:
            index_out = set(tmp_bond_dict.keys())
        else:
            index_out = (visited | set(tmp_bond_dict.keys()))
    else:
        index_out = {i}
    if give_only_index:
        return (index_out - exclude)
    else:
        return self.loc[(index_out - exclude)]

Return a Cartesian of atoms in the n-th coordination sphere.

    Connected means that a path along covalent bonds exists.

Args:
        index_of_atom (int):
        give_only_index (bool): If ``True`` a set of indices is
            returned. Otherwise a new Cartesian instance.
        n_sphere (int): Determines the number of the coordination sphere.
        only_surface (bool): Return only the surface of the coordination
            sphere.
        exclude (set): A set of indices that should be ignored
            for the path finding.
        use_lookup (bool): Use a lookup variable for
            :meth:`~chemcoord.Cartesian.get_bonds`. The default is
            specified in ``settings['defaults']['use_lookup']``

Returns:
        A set of indices or a new Cartesian instance.


def _project_THn(self, hist: Hist) -> Any:
    projection_axes = [axis.axis_type.value for axis in self.projection_axes]
    if (len(projection_axes) == 2):
        projection_axes.reverse()
    args = (projection_axes + ['E'])
    logger.debug(f'hist: {hist.GetName()} args: {args}')
    if (len(projection_axes) > 3):
        projected_hist = hist.ProjectionND(*args)
    else:
        projected_hist = hist.Projection(*args)
    return projected_hist

Perform the actual THn -> THn or TH1 projection.

    This projection could be to 1D, 2D, 3D, or ND.

Args:
        hist (ROOT.THnBase): Histogram from which the projections should be performed.

Returns:
        ROOT.THnBase or ROOT.TH1: The projected histogram.


def set_description(self, name, action, seqno, value=None, default=False, disable=False):
    commands = [('route-map %s %s %s' % (name, action, seqno))]
    if (value is not None):
        commands.append(self.command_builder('description', disable=True))
    commands.append(self.command_builder('description', value=value, default=default, disable=disable))
    return self.configure(commands)

Configures the routemap description

Args:
        name (string): The full name of the routemap.
        action (string): The action to take for this routemap clause.
        seqno (integer): The sequence number for the routemap clause.
        value (string): The value to configure for the routemap description
        default (bool): Specifies to default the routemap description value
        disable (bool): Specifies to negate the routemap description

Returns:
        True if the operation succeeds otherwise False is returned


def xor_gate(variables, vartype=dimod.BINARY, name='XOR'):
    variables = tuple(variables)
    if (vartype is dimod.BINARY):
        configs = frozenset([(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)])

        def func(in1, in2, out):
            return ((in1 != in2) == out)
    else:
        configs = frozenset([((- 1), (- 1), (- 1)), ((- 1), (+ 1), (+ 1)), ((+ 1), (- 1), (+ 1)), ((+ 1), (+ 1), (- 1))])

        def func(in1, in2, out):
            return (((in1 > 0) != (in2 > 0)) == (out > 0))
    return Constraint(func, configs, variables, vartype=vartype, name=name)

XOR gate.

Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='XOR'): Name for the constraint.

Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an XOR gate.

Example:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.xor_gate(['x', 'y', 'z'], name='XOR1'))
        >>> csp.check({'x': 1, 'y': 1, 'z': 1})
        False


def step(self, action):
    if self.done:
        raise ValueError('cannot step in a done environment! call `reset`')
    self.controllers[0][:] = action
    _LIB.Step(self._env)
    reward = self._get_reward()
    self.done = self._get_done()
    info = self._get_info()
    self._did_step(self.done)
    if (reward < self.reward_range[0]):
        reward = self.reward_range[0]
    elif (reward > self.reward_range[1]):
        reward = self.reward_range[1]
    return (self.screen, reward, self.done, info)

Run one frame of the NES and return the relevant observation data.

Args:
        action (byte): the bitmap determining which buttons to press

Returns:
        a tuple of:
        - state (np.ndarray): next frame as a result of the given action
        - reward (float) : amount of reward returned after given action
        - done (boolean): whether the episode has ended
        - info (dict): contains auxiliary diagnostic information


def hgnc_genes(self, hgnc_symbol, build='37', search=False):
    LOG.debug(('Fetching genes with symbol %s' % hgnc_symbol))
    if search:
        full_query = self.hgnc_collection.find({'$or': [{'aliases': hgnc_symbol}, {'hgnc_id': (int(hgnc_symbol) if hgnc_symbol.isdigit() else None)}], 'build': build})
        if (full_query.count() != 0):
            return full_query
        return self.hgnc_collection.find({'aliases': {'$regex': hgnc_symbol, '$options': 'i'}, 'build': build})
    return self.hgnc_collection.find({'build': build, 'aliases': hgnc_symbol})

Fetch all hgnc genes that match a hgnc symbol

    Check both hgnc_symbol and aliases

Args:
        hgnc_symbol(str)
        build(str): The build in which to search
        search(bool): if partial searching should be used

Returns:
        result()


def get_user_info(self, token):
    url = self.get_user_info_url()
    try:
        headers = {'Authorization': 'Bearer {}'.format(token)}
        response = requests.get(url, headers=headers)
    except requests.RequestException:
        logger.exception('Failed to retrieve user info due to a request exception.')
        raise UserInfoRetrievalFailed
    if (response.status_code == 200):
        return self.process_user_info_response(response.json())
    else:
        msg = 'Failed to retrieve user info. Server [{server}] responded with status [{status}].'.format(server=url, status=response.status_code)
        raise UserInfoRetrievalFailed(msg)

Retrieves the user info from the OAuth provider.

Args:
        token (str): OAuth2 access token.

Returns:
        dict

Raises:
        UserInfoRetrievalFailed: Retrieval of user info from the remote server failed.


def get_actions(self, issues):
    actions = []
    try:
        for issue in issues:
            action_item = self.determine_action(issue)
            if (action_item['action'] != AuditActions.IGNORE):
                action_item['owners'] = self.get_contacts(issue)
                actions.append(action_item)
    finally:
        db.session.rollback()
    return actions

Returns a list of actions to executed

Args:
        issues (`list` of :obj:`RequiredTagsIssue`): List of issues

Returns:
        `list` of `dict`


def get_weights_of_nn_sites(self, structure, n):
    return [e['weight'] for e in self.get_nn_info(structure, n)]

Get weight associated with each near neighbor of site with
    index n in structure.

Args:
        structure (Structure): input structure.
        n (integer): index of site for which to determine the weights.

Returns:
        weights (list of floats): near-neighbor weights.


def _import_templates(force=False):
    tmplpath = os.path.join(resource_filename('cloud_inquisitor', 'data'), 'templates')
    disk_templates = {f: os.path.join(root, f) for (root, directory, files) in os.walk(tmplpath) for f in files}
    db_templates = {tmpl.template_name: tmpl for tmpl in db.Template.find()}
    for (name, template_file) in disk_templates.items():
        with open(template_file, 'r') as f:
            body = f.read()
        disk_hash = get_hash(body)
        if (name not in db_templates):
            template = Template()
            template.template_name = name
            template.template = body
            db.session.add(template)
            auditlog(event='template.import', actor='init', data={'template_name': name, 'template': body})
            logger.info('Imported template {}'.format(name))
        else:
            template = db_templates[name]
            db_hash = get_hash(template.template)
            if (db_hash != disk_hash):
                if (force or (not db_templates[name].is_modified)):
                    template.template = body
                    db.session.add(template)
                    auditlog(event='template.update', actor='init', data={'template_name': name, 'template_diff': diff(template.template, body)})
                    logger.info('Updated template {}'.format(name))
                else:
                    logger.warning('Updated template available for {}. Will not import as it would overwrite user edited content and force is not enabled'.format(name))

Import templates from disk into database

    Reads all templates from disk and adds them to the database. By default, any template that has been modified by
    the user will not be updated. This can however be changed by setting `force` to `True`, which causes all templates
    to be imported regardless of status

Args:
        force (`bool`): Force overwrite any templates with local changes made. Default: `False`

Returns:
        `None`


def lsfiles(root='.', **kwargs):
    paths = ls(root=root, **kwargs)
    if isfile(root):
        return paths
    return [_path for _path in paths if isfile(path(root, _path))]

Return only files from a directory listing.

Args:
        root (str): Path to directory. Can be relative or absolute.
        **kwargs: Any additional arguments to be passed to ls().

Returns:
        list of str: A list of file paths.

Raises:
        OSError: If root directory does not exist.


def create_view(self, state_root_hash=None):
    if (state_root_hash is None):
        state_root_hash = INIT_ROOT_KEY
    merkle_db = MerkleDatabase(self._database, merkle_root=state_root_hash)
    return StateView(merkle_db)

Creates a StateView for the given state root hash.

Args:
        state_root_hash (str): The state root hash of the state view
            to return.  If None, returns the state view for the

Returns:
        StateView: state view locked to the given root hash.


def label_sequential_regions(inlist):
    import more_itertools as mit
    df = pd.DataFrame(inlist).set_index(0)
    labeled = {}
    for label in df[1].unique():
        iterable = df[(df[1] == label)].index.tolist()
        labeled.update({'{}{}'.format(label, (i + 1)): items for (i, items) in enumerate([list(group) for group in mit.consecutive_groups(iterable)])})
    return labeled

Input a list of labeled tuples and return a dictionary of sequentially labeled regions.

Args:
        inlist (list): A list of tuples with the first number representing the index and the second the index label.

Returns:
        dict: Dictionary of labeled regions.

Example:
        >>> label_sequential_regions([(1, 'O'), (2, 'O'), (3, 'O'), (4, 'M'), (5, 'M'), (6, 'I'), (7, 'M'), (8, 'O'), (9, 'O')])
        {'O1': [1, 2, 3], 'M1': [4, 5], 'I1': [6], 'M2': [7], 'O2': [8, 9]}


def update_caseid(self, case_obj, family_id):
    new_case = deepcopy(case_obj)
    new_case['_id'] = family_id
    for case_variants in ['suspects', 'causatives']:
        new_variantids = []
        for variant_id in case_obj.get(case_variants, []):
            case_variant = self.variant(variant_id)
            if (not case_variant):
                continue
            new_variantid = get_variantid(case_variant, family_id)
            new_variantids.append(new_variantid)
        new_case[case_variants] = new_variantids
    for acmg_obj in self.acmg_collection.find({'case_id': case_obj['_id']}):
        LOG.info('update ACMG classification: %s', acmg_obj['classification'])
        acmg_variant = self.variant(acmg_obj['variant_specific'])
        new_specific_id = get_variantid(acmg_variant, family_id)
        self.acmg_collection.find_one_and_update({'_id': acmg_obj['_id']}, {'$set': {'case_id': family_id, 'variant_specific': new_specific_id}})
    institute_obj = self.institute(case_obj['owner'])
    for event_obj in self.events(institute_obj, case=case_obj):
        LOG.info('update event: %s', event_obj['verb'])
        self.event_collection.find_one_and_update({'_id': event_obj['_id']}, {'$set': {'case': family_id}})
    self.case_collection.insert_one(new_case)
    self.case_collection.find_one_and_delete({'_id': case_obj['_id']})
    return new_case

Update case id for a case across the database.

    This function is used when a case is a rerun or updated for another reason.

Args:
        case_obj(dict)
        family_id(str): The new family id

Returns:
        new_case(dict): The updated case object


def delete_nsg(access_token, subscription_id, resource_group, nsg_name):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkSecurityGroups/', nsg_name, '?api-version=', NETWORK_API])
    return do_delete(endpoint, access_token)

Delete network security group.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        resource_group (str): Azure resource group name.
        nsg_name (str): Name of the NSG.

Returns:
        HTTP response.


def create_endpoint(self, endpoint_name, config_name, tags=None, wait=True):
    LOGGER.info('Creating endpoint with name {}'.format(endpoint_name))
    tags = (tags or [])
    self.sagemaker_client.create_endpoint(EndpointName=endpoint_name, EndpointConfigName=config_name, Tags=tags)
    if wait:
        self.wait_for_endpoint(endpoint_name)
    return endpoint_name

Create an Amazon SageMaker ``Endpoint`` according to the endpoint configuration specified in the request.

    Once the ``Endpoint`` is created, client applications can send requests to obtain inferences.
    The endpoint configuration is created using the ``CreateEndpointConfig`` API.

Args:
        endpoint_name (str): Name of the Amazon SageMaker ``Endpoint`` being created.
        config_name (str): Name of the Amazon SageMaker endpoint configuration to deploy.
        wait (bool): Whether to wait for the endpoint deployment to complete before returning (default: True).

Returns:
        str: Name of the Amazon SageMaker ``Endpoint`` created.


def set_iprouting(self, value=None, default=False, disable=False):
    if (value is False):
        disable = True
    cmd = self.command_builder('ip routing', value=value, default=default, disable=disable)
    return self.configure(cmd)

Configures the state of global ip routing

    EosVersion:
        4.13.7M

Args:
        value(bool): True if ip routing should be enabled or False if
            ip routing should be disabled
        default (bool): Controls the use of the default keyword
        disable (bool): Controls the use of the no keyword

Returns:
        bool: True if the commands completed successfully otherwise False


def init(dvc_dir):
    config_file = os.path.join(dvc_dir, Config.CONFIG)
    open(config_file, 'w+').close()
    return Config(dvc_dir)

Initializes dvc config.

Args:
        dvc_dir (str): path to .dvc directory.

Returns:
        dvc.config.Config: config object.


def adjust_saturation(img, saturation_factor):
    if (not _is_pil_image(img)):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
    enhancer = ImageEnhance.Color(img)
    img = enhancer.enhance(saturation_factor)
    return img

Adjust color saturation of an image.

Args:
        img (PIL Image): PIL Image to be adjusted.
        saturation_factor (float):  How much to adjust the saturation. 0 will
            give a black and white image, 1 will give the original image while
            2 will enhance the saturation by a factor of 2.

Returns:
        PIL Image: Saturation adjusted image.


def create(self, data, **kwargs):
    path = self.path[:(- 1)]
    return CreateMixin.create(self, data, path=path, **kwargs)

Creates a new object.

Args:
        data (dict): Parameters to send to the server to create the
                    resource
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabCreateError: If the server cannot perform the request

Returns:
        RESTObject: A new instance of the managed object class build with
            the data sent by the server


def bounding_box_from(points, i, i1, thr):
    pi = points[i]
    pi1 = points[i1]
    min_lat = min(pi.lat, pi1.lat)
    min_lon = min(pi.lon, pi1.lon)
    max_lat = max(pi.lat, pi1.lat)
    max_lon = max(pi.lon, pi1.lon)
    return ((min_lat - thr), (min_lon - thr), (max_lat + thr), (max_lon + thr))

Creates bounding box for a line segment

Args:
        points (:obj:`list` of :obj:`Point`)
        i (int): Line segment start, index in points array
        i1 (int): Line segment end, index in points array

Returns:
        (float, float, float, float): with bounding box min x, min y, max x and max y


def register(self, message, host):
    cuuid = message['cuuid']
    if (len(self.registry) > self.registration_limit):
        logger.warning(('<%s> Registration limit exceeded' % cuuid))
        response = serialize_data({'method': 'BYE REGISTER'}, self.compression, encryption=False)
        return response
    data = {'host': host[0], 'port': host[1], 'time': datetime.now()}
    return_msg = {'method': 'OK REGISTER'}
    if (('encryption' in message) and self.encryption):
        data['encryption'] = PublicKey(message['encryption'][0], message['encryption'][1])
        self.encrypted_hosts[host] = cuuid
        return_msg['encryption'] = [self.encryption.n, self.encryption.e]
    if (cuuid in self.registry):
        for key in data:
            self.registry[cuuid][key] = data[key]
    else:
        self.registry[cuuid] = data
        self.registry[cuuid]['authenticated'] = False
    response = serialize_data(return_msg, self.compression, encryption=False)
    logger.debug(('<%s> Registry entries:' % cuuid))
    for (key, value) in self.registry.items():
        logger.debug(('<%s> %s %s' % (str(cuuid), str(key), pformat(value))))
    return response

This function will register a particular client in the server's
    registry dictionary.

    Any clients that are registered will be able to send and recieve events
    to and from the server.

Args:
        message (dict): The client message from the client who wants to
        register.
        host (tuple): The (address, port) tuple of the client that is
        registering.

Returns:
        A server response with an "OK REGISTER" if the registration was
        successful or a "BYE REGISTER" if unsuccessful.


def load(file, check_version=True):
    s = file.read()
    return loads(s, check_version)

Load VOEvent from file object.

    A simple wrapper to read a file before passing the contents to
    :py:func:`.loads`. Use with an open file object, e.g.::

        with open('/path/to/voevent.xml', 'rb') as f:
            v = vp.load(f)

Args:
        file (io.IOBase): An open file object (binary mode preferred), see also
            http://lxml.de/FAQ.html :
            "Can lxml parse from file objects opened in unicode/text mode?"

        check_version (bool): (Default=True) Checks that the VOEvent is of a
            supported schema version - currently only v2.0 is supported.

Returns:
        :py:class:`Voevent`: Root-node of the  etree.


def all(self, predicate=bool):
    if self.closed():
        raise ValueError('Attempt to call all() on a closed Queryable.')
    if (not is_callable(predicate)):
        raise TypeError('all() parameter predicate={0} is not callable'.format(repr(predicate)))
    return all(self.select(predicate))

Determine if all elements in the source sequence satisfy a condition.

    All of the source sequence will be consumed.

    Note: This method uses immediate execution.

Args:
        predicate (callable): An optional single argument function used to
            test each elements. If omitted, the bool() function is used
            resulting in the elements being tested directly.

Returns:
        True if all elements in the sequence meet the predicate condition,
        otherwise False.

Raises:
        ValueError: If the Queryable is closed()
        TypeError: If predicate is not callable.


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

Obtain bus arrival info in target stop.

Args:
        stop_number (int): Stop number to query.
        lang (str): Language code (*es* or *en*).

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


def convert_old_publication_info_to_new(publication_infos):
    result = []
    hidden_publication_infos = []
    for publication_info in publication_infos:
        _publication_info = copy.deepcopy(publication_info)
        journal_title = _publication_info.get('journal_title')
        try:
            journal_title = _JOURNALS_RENAMED_OLD_TO_NEW[journal_title]
            _publication_info['journal_title'] = journal_title
            result.append(_publication_info)
            continue
        except KeyError:
            pass
        journal_volume = _publication_info.get('journal_volume')
        if ((journal_title in _JOURNALS_WITH_YEAR_ADDED_TO_VOLUME) and journal_volume and (len(journal_volume) == 4)):
            try:
                was_last_century = (int(journal_volume[:2]) > 50)
            except ValueError:
                pass
            else:
                _publication_info['year'] = int((('19' + journal_volume[:2]) if was_last_century else ('20' + journal_volume[:2])))
                _publication_info['journal_volume'] = journal_volume[2:]
            result.append(_publication_info)
            continue
        if (journal_title and journal_volume and (journal_title.lower() not in JOURNALS_IGNORED_IN_OLD_TO_NEW)):
            volume_starts_with_a_letter = _RE_VOLUME_STARTS_WITH_A_LETTER.match(journal_volume)
            volume_ends_with_a_letter = _RE_VOLUME_ENDS_WITH_A_LETTER.match(journal_volume)
            match = (volume_starts_with_a_letter or volume_ends_with_a_letter)
            if match:
                _publication_info.pop('journal_record', None)
                if (journal_title in _JOURNALS_RENAMED_OLD_TO_NEW.values()):
                    _publication_info['journal_title'] = journal_title
                else:
                    _publication_info['journal_title'] = ''.join([journal_title, ('' if journal_title.endswith('.') else ' '), match.group('letter')])
                _publication_info['journal_volume'] = match.group('volume')
        hidden = _publication_info.pop('hidden', None)
        if hidden:
            hidden_publication_infos.append(_publication_info)
        else:
            result.append(_publication_info)
    for publication_info in hidden_publication_infos:
        if (publication_info not in result):
            publication_info['hidden'] = True
            result.append(publication_info)
    return result

Convert a ``publication_info`` value from the old format to the new.

    On Legacy different series of the same journal were modeled by adding the
    letter part of the name to the journal volume. For example, a paper published
    in Physical Review D contained::

        {
            'publication_info': [
                {
                    'journal_title': 'Phys.Rev.',
                    'journal_volume': 'D43',
                },
            ],
        }

    On Labs we instead represent each series with a different journal record. As
    a consequence, the above example becomes::

        {
            'publication_info': [
                {
                    'journal_title': 'Phys.Rev.D',
                    'journal_volume': '43',
                },
            ],
        }

    This function handles this translation from the old format to the new. Please
    also see the tests for various edge cases that this function also handles.

Args:
        publication_infos: a ``publication_info`` in the old format.

Returns:
        list(dict): a ``publication_info`` in the new format.


def get_users(self, condensed=False):
    user_list = self.slack_client.api_call('users.list')
    if (not user_list.get('ok')):
        return None
    if condensed:
        users = [{'id': item.get('id'), 'name': item.get('name'), 'display_name': item.get('profile').get('display_name')} for item in user_list.get('members')]
        return users
    else:
        return user_list

Grabs all users in the slack team

    This should should only be used for getting list of all users. Do not
    use it for searching users. Use get_user_info instead.

Args:
        condensed (bool): if true triggers list condensing functionality

Returns:
        dict: Dict of users in Slack team.
            See also: https://api.slack.com/methods/users.list


def update(self, roomId, title=None, **request_parameters):
    check_type(roomId, basestring, may_be_none=False)
    check_type(roomId, basestring)
    put_data = dict_from_items_with_values(request_parameters, title=title)
    json_data = self._session.put(((API_ENDPOINT + '/') + roomId), json=put_data)
    return self._object_factory(OBJECT_TYPE, json_data)

Update details for a room, by ID.

Args:
        roomId(basestring): The room ID.
        title(basestring): A user-friendly name for the room.
        **request_parameters: Additional request parameters (provides
            support for parameters that may be added in the future).

Returns:
        Room: A Room object with the updated Webex Teams room details.

Raises:
        TypeError: If the parameter types are incorrect.
        ApiError: If the Webex Teams cloud returns an error.


def _urllib_post(self, url, json='', data='', username='', password='', headers=None, timeout=30):
    if (headers is None):
        headers = {}
    raw_store = json
    raw_request = (json_lib.dumps(json) if json else urlencode(data))
    url_request = Request(url, data=raw_request.encode('utf8'))
    if json:
        url_request.add_header('Content-Type', 'application/json')
    elif (not data):
        raise ValueError('Please provide either a json or a data field.')
    headers['User-Agent'] = self.user_agent
    raw_request = raw_store
    if (username and password):
        if (sys.version_info[0] >= 3):
            basic_authstring = base64.encodebytes(('%s:%s' % (username, password)).encode()).decode().replace('\n', '')
        else:
            basic_authstring = base64.encodestring(('%s:%s' % (username, password))).replace('\n', '')
        url_request.add_header('Authorization', ('Basic %s' % basic_authstring))
    for (key, value) in headers.items():
        url_request.add_header(key, str(value))
    try:
        response = urlopen(url_request, timeout=timeout)
    except HTTPError as e:
        raw_response = e.read()
        return (raw_response, raw_request, e.getcode(), e.headers)
    else:
        raw_response = response.read()
        response.close()
        return (raw_response, raw_request, response.getcode(), dict(response.info()))

This function will POST to the url endpoint using urllib2. returning
    an AdyenResult object on 200 HTTP responce. Either json or data has to
    be provided. If username and password are provided, basic auth will be
    used.

Args:
        url (str):                  url to send the POST
        json (dict, optional):      Dict of the JSON to POST
        data (dict, optional):      Dict, presumed flat structure of
                                    key/value of request to place as
                                    www-form
        username (str, optional):    Username for basic auth. Must be
                                    uncluded as part of password.
        password (str, optional):   Password for basic auth. Must be
                                    included as part of username.
        headers (dict, optional):   Key/Value pairs of headers to include
        timeout (int, optional): Default 30. Timeout for the request.

Returns:
        str:    Raw response received
        str:    Raw request placed
        int:    HTTP status code, eg 200,404,401
        dict:   Key/Value pairs of the headers received.


def new_message_from_header(header):
    message_type = header.message_type
    if (not isinstance(message_type, Type)):
        try:
            if isinstance(message_type, str):
                message_type = Type[message_type]
            elif isinstance(message_type, int):
                message_type = Type(message_type)
        except ValueError:
            raise ValueError
    message = new_message_from_message_type(message_type)
    message.header.xid = header.xid
    message.header.length = header.length
    return message

Given an OF Header, return an empty message of header's message_type.

Args:
        header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header.

Returns:
        Empty OpenFlow message of the same type of message_type attribute from
        the given header.
        The header attribute of the message will be populated.

Raises:
        KytosUndefinedMessageType: Unkown Message_Type.


def wrap_callable(cls, uri, methods, callable_obj):
    if isinstance(callable_obj, HandlerMeta):
        callable_obj.base_endpoint = uri
        callable_obj.is_valid = True
        return callable_obj
    if isinstance(callable_obj, types.FunctionType):
        return cls(uri=uri, methods=methods, callable_obj=callable_obj)
    raise RouteError('Invalid handler type.')

Wraps function-based callable_obj into a `Route` instance, else
    proxies a `bottle_neck.handlers.BaseHandler` subclass instance.

Args:
        uri (str):  The uri relative path.
        methods (tuple): A tuple of valid method strings.
        callable_obj (instance): The callable object.

Returns:
        A route instance.

Raises:
        RouteError for invalid callable object type.


def cut_sphere(self, radius=15.0, origin=None, outside_sliced=True, preserve_bonds=False):
    if (origin is None):
        origin = np.zeros(3)
    elif pd.api.types.is_list_like(origin):
        origin = np.array(origin, dtype='f8')
    else:
        origin = self.loc[(origin, ['x', 'y', 'z'])]
    molecule = self.get_distance_to(origin)
    if outside_sliced:
        molecule = molecule[(molecule['distance'] < radius)]
    else:
        molecule = molecule[(molecule['distance'] > radius)]
    if preserve_bonds:
        molecule = self._preserve_bonds(molecule)
    return molecule

Cut a sphere specified by origin and radius.

Args:
        radius (float):
        origin (list): Please note that you can also pass an
            integer. In this case it is interpreted as the
            index of the atom which is taken as origin.
        outside_sliced (bool): Atoms outside/inside the sphere
            are cut out.
        preserve_bonds (bool): Do not cut covalent bonds.

Returns:
        Cartesian:


def from_string(string):
    lines = string.split('\n')
    toks = lines[0].split()
    lengths = [float(i) for i in toks]
    toks = lines[1].split()
    angles = [float(i) for i in toks[0:3]]
    latt = Lattice.from_lengths_and_angles(lengths, angles)
    sp = []
    coords = []
    for l in lines[4:]:
        m = re.match('\\d+\\s+(\\w+)\\s+([0-9\\-\\.]+)\\s+([0-9\\-\\.]+)\\s+([0-9\\-\\.]+)', l.strip())
        if m:
            sp.append(m.group(1))
            coords.append([float(m.group(i)) for i in range(2, 5)])
    return Cssr(Structure(latt, sp, coords))

Reads a string representation to a Cssr object.

Args:
        string (str): A string representation of a CSSR.

Returns:
        Cssr object.


def build_graph(path, term_depth=1000, skim_depth=10, d_weights=False, **kwargs):
    click.echo('\nTokenizing text...')
    t = Text.from_file(path)
    click.echo(('Extracted %d tokens' % len(t.tokens)))
    m = Matrix()
    click.echo('\nIndexing terms:')
    m.index(t, t.most_frequent_terms(term_depth), **kwargs)
    g = Skimmer()
    click.echo('\nGenerating graph:')
    g.build(t, m, skim_depth, d_weights)
    return g

Tokenize a text, index a term matrix, and build out a graph.

Args:
        path (str): The file path.
        term_depth (int): Consider the N most frequent terms.
        skim_depth (int): Connect each word to the N closest siblings.
        d_weights (bool): If true, give "close" nodes low weights.

Returns:
        Skimmer: The indexed graph.


def destroy_cloudwatch_log_event(app='', env='dev', region=''):
    session = boto3.Session(profile_name=env, region_name=region)
    cloudwatch_client = session.client('logs')
    cloudwatch_client.delete_subscription_filter(logGroupName='/aws/lambda/awslimitchecker', filterName=app)
    return True

Destroy Cloudwatch log event.

Args:
        app (str): Spinnaker Application name.
        env (str): Deployment environment.
        region (str): AWS region.

Returns:
        bool: True upon successful completion.


def get_col_info(table_name, col_name, meta_file):
    with open(meta_file, 'r') as f:
        meta = json.load(f)
    (data_table, table) = load_data_table(table_name, meta_file, meta)
    for field in table['fields']:
        if (field['name'] == col_name):
            col_meta = field
    col = data_table[col_name]
    return (col, col_meta)

Return the content and metadata of a fiven column.

Args:
        table_name(str): Name of the table.
        col_name(str): Name of the column.
        meta_file(str): Path to the meta.json file.

Returns:
        tuple(pandas.Series, dict)


def rpc(self, address, rpc_id, *args, **kwargs):
    if isinstance(rpc_id, RPCDeclaration):
        arg_format = rpc_id.arg_format
        resp_format = rpc_id.resp_format
        rpc_id = rpc_id.rpc_id
    else:
        arg_format = kwargs.get('arg_format', None)
        resp_format = kwargs.get('resp_format', None)
    arg_payload = b''
    if (arg_format is not None):
        arg_payload = pack_rpc_payload(arg_format, args)
    self._logger.debug('Sending rpc to %d:%04X, payload=%s', address, rpc_id, args)
    resp_payload = self.call_rpc(address, rpc_id, arg_payload)
    if (resp_format is None):
        return []
    resp = unpack_rpc_payload(resp_format, resp_payload)
    return resp

Immediately dispatch an RPC inside this EmulatedDevice.

    This function is meant to be used for testing purposes as well as by
    tiles inside a complex EmulatedDevice subclass that need to
    communicate with each other.  It should only be called from the main
    virtual device thread where start() was called from.

    **Background workers may not call this method since it may cause them to deadlock.**

Args:
        address (int): The address of the tile that has the RPC.
        rpc_id (int): The 16-bit id of the rpc we want to call
        *args: Any required arguments for the RPC as python objects.
        **kwargs: Only two keyword arguments are supported:
            - arg_format: A format specifier for the argument list
            - result_format: A format specifier for the result

Returns:
        list: A list of the decoded response members from the RPC.


def ungroup_unique(unique_items, groupxs, maxval=None):
    if (maxval is None):
        maxpergroup = [(max(xs) if len(xs) else 0) for xs in groupxs]
        maxval = (max(maxpergroup) if len(maxpergroup) else 0)
    ungrouped_items = ([None] * (maxval + 1))
    for (item, xs) in zip(unique_items, groupxs):
        for x in xs:
            ungrouped_items[x] = item
    return ungrouped_items

Ungroups unique items to correspond to original non-unique list

Args:
        unique_items (list):
        groupxs (list):
        maxval (int): (default = None)

Returns:
        list: ungrouped_items

    CommandLine:
        python -m utool.util_alg ungroup_unique

Example:
        >>> # ENABLE_DOCTEST
        >>> from utool.util_alg import *  # NOQA
        >>> import utool as ut
        >>> unique_items = [1, 2, 3]
        >>> groupxs = [[0, 2], [1, 3], [4, 5]]
        >>> maxval = None
        >>> ungrouped_items = ungroup_unique(unique_items, groupxs, maxval)
        >>> result = ('ungrouped_items = %s' % (ut.repr2(ungrouped_items),))
        >>> print(result)
        ungrouped_items = [1, 2, 1, 2, 3, 3]


def get_realtime_urls(admin_view_func=(lambda x: x)):
    from .widgets import REALTIME_WIDGETS
    return [url(w.url_regex, admin_view_func(w.as_view()), name=w.url_name) for w in REALTIME_WIDGETS]

Get the URL for real-time widgets.

Args:
        admin_view_func (callable): an admin_view method from an AdminSite
            instance. By default: identity.

Returns:
        list: the list of the real-time URLs as django's ``url()``.


def list_folder(cls, session, mailbox, folder):
    return cls(('/mailboxes/%d/folders/%s/conversations.json' % (mailbox.id, folder.id)), session=session)

Return conversations in a specific folder of a mailbox.

Args:
        session (requests.sessions.Session): Authenticated session.
        mailbox (helpscout.models.Mailbox): Mailbox that folder is in.
        folder (helpscout.models.Folder): Folder to list.

Returns:
        RequestPaginator(output_type=helpscout.models.Conversation):
            Conversations iterator.


def _get_samples_shared_with(self, other, index=None):
    if isinstance(other, (pd.DataFrame, Projection)):
        df_other = (other.coords if isinstance(other, Projection) else other)
        if (len(set(df_other.index)) != len(df_other.index)):
            raise ValueError('other index has duplicates')
        if (len(set(self.coords.index)) != len(self.coords.index)):
            raise ValueError('This projection index has duplicates')
        if index:
            uniq_idx = set(index)
            if (len(uniq_idx) != len(index)):
                raise ValueError('index has has duplicates')
            if (uniq_idx - set(df_other.index)):
                raise ValueError('index has samples not in other')
            if (uniq_idx - set(self.coords.index)):
                raise ValueError('index has samples not in this projection')
        else:
            uniq_idx = (set(df_other.index) & set(self.coords.index))
            if (not len(uniq_idx)):
                raise ValueError('No samples shared between other and this projection')
        idx = list(uniq_idx)
        return (self.coords.loc[(idx, :)].values, df_other.loc[(idx, :)].values)
    else:
        other = np.array(other)
        if (other.shape != self.coords.shape):
            raise ValueError('array-like must have the same shape as self.coords')
        return (self.coords.values, other)

Find samples shared with another dataset.

Args:
        other
            (:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`
                or `array-like`):
            The other dataset. If `other` is an instance of
            :py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`,
            then `other` must have indexes in common with this projection.
            If `array-like`, then other must have same dimensions as
            `self.coords`.
        index (`list-like` or `None`): If `other` is an instance of
            :py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`
            then only return samples in index.

Returns:
        `tuple`: containing:

            - this (`numpy.array`) Shape [`x`, `n`].
            - other (`numpy.array`) Shape [`x`, `n`].


def has_all_nonzero_neurite_radii(neuron, threshold=0.0):
    bad_ids = []
    seen_ids = set()
    for s in _nf.iter_sections(neuron):
        for (i, p) in enumerate(s.points):
            info = (s.id, i)
            if ((p[COLS.R] <= threshold) and (info not in seen_ids)):
                seen_ids.add(info)
                bad_ids.append(info)
    return CheckResult((len(bad_ids) == 0), bad_ids)

Check presence of neurite points with radius not above threshold

Args:
        neuron(Neuron): The neuron object to test
        threshold: value above which a radius is considered to be non-zero

Returns:
        CheckResult with result including list of (section ID, point ID) pairs
        of zero-radius points


def read_csv(filename):
    field_names = ('latitude', 'longitude', 'name')
    data = utils.prepare_csv_read(filename, field_names, skipinitialspace=True)
    locations = {}
    args = []
    for (index, row) in enumerate(data, 1):
        name = ('%02i:%s' % (index, row['name']))
        locations[name] = (row['latitude'], row['longitude'])
        args.append(name)
    return (locations, args)

Pull locations from a user's CSV file.

    Read gpsbabel_'s CSV output format

    .. _gpsbabel: http://www.gpsbabel.org/

Args:
        filename (str): CSV file to parse

Returns:
        tuple of dict and list: List of locations as ``str`` objects


def search(self, term):
    return self._result(self._get(self._url('/images/search'), params={'term': term}), True)

Search for images on Docker Hub. Similar to the ``docker search``
    command.

Args:
        term (str): A term to search for.

Returns:
        (list of dicts): The response of the search.

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def valueReadPreprocessor(valueString, replaceParamsFile=None):
    if (type(valueString) is bool):
        log.warning('Only numerical variable types can be handled by the valueReadPreprocessor function.')
        return valueString
    processedValue = valueString
    if ((replaceParamsFile is not None) and (valueString is not None)):
        if (('[' in valueString) or (']' in valueString)):
            processedValue = '{0}'.format(REPLACE_NO_VALUE)
            for targetParam in replaceParamsFile.targetParameters:
                if (targetParam.targetVariable == valueString):
                    processedValue = '{0}'.format(((- 1) * targetParam.id))
                    break
    return processedValue

Apply global pre-processing to values during reading throughout the project.

Args:
        valueString (str): String representing the value to be preprocessed.
        replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if
            replacement variables are included in the project.

Returns:
        str: Processed value as a string


def build_command(self, action, args=None):
    arguments = self.wrap_arguments(args)
    body = self.soap_body_template.format(arguments=arguments, action=action, service_type=self.service_type, version=self.version)
    soap_action_template = 'urn:schemas-upnp-org:service:{service_type}:{version}#{action}'
    soap_action = soap_action_template.format(service_type=self.service_type, version=self.version, action=action)
    headers = {'Content-Type': 'text/xml; charset="utf-8"', 'SOAPACTION': soap_action}
    return (headers, body)

Build a SOAP request.

Args:
        action (str): the name of an action (a string as specified in the
            service description XML file) to be sent.
        args (list, optional): Relevant arguments as a list of (name,
            value) tuples.

Returns:
        tuple: a tuple containing the POST headers (as a dict) and a
            string containing the relevant SOAP body. Does not set
            content-length, or host headers, which are completed upon
            sending.


def conv_elems_1d(x, factor, out_depth=None):
    out_depth = (out_depth or x.get_shape().as_list()[(- 1)])
    x = tf.expand_dims(x, 1)
    x = layers().Conv2D(filters=out_depth, kernel_size=(1, factor), strides=(1, factor), padding='valid', data_format='channels_last')(x)
    x = tf.squeeze(x, 1)
    return x

Decrease the length and change the dimensionality.

    Merge/restore/compress factors positions of dim depth of the input into
    a single position of dim out_depth.
    This is basically just a strided convolution without overlap
    between each strides. The original length has to be divided by factor.

Args:
        x (tf.Tensor): shape [batch_size, length, depth]
        factor (int): Length compression factor.
        out_depth (int): Output depth

Returns:
        tf.Tensor: shape [batch_size, length//factor, out_depth]


def warning_handler(self, handler):
    if (not self.opened()):
        handler = (handler or util.noop)
        self._warning_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
        self._dll.JLINKARM_SetWarnOutHandler(self._warning_handler)

Setter for the warning handler function.

    If the DLL is open, this function is a no-op, so it should be called
    prior to calling ``open()``.

Args:
        self (JLink): the ``JLink`` instance
        handler (function): function to call on warning messages

Returns:
        ``None``


def _ParseItem(self, parser_mediator, olecf_item):
    result = False
    event_data = OLECFItemEventData()
    event_data.name = olecf_item.name
    event_data.offset = 0
    event_data.size = olecf_item.size
    (creation_time, modification_time) = self._GetTimestamps(olecf_item)
    if creation_time:
        date_time = dfdatetime_filetime.Filetime(timestamp=creation_time)
        event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_CREATION)
        parser_mediator.ProduceEventWithEventData(event, event_data)
        result = True
    if modification_time:
        date_time = dfdatetime_filetime.Filetime(timestamp=modification_time)
        event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_MODIFICATION)
        parser_mediator.ProduceEventWithEventData(event, event_data)
        result = True
    for sub_item in olecf_item.sub_items:
        if self._ParseItem(parser_mediator, sub_item):
            result = True
    return result

Parses an OLECF item.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        olecf_item (pyolecf.item): OLECF item.

Returns:
        bool: True if an event was produced.


def get_and_check_project(valid_vcs_rules, source_url):
    project_path = match_url_regex(valid_vcs_rules, source_url, match_url_path_callback)
    if (project_path is None):
        raise ValueError('Unknown repo for source url {}!'.format(source_url))
    project = project_path.split('/')[(- 1)]
    return project

Given vcs rules and a source_url, return the project.

    The project is in the path, but is the repo name.
    `releases/mozilla-beta` is the path; `mozilla-beta` is the project.

Args:
        valid_vcs_rules (tuple of frozendicts): the valid vcs rules, per
            ``match_url_regex``.
        source_url (str): the source url to find the project for.

Raises:
        RuntimeError: on failure to find the project.

Returns:
        str: the project.


def parse(self, ping_message):
    try:
        if typepy.is_not_null_string(ping_message.stdout):
            ping_message = ping_message.stdout
    except AttributeError:
        pass
    logger.debug('parsing ping result: {}'.format(ping_message))
    self.__parser = NullPingParser()
    if typepy.is_null_string(ping_message):
        logger.debug('ping_message is empty')
        self.__stats = PingStats()
        return self.__stats
    ping_lines = _to_unicode(ping_message).splitlines()
    parser_class_list = (LinuxPingParser, WindowsPingParser, MacOsPingParser, AlpineLinuxPingParser)
    for parser_class in parser_class_list:
        self.__parser = parser_class()
        try:
            self.__stats = self.__parser.parse(ping_lines)
            return self.__stats
        except ParseError as e:
            if (e.reason != ParseErrorReason.HEADER_NOT_FOUND):
                raise e
        except pp.ParseException:
            pass
    self.__parser = NullPingParser()
    return self.__stats

Parse ping command output.

Args:
        ping_message (str or :py:class:`~pingparsing.PingResult`):
            ``ping`` command output.

Returns:
        :py:class:`~pingparsing.PingStats`: Parsed result.


def create_cells(headers, schema_fields, values=None, row_number=None):
    fillvalue = '_fillvalue'
    is_header_row = (values is None)
    cells = []
    iterator = zip_longest(headers, schema_fields, (values or []), fillvalue=fillvalue)
    for (column_number, (header, field, value)) in enumerate(iterator, start=1):
        if (header == fillvalue):
            header = None
        elif is_header_row:
            value = header
        if (field == fillvalue):
            field = None
        if (value == fillvalue):
            value = None
        elif (value is None):
            value = ''
        cell = create_cell(header, value, field, column_number, row_number)
        cells.append(cell)
    return cells

Create list of cells from headers, fields and values.

Args:
        headers (List[str]): The headers values.
        schema_fields (List[tableschema.field.Field]): The tableschema
            fields.
        values (List[Any], optional): The cells values. If not specified,
            the created cells will have the same values as their
            corresponding headers. This is useful for specifying headers
            cells.
            If the list has any `None` values, as is the case on empty
            cells, the resulting Cell will have an empty string value. If
            the `values` list has a different length than the `headers`,
            the resulting Cell will have value `None`.
        row_number (int, optional): The row number.

Returns:
        List[dict]: List of cells.


def encode_value(value):
    if (value is None):
        return document_pb2.Value(null_value=struct_pb2.NULL_VALUE)
    if isinstance(value, bool):
        return document_pb2.Value(boolean_value=value)
    if isinstance(value, six.integer_types):
        return document_pb2.Value(integer_value=value)
    if isinstance(value, float):
        return document_pb2.Value(double_value=value)
    if isinstance(value, DatetimeWithNanoseconds):
        return document_pb2.Value(timestamp_value=value.timestamp_pb())
    if isinstance(value, datetime.datetime):
        return document_pb2.Value(timestamp_value=_datetime_to_pb_timestamp(value))
    if isinstance(value, six.text_type):
        return document_pb2.Value(string_value=value)
    if isinstance(value, six.binary_type):
        return document_pb2.Value(bytes_value=value)
    document_path = getattr(value, '_document_path', None)
    if (document_path is not None):
        return document_pb2.Value(reference_value=document_path)
    if isinstance(value, GeoPoint):
        return document_pb2.Value(geo_point_value=value.to_protobuf())
    if isinstance(value, list):
        value_list = [encode_value(element) for element in value]
        value_pb = document_pb2.ArrayValue(values=value_list)
        return document_pb2.Value(array_value=value_pb)
    if isinstance(value, dict):
        value_dict = encode_dict(value)
        value_pb = document_pb2.MapValue(fields=value_dict)
        return document_pb2.Value(map_value=value_pb)
    raise TypeError('Cannot convert to a Firestore Value', value, 'Invalid type', type(value))

Converts a native Python value into a Firestore protobuf ``Value``.

Args:
        value (Union[NoneType, bool, int, float, datetime.datetime, \
            str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native
            Python value to convert to a protobuf field.

Returns:
        ~google.cloud.firestore_v1beta1.types.Value: A
        value encoded as a Firestore protobuf.

Raises:
        TypeError: If the ``value`` is not one of the accepted types.


def get_block_iter(self, start_block=None, start_block_num=None, reverse=True):
    start = None
    if start_block_num:
        if (len(start_block_num) < 2):
            raise ValueError('Invalid start block num')
        if (start_block_num[:2] != '0x'):
            raise ValueError('Invalid start block num')
        start = int(start_block_num, 16)
    elif start_block:
        start = start_block.block_num
    return _BlockStoreIter(self.pointer, start, reverse)

Returns an iterator that traverses blocks in block number order.

Args:
        start_block (:obj:`BlockWrapper`): the block from which traversal
            begins
        start_block_num (str): a starting block number, in hex, from where
            traversal begins; only used if no starting_block is provided

        reverse (bool): If True, traverse the blocks in from most recent
            to oldest block. Otherwise, it traverse the blocks in the
            opposite order.

Returns:
        An iterator of block wrappers

Raises:
        ValueError: If start_block or start_block_num do not specify a
            valid block


def export(self, container, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
    res = self._get(self._url('/containers/{0}/export', container), stream=True)
    return self._stream_raw_result(res, chunk_size, False)

Export the contents of a filesystem as a tar archive.

Args:
        container (str): The container to export
        chunk_size (int): The number of bytes returned by each iteration
            of the generator. If ``None``, data will be streamed as it is
            received. Default: 2 MB

Returns:
        (generator): The archived filesystem data stream

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def json_to_entity(tc_data, value_fields, resource_type, resource_type_parent):
    if (not isinstance(tc_data, list)):
        tc_data = [tc_data]
    entity_array = []
    for d in tc_data:
        entity = {'id': d.get('id'), 'webLink': d.get('webLink')}
        values = []
        if ('summary' in d):
            values.append(d.get('summary'))
        else:
            for field in value_fields:
                if (d.get(field) is not None):
                    values.append(d.get(field))
        entity['value'] = ' : '.join(values)
        if (d.get('type') is not None):
            entity['type'] = d.get('type')
        else:
            entity['type'] = resource_type
        if (resource_type_parent in ['Indicator']):
            entity['confidence'] = d.get('confidence')
            entity['rating'] = d.get('rating')
            entity['threatAssessConfidence'] = d.get('threatAssessConfidence')
            entity['threatAssessRating'] = d.get('threatAssessRating')
            entity['dateLastModified'] = d.get('lastModified')
        if (resource_type_parent in ['Indicator', 'Group']):
            if ('owner' in d):
                entity['ownerName'] = d['owner']['name']
            else:
                entity['ownerName'] = d.get('ownerName')
            entity['dateAdded'] = d.get('dateAdded')
        if (resource_type_parent in ['Victim']):
            entity['ownerName'] = d.get('org')
        entity_array.append(entity)
    return entity_array

Convert ThreatConnect JSON response to a TCEntityArray.

    .. Attention:: This method is subject to frequent changes.

Args:
        tc_data (dictionary): Array of data returned from TC API call.
        value_fields (list): Field names that contain the "value" data.
        resource_type (string): The resource type of the tc_data provided.
        resource_type_parent (string): The resource parent type of the tc_data provided.

Returns:
        (list): A list representing a TCEntityArray.


def is_valid_transition(self, source: str, dest: str) -> bool:
    if ((dest not in self._states) or (source not in self._states)):
        raise NotValidState
    elif (dest not in self._transitions[source]):
        raise NotValidTransition
    return True

Checks if a transitions is registered in the FSM

Args:
        source (str): the source state name
        dest (str): the destination state name

Returns:
        bool: wether the transition is valid or not


def version(msg):
    tc = typecode(msg)
    if (tc != 31):
        raise RuntimeError(('%s: Not a status operation message, expecting TC = 31' % msg))
    msgbin = common.hex2bin(msg)
    version = common.bin2int(msgbin[72:75])
    return version

ADS-B Version

Args:
        msg (string): 28 bytes hexadecimal message string, TC = 31

Returns:
        int: version number


def get(self, path, params=None, headers=None):
    response = requests.get(self._url_for(path), params=params, headers=self._headers(headers))
    self._handle_errors(response)
    return response

Perform a GET request, optionally providing query-string params.

Args:
        path (str): A path that gets appended to ``base_url``.
        params (dict, optional): Dictionary of param names to values.

Example:
        api_client.get('/users', params={'active': True})

Returns:
        A requests ``Response`` object.


def in_sorted(values, value):
    index = bisect.bisect_left(values, value)
    if (index >= len(values)):
        return False
    return (values[index] == value)

Checks if a value is in a sorted list.

    Uses the :mod:`bisect` builtin to find the insertion point for
    ``value``.

Args:
        values (List[int]): Integers sorted in ascending order.
        value (int): Value to check if contained in ``values``.

Returns:
        bool: Indicating if the value is contained.


def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5):
    (x, y) = texture
    x = (x.copy() - x_offset)
    y = (y.copy() - y_offset)
    angle = np.radians(rotation)
    x_rot = ((x * np.cos(angle)) + (y * np.sin(angle)))
    y_rot = ((x * (- np.sin(angle))) + (y * np.cos(angle)))
    return ((x_rot + x_offset), (y_rot + y_offset))

Rotates the given texture by a given angle.

Args:
        texture (texture): the texture to rotate
        rotation (float): the angle of rotation in degrees
        x_offset (float): the x component of the center of rotation (optional)
        y_offset (float): the y component of the center of rotation (optional)

Returns:
        texture: A texture.


def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None):
    (qregs, cregs, ops) = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify)
    qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits)
    latex = qcimg.latex()
    if filename:
        with open(filename, 'w') as latex_file:
            latex_file.write(latex)
    return latex

Convert QuantumCircuit to LaTeX string.

Args:
        circuit (QuantumCircuit): input circuit
        scale (float): image scaling
        filename (str): optional filename to write latex
        style (dict or str): dictionary of style or file name of style file
        reverse_bits (bool): When set to True reverse the bit order inside
            registers for the output visualization.
        plot_barriers (bool): Enable/disable drawing barriers in the output
            circuit. Defaults to True.
        justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
                        the circuit should be justified.

Returns:
        str: Latex string appropriate for writing to file.


def _CheckParserCanProcessFileEntry(self, parser, file_entry):
    for filter_object in parser.FILTERS:
        if filter_object.Match(file_entry):
            return True
    return False

Determines if a parser can process a file entry.

Args:
        file_entry (dfvfs.FileEntry): file entry.
        parser (BaseParser): parser.

Returns:
        bool: True if the file entry can be processed by the parser object.


def _GetTimeElementsTuple(self, timestamp):
    (year, month, day_of_month, hours, minutes, seconds) = (int((hexdigit[0] + hexdigit[1]), 16) for hexdigit in zip(timestamp[::2], timestamp[1::2]))
    return ((year + 1970), (month + 1), day_of_month, hours, minutes, seconds)

Retrieves a time elements tuple from the timestamp.

    A Symantec log timestamp consist of six hexadecimal octets, that represent:
        First octet: Number of years since 1970
        Second octet: Month, where January is represented by 0
        Third octet: Day of the month
        Fourth octet: Number of hours
        Fifth octet: Number of minutes
        Sixth octet: Number of seconds

    For example, 200A13080122 represents November 19, 2002, 8:01:34 AM.

Args:
        timestamp (str): hexadecimal encoded date and time values.

Returns:
        tuple: containing:
        year (int): year.
        month (int): month, where 1 represents January.
        day_of_month (int): day of month, where 1 is the first day of the month.
        hours (int): hours.
        minutes (int): minutes.
        seconds (int): seconds.


def make_gradients(dims=DEFAULT_DIMS):
    return np.meshgrid(np.linspace(0.0, 1.0, dims[0]), np.linspace(0.0, 1.0, dims[1]))

Makes a pair of gradients to generate textures from numpy primitives.

Args:
        dims (pair): the dimensions of the surface to create

Returns:
        pair: A pair of surfaces.


def decode(self, codes):
    assert (codes.ndim == 2)
    (N, M) = codes.shape
    assert (M == self.M)
    assert (codes.dtype == self.code_dtype)
    vecs = np.empty((N, (self.Ds * self.M)), dtype=np.float32)
    for m in range(self.M):
        vecs[(:, (m * self.Ds):((m + 1) * self.Ds))] = self.codewords[m][(codes[(:, m)], :)]
    return vecs

Given PQ-codes, reconstruct original D-dimensional vectors
    approximately by fetching the codewords.

Args:
        codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype.
            Each row is a PQ-code

Returns:
        np.ndarray: Reconstructed vectors with shape=(N, D) and dtype=np.float32


def valueWritePreprocessor(valueString, replaceParamsFile=None):
    if (type(valueString) is bool):
        log.warning('Only numerical variable types can be handled by the valueReadPreprocessor function.')
        return valueString
    variableString = valueString
    if (replaceParamsFile is not None):
        if (variableString == REPLACE_NO_VALUE):
            variableString = '[NO_VARIABLE]'
        else:
            try:
                number = int(valueString)
                if (number < 0):
                    parameterID = (number * (- 1))
                    for targetParam in replaceParamsFile.targetParameters:
                        if (targetParam.id == parameterID):
                            variableString = targetParam.targetVariable
                            break
            except:
                pass
    return variableString

Look up variable name in replace param file for the negative id given and return it.

Args:
        valueString (str): String representing the value to be preprocessed.
        replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if
            replacement variables are included in the project.

Returns:
        str: Processed value as a string


def get_report_zip(results):

    def add_subdir(root_path, subdir):
        subdir_path = os.path.join(root_path, subdir)
        for (subdir_root, subdir_dirs, subdir_files) in os.walk(subdir_path):
            for subdir_file in subdir_files:
                subdir_file_path = os.path.join(root_path, subdir, subdir_file)
                if os.path.isfile(subdir_file_path):
                    rel_path = os.path.relpath(subdir_root, subdir_file_path)
                    subdir_arc_name = os.path.join(rel_path, subdir_file)
                    zip_file.write(subdir_file_path, subdir_arc_name)
            for subdir in subdir_dirs:
                add_subdir(subdir_path, subdir)
    storage = BytesIO()
    tmp_dir = tempfile.mkdtemp()
    try:
        save_output(results, tmp_dir)
        with zipfile.ZipFile(storage, 'w', zipfile.ZIP_DEFLATED) as zip_file:
            for (root, dirs, files) in os.walk(tmp_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    if os.path.isfile(file_path):
                        arcname = os.path.join(os.path.relpath(root, tmp_dir), file)
                        zip_file.write(file_path, arcname)
                for directory in dirs:
                    dir_path = os.path.join(root, directory)
                    if os.path.isdir(dir_path):
                        zip_file.write(dir_path, directory)
                        add_subdir(root, directory)
    finally:
        shutil.rmtree(tmp_dir)
    return storage.getvalue()

Creates a zip file of parsed report output

Args:
        results (OrderedDict): The parsed results

Returns:
        bytes: zip file bytes


def islink(self, path=None, header=None):
    if (header is None):
        header = self._head(self.get_client_kwargs(path))
    for key in ('x-oss-object-type', 'type'):
        try:
            return (header.pop(key) == 'Symlink')
        except KeyError:
            continue
    return False

Returns True if object is a symbolic link.

Args:
        path (str): File path or URL.
        header (dict): Object header.

Returns:
        bool: True if object is Symlink.


def getConfig(self, section=None):
    data = {}
    if (section is None):
        for s in self.config.sections():
            if ('/' in s):
                (parent, _s) = s.split('/')
                data[parent][_s] = dict(self.config.items(s))
            else:
                data[s] = dict(self.config.items(s))
    else:
        data = dict(self.config.items(section))
    return data

Returns a dictionary which contains the current config. If a section is setted,
    only will returns the section config

Args:
    section (str): (Optional) Section name.

Returns:
    dict: Representation of current config


def get_intersection(self, range_):
    result = []
    for entry in self.entries:
        (package, value) = entry
        if (value is None):
            continue
        if (package.version not in range_):
            continue
        if isinstance(value, list):
            variants = value
            entry_ = _PackageEntry(package, variants, self.solver)
            result.append(entry_)
            continue
        if self.solver.package_filter:
            rule = self.solver.package_filter.excludes(package)
            if rule:
                if config.debug_package_exclusions:
                    print_debug(("Package '%s' was excluded by rule '%s'" % (package.qualified_name, str(rule))))
                entry[1] = None
                continue
        if self.solver.package_load_callback:
            self.solver.package_load_callback(package)
        variants_ = []
        for var in package.iter_variants():
            variant = PackageVariant(var, self.solver.building)
            variants_.append(variant)
        entry[1] = variants_
        entry_ = _PackageEntry(package, variants_, self.solver)
        result.append(entry_)
    return (result or None)

Get a list of variants that intersect with the given range.

Args:
        range_ (`VersionRange`): Package version range.

Returns:
        List of `_PackageEntry` objects.


def launch_run(self, command, project=None, entity=None, run_id=None):
    query = gql('\n        mutation launchRun(\n            $entity: String\n            $model: String\n            $runId: String\n            $image: String\n            $command: String\n            $patch: String\n            $cwd: String\n            $datasets: [String]\n        ) {\n            launchRun(input: {id: $runId, entityName: $entity, patch: $patch, modelName: $model,\n                image: $image, command: $command, datasets: $datasets, cwd: $cwd}) {\n                podName\n                status\n                runId\n            }\n        }\n        ')
    patch = BytesIO()
    if self.git.dirty:
        self.git.repo.git.execute(['git', 'diff'], output_stream=patch)
        patch.seek(0)
    cwd = '.'
    if self.git.enabled:
        cwd = (cwd + os.getcwd().replace(self.git.repo.working_dir, ''))
    return self.gql(query, variable_values={'entity': (entity or self.settings('entity')), 'model': (project or self.settings('project')), 'command': command, 'runId': run_id, 'patch': patch.read().decode('utf8'), 'cwd': cwd})

Launch a run in the cloud.

Args:
        command (str): The command to run
        program (str): The file to run
        project (str): The project to scope the runs to
        entity (str, optional): The entity to scope this project to.  Defaults to public models
        run_id (str, optional): The run_id to scope to

Returns:
            [{"podName","status"}]


def tokens(self, tokenset='internal'):
    toks = self.get('tokens', {}).get(tokenset)
    if (toks is not None):
        if isinstance(toks, stringtypes):
            toks = YyTokenLattice.from_string(toks)
        elif isinstance(toks, Sequence):
            toks = YyTokenLattice.from_list(toks)
    return toks

Deserialize and return a YyTokenLattice object for the
    initial or internal token set, if provided, from the YY
    format or the JSON-formatted data; otherwise return the
    original string.

Args:
        tokenset (str): return `'initial'` or `'internal'` tokens
            (default: `'internal'`)

Returns:
        :class:`YyTokenLattice`


def _process_rules(self, rules):
    cidr = []
    non_cidr = []
    for rule in rules:
        if ('.' in rule['app']):
            self.log.debug('Custom CIDR rule: %s', rule)
            self._validate_cidr(rule)
            cidr.append(rule)
        else:
            self.log.debug('SG reference rule: %s', rule)
            non_cidr.append(rule)
    self.log.debug('Custom CIDR rules: %s', cidr)
    self.log.debug('SG reference rules: %s', non_cidr)
    return (non_cidr, cidr)

Process rules into cidr and non-cidr lists.

Args:
        rules (list): Allowed Security Group ports and protocols.

Returns:
        (list, list): Security Group reference rules and custom CIDR rules.


def _FormatServiceText(self, service):
    string_segments = [service.name, '\tImage Path    = {0:s}'.format(service.image_path), '\tService Type  = {0:s}'.format(service.HumanReadableType()), '\tStart Type    = {0:s}'.format(service.HumanReadableStartType()), '\tService Dll   = {0:s}'.format(service.service_dll), '\tObject Name   = {0:s}'.format(service.object_name), '\tSources:']
    for source in service.sources:
        string_segments.append('\t\t{0:s}:{1:s}'.format(source[0], source[1]))
    return '\n'.join(string_segments)

Produces a human readable multi-line string representing the service.

Args:
        service (WindowsService):  service to format.

Returns:
        str: human readable representation of a Windows Service.


def open_street_map_geoloc_link(data):
    if isinstance(data, str):
        lat_lon = ip_geoloc(data)
        if (lat_lon is None):
            return ''
        (lat, lon) = lat_lon
    else:
        (lat, lon) = data
    return ('https://www.openstreetmap.org/search?query=%s%%2C%s#map=7/%s/%s' % (lat, lon, lat, lon))

Get a link to open street map pointing on this IP's geolocation.

Args:
        data (str/tuple): IP address or (latitude, longitude).

Returns:
        str: a link to open street map pointing on this IP's geolocation.


def sample(self, nmr_samples, burnin=0, thinning=1):
    if ((not thinning) or (thinning < 1)):
        thinning = 1
    if ((not burnin) or (burnin < 0)):
        burnin = 0
    max_samples_per_batch = max((1000 // thinning), 100)
    with self._logging(nmr_samples, burnin, thinning):
        if (burnin > 0):
            for (batch_start, batch_end) in split_in_batches(burnin, max_samples_per_batch):
                self._sample((batch_end - batch_start), return_output=False)
        if (nmr_samples > 0):
            outputs = []
            for (batch_start, batch_end) in split_in_batches(nmr_samples, max_samples_per_batch):
                outputs.append(self._sample((batch_end - batch_start), thinning=thinning))
            return SimpleSampleOutput(*[np.concatenate([o[ind] for o in outputs], axis=(- 1)) for ind in range(3)])

Take additional samples from the given likelihood and prior, using this sampler.

    This method can be called multiple times in which the sample state is stored in between.

Args:
        nmr_samples (int): the number of samples to return
        burnin (int): the number of samples to discard before returning samples
        thinning (int): how many sample we wait before storing a new one. This will draw extra samples such that
                the total number of samples generated is ``nmr_samples * (thinning)`` and the number of samples
                stored is ``nmr_samples``. If set to one or lower we store every sample after the burn in.

Returns:
        SamplingOutput: the sample output object


def get_excitation_spectrum(self, width=0.1, npoints=2000):
    roots = self.parse_tddft()
    data = roots['singlet']
    en = np.array([d['energy'] for d in data])
    osc = np.array([d['osc_strength'] for d in data])
    epad = (20.0 * width)
    emin = (en[0] - epad)
    emax = (en[(- 1)] + epad)
    de = ((emax - emin) / npoints)
    if (width < (2 * de)):
        width = (2 * de)
    energies = [(emin + (ie * de)) for ie in range(npoints)]
    cutoff = (20.0 * width)
    gamma = (0.5 * width)
    gamma_sqrd = (gamma * gamma)
    de = ((energies[(- 1)] - energies[0]) / (len(energies) - 1))
    prefac = ((gamma / np.pi) * de)
    x = []
    y = []
    for energy in energies:
        xx0 = (energy - en)
        stot = (osc / ((xx0 * xx0) + gamma_sqrd))
        t = np.sum(stot[(np.abs(xx0) <= cutoff)])
        x.append(energy)
        y.append((t * prefac))
    return ExcitationSpectrum(x, y)

Generate an excitation spectra from the singlet roots of TDDFT
    calculations.

Args:
        width (float): Width for Gaussian smearing.
        npoints (int): Number of energy points. More points => smoother
            curve.

Returns:
        (ExcitationSpectrum) which can be plotted using
            pymatgen.vis.plotters.SpectrumPlotter.


def get(self, value):
    config = self.get_block(('vlan %s' % value))
    if (not config):
        return None
    response = dict(vlan_id=value)
    response.update(self._parse_name(config))
    response.update(self._parse_state(config))
    response.update(self._parse_trunk_groups(config))
    return response

Returns the VLAN configuration as a resource dict.

Args:
        vid (string): The vlan identifier to retrieve from the
            running configuration.  Valid values are in the range
            of 1 to 4095

Returns:
        A Python dict object containing the VLAN attributes as
            key/value pairs.


def _parse_symbol(self, sym):
    special = {'Hw': 'H', 'Ow': 'O', 'Wat': 'O', 'wat': 'O', 'OH': '', 'OH2': '', 'NO3': 'N'}
    parsed_sym = None
    m_sp = re.match('|'.join(special.keys()), sym)
    if m_sp:
        parsed_sym = special[m_sp.group()]
    elif Element.is_valid_symbol(sym[:2].title()):
        parsed_sym = sym[:2].title()
    elif Element.is_valid_symbol(sym[0].upper()):
        parsed_sym = sym[0].upper()
    else:
        m = re.match('w?[A-Z][a-z]*', sym)
        if m:
            parsed_sym = m.group()
    if ((parsed_sym is not None) and (m_sp or (not re.match('{}\\d*'.format(parsed_sym), sym)))):
        msg = '{} parsed as {}'.format(sym, parsed_sym)
        warnings.warn(msg)
        self.errors.append(msg)
    return parsed_sym

Parse a string with a symbol to extract a string representing an element.

Args:
        sym (str): A symbol to be parsed.

Returns:
        A string with the parsed symbol. None if no parsing was possible.


def detect_scheme(filename):
    logger = logging.getLogger(__name__)
    logger.info('Detecting partitioning scheme')
    with open(filename, 'rb') as f:
        f.seek(mbr.MBR_SIG_OFFSET)
        data = f.read(mbr.MBR_SIG_SIZE)
        signature = struct.unpack('<H', data)[0]
        if (signature != mbr.MBR_SIGNATURE):
            logger.debug('Unknown partitioning scheme')
            return PartitionScheme.SCHEME_UNKNOWN
        else:
            f.seek(gpt.GPT_HEADER_OFFSET)
            data = f.read(gpt.GPT_SIG_SIZE)
            signature = struct.unpack('<8s', data)[0]
            if (signature != gpt.GPT_SIGNATURE):
                logger.debug('MBR scheme detected')
                return PartitionScheme.SCHEME_MBR
            else:
                logger.debug('GPT scheme detected')
                return PartitionScheme.SCHEME_GPT

Detects partitioning scheme of the source

Args:
        filename (str): path to file or device for detection of \
        partitioning scheme.

Returns:
        SCHEME_MBR, SCHEME_GPT or SCHEME_UNKNOWN

Raises:
        IOError: The file doesn't exist or cannot be opened for reading

    >>> from rawdisk.scheme.common import *
    >>> scheme = detect_scheme('/dev/disk1')
    >>> if scheme == PartitionScheme.SCHEME_MBR:
    >>> <...>


def drp(points, epsilon):
    dmax = 0.0
    index = 0
    for i in range(1, (len(points) - 1)):
        dist = point_line_distance(points[i], points[0], points[(- 1)])
        if (dist > dmax):
            index = i
            dmax = dist
    if (dmax > epsilon):
        return (drp(points[:(index + 1)], epsilon)[:(- 1)] + drp(points[index:], epsilon))
    else:
        return [points[0], points[(- 1)]]

Douglas ramer peucker

    Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm

Args:
        points (:obj:`list` of :obj:`Point`)
        epsilon (float): drp threshold

Returns:
        :obj:`list` of :obj:`Point`


def get_datasets(self, query='*:*', **kwargs):
    return hdx.data.dataset.Dataset.search_in_hdx(query=query, configuration=self.configuration, fq=('organization:%s' % self.data['name']), **kwargs)

Get list of datasets in organization

Args:
        query (str): Restrict datasets returned to this query (in Solr format). Defaults to '*:*'.
        **kwargs: See below
        sort (string): Sorting of the search results. Defaults to 'relevance asc, metadata_modified desc'.
        rows (int): Number of matching rows to return. Defaults to all datasets (sys.maxsize).
        start (int): Offset in the complete result for where the set of returned datasets should begin
        facet (string): Whether to enable faceted results. Default to True.
        facet.mincount (int): Minimum counts for facet fields should be included in the results
        facet.limit (int): Maximum number of values the facet fields return (- = unlimited). Defaults to 50.
        facet.field (List[str]): Fields to facet upon. Default is empty.
        use_default_schema (bool): Use default package schema instead of custom schema. Defaults to False.

Returns:
        List[Dataset]: List of datasets in organization


def find(cls, session, resource_id, include=None):
    url = session._build_url(cls._resource_path(), resource_id)
    params = build_request_include(include, None)
    process = cls._mk_one(session, include=include)
    return session.get(url, CB.json(200, process), params=params)

Retrieve a single resource.

    This should only be called from sub-classes.

Args:
        session(Session): The session to find the resource in

        resource_id: The ``id`` for the resource to look up

    Keyword Args:

        include: Resource classes to include

Returns:
        Resource: An instance of a resource, or throws a
        :class:`NotFoundError` if the resource can not be found.


def _GetDayOfYear(self, year, month, day_of_month):
    if (month not in range(1, 13)):
        raise ValueError('Month value out of bounds.')
    days_per_month = self._GetDaysPerMonth(year, month)
    if ((day_of_month < 1) or (day_of_month > days_per_month)):
        raise ValueError('Day of month value out of bounds.')
    day_of_year = day_of_month
    for past_month in range(1, month):
        day_of_year += self._GetDaysPerMonth(year, past_month)
    return day_of_year

Retrieves the day of the year for a specific day of a month in a year.

Args:
        year (int): year e.g. 1970.
        month (int): month, where 1 represents January.
        day_of_month (int): day of the month, where 1 represents the first day.

Returns:
        int: day of year.

Raises:
        ValueError: if the month or day of month value is out of bounds.


def inspect_task(self, task):
    url = self._url('/tasks/{0}', task)
    return self._result(self._get(url), True)

Retrieve information about a task.

Args:
        task (str): Task ID

Returns:
        (dict): Information about the task.

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def _get_target(self, target):
    depth = (target.count('.') + 1)
    parts = target.split('.', 1)
    for m in self.modules:
        if (parts[0] == m.name):
            if (depth < 3):
                return m
    for p in self.packages:
        if (parts[0] == p.name):
            if (depth == 1):
                return p
            target = p._get_target(parts[1])
            if target:
                return target
            if (depth < 3):
                return p
    return None

Get the Package or Module related to given target.

Args:
        target (str): target to find.

Returns:
        Package/Module: package containing target or corresponding module.


def getsource(classorfunc):
    if _isbuiltin(classorfunc):
        return ''
    try:
        source = inspect.getsource(classorfunc)
    except TypeError:
        source = getsourcefallback(classorfunc)
    declaration = []
    lines = source.splitlines()
    if (PY2 and (not isinstance(source, unicode))):
        encoding = detect_encoding(iter(lines).next)[0]
        sourcelines = (s.decode(encoding) for s in lines)
    else:
        sourcelines = iter(lines)
    found_keyword = False
    for line in sourcelines:
        words = line.split()
        if (not words):
            continue
        if (words[0] in ('def', 'class')):
            found_keyword = True
        if found_keyword:
            cind = line.find(':')
            if (cind > 0):
                declaration.append(line[:(cind + 1)])
                after_decl = line[(cind + 1):].strip()
                break
            else:
                declaration.append(line)
    bodylines = list(sourcelines)
    if (type(classorfunc) == type):
        cls = classorfunc
        base_imports = {}
        for base in cls.__bases__:
            if ((base.__name__ == 'object') and (base.__module__ == 'builtins')):
                continue
            if (base in base_imports):
                continue
            if (base.__module__ == '__main__'):
                continue
            base_imports[base] = ('from %s import %s' % (base.__module__, base.__name__))
        cind = declaration[0].index('class ')
        declstring = (declaration[0][:cind] + ('class %s(%s):%s' % (cls.__name__, ','.join([base.__name__ for base in cls.__bases__]), after_decl)))
        declaration = [impstring for (c, impstring) in base_imports.items() if (c.__module__ != '__builtin__')]
        declaration.append(declstring)
    else:
        declaration[(- 1)] += after_decl
    return '\n'.join((declaration + bodylines))

Return the source code for a class or function.

Note:
        Returned source will not include any decorators for the object.
        This will only return the explicit declaration of the object, not any dependencies

Args:
        classorfunc (type or function): the object to get the source code for

Returns:
        str: text of source code (without any decorators). Note: in python 2, this returns unicode


def get_angle_degrees(self, indices):
    coords = ['x', 'y', 'z']
    if isinstance(indices, pd.DataFrame):
        i_pos = self.loc[(indices.index, coords)].values
        b_pos = self.loc[(indices.loc[(:, 'b')], coords)].values
        a_pos = self.loc[(indices.loc[(:, 'a')], coords)].values
    else:
        indices = np.array(indices)
        if (len(indices.shape) == 1):
            indices = indices[(None, :)]
        i_pos = self.loc[(indices[(:, 0)], coords)].values
        b_pos = self.loc[(indices[(:, 1)], coords)].values
        a_pos = self.loc[(indices[(:, 2)], coords)].values
    (BI, BA) = ((i_pos - b_pos), (a_pos - b_pos))
    (bi, ba) = [(v / np.linalg.norm(v, axis=1)[(:, None)]) for v in (BI, BA)]
    dot_product = np.sum((bi * ba), axis=1)
    dot_product[(dot_product > 1)] = 1
    dot_product[(dot_product < (- 1))] = (- 1)
    angles = np.degrees(np.arccos(dot_product))
    return angles

Return the angles between given atoms.

    Calculates the angle in degrees between the atoms with
    indices ``i, b, a``.
    The indices can be given in three ways:

    * As simple list ``[i, b, a]``
    * As list of lists: ``[[i1, b1, a1], [i2, b2, a2]...]``
    * As :class:`pd.DataFrame` where ``i`` is taken from the index and
        ``b`` and ``a`` from the respective columns ``'b'`` and ``'a'``.

Args:
        indices (list):

Returns:
        :class:`numpy.ndarray`: Vector of angles in degrees.


def __Build(leaves):
    if (len(leaves) < 1):
        raise Exception('Leaves must have length')
    if (len(leaves) == 1):
        return leaves[0]
    num_parents = int(((len(leaves) + 1) / 2))
    parents = [MerkleTreeNode() for i in range(0, num_parents)]
    for i in range(0, num_parents):
        node = parents[i]
        node.LeftChild = leaves[(i * 2)]
        leaves[(i * 2)].Parent = node
        if (((i * 2) + 1) == len(leaves)):
            node.RightChild = node.LeftChild
        else:
            node.RightChild = leaves[((i * 2) + 1)]
            leaves[((i * 2) + 1)].Parent = node
        hasharray = bytearray((node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray()))
        node.Hash = UInt256(data=Crypto.Hash256(hasharray))
    return MerkleTree.__Build(parents)

Build the merkle tree.

Args:
        leaves (list): items are of type MerkleTreeNode.

Returns:
        MerkleTreeNode: the root node.


def OpenFileEntry(cls, path_spec_object, resolver_context=None):
    file_system = cls.OpenFileSystem(path_spec_object, resolver_context=resolver_context)
    if (resolver_context is None):
        resolver_context = cls._resolver_context
    file_entry = file_system.GetFileEntryByPathSpec(path_spec_object)
    resolver_context.ReleaseFileSystem(file_system)
    return file_entry

Opens a file entry object defined by path specification.

Args:
        path_spec_object (PathSpec): path specification.
        resolver_context (Optional[Context]): resolver context, where None
        represents the built in context which is not multi process safe.

Returns:
        FileEntry: file entry or None if the path specification could not be
        resolved.


def find_replace(obj, find, replace):
    try:
        if isinstance(obj, dict):
            return {find_replace(key, find, replace): find_replace(value, find, replace) for (key, value) in obj.items()}
        elif isinstance(obj, list):
            return [find_replace(element, find, replace) for element in obj]
        elif (obj == find):
            return unicode_convert(replace)
        else:
            try:
                return unicode_convert(find_replace_string(obj, find, replace))
            except:
                return unicode_convert(obj)
    except:
        (line, filename, synerror) = trace()
        raise ArcRestHelperError({'function': 'find_replace', 'line': line, 'filename': filename, 'synerror': synerror})
    finally:
        pass

Searches an object and performs a find and replace.

Args:
        obj (object): The object to iterate and find/replace.
        find (str): The string to search for.
        replace (str): The string to replace with.

Returns:
        object: The object with replaced strings.


def ensuredir(dpath, mode=1023, verbose=None):
    if (verbose is None):
        verbose = 0
    if isinstance(dpath, (list, tuple)):
        dpath = join(*dpath)
    if (not exists(dpath)):
        if verbose:
            print(('Ensuring new directory (%r)' % dpath))
        if (sys.version_info.major == 2):
            os.makedirs(normpath(dpath), mode=mode)
        else:
            os.makedirs(normpath(dpath), mode=mode, exist_ok=True)
    elif verbose:
        print(('Ensuring existing directory (%r)' % dpath))
    return dpath

r"""
    Ensures that directory will exist. Creates new dir with sticky bits by
    default

Args:
        dpath (PathLike): dir to ensure. Can also be a tuple to send to join
        mode (int): octal mode of directory (default 0o1777)
        verbose (int): verbosity (default 0)

Returns:
        PathLike: path: the ensured directory

Note:
        This function is not thread-safe in Python2

Example:
        >>> from ubelt.util_platform import *  # NOQA
        >>> import ubelt as ub
        >>> cache_dpath = ub.ensure_app_cache_dir('ubelt')
        >>> dpath = join(cache_dpath, 'ensuredir')
        >>> if exists(dpath):
        ...     os.rmdir(dpath)
        >>> assert not exists(dpath)
        >>> ub.ensuredir(dpath)
        >>> assert exists(dpath)
        >>> os.rmdir(dpath)


def filter_string(self, word):
    segs = [m.group(0) for m in self.seg_regex.finditer(word)]
    return ''.join(segs)

Return a string like the input but containing only legal IPA segments

Args:
        word (unicode): input string to be filtered

Returns:
        unicode: string identical to `word` but with invalid IPA segments
                absent


def process_arguments(self, func, args):
    pos_args = []
    kw_args = {}
    while (len(args) > 0):
        if (func.metadata.spec_filled(pos_args, kw_args) and (not self._is_flag(args[0]))):
            break
        arg = args.pop(0)
        if (arg == '--'):
            break
        elif self._is_flag(arg):
            arg_value = None
            arg_name = None
            if (len(arg) == 2):
                arg_name = func.metadata.match_shortname(arg[1:], filled_args=pos_args)
            else:
                if (not arg.startswith('--')):
                    raise ArgumentError('Invalid method of specifying keyword argument that did not start with --', argument=arg)
                arg = arg[2:]
                if ('=' in arg):
                    (arg, arg_value) = arg.split('=', 1)
                arg_name = func.metadata.match_shortname(arg, filled_args=pos_args)
            arg_type = func.metadata.param_type(arg_name)
            if (arg_type is None):
                raise ArgumentError('Attempting to set a parameter from command line that does not have type information', argument=arg_name)
            if (arg_value is None):
                arg_value = self._extract_arg_value(arg_name, arg_type, args)
            kw_args[arg_name] = arg_value
        else:
            pos_args.append(arg)
    if ((len(args) > 0) and (args[0] == '--')):
        args.pop(0)
    return (pos_args, kw_args, args)

Process arguments from the command line into positional and kw args.

    Arguments are consumed until the argument spec for the function is filled
    or a -- is found or there are no more arguments.  Keyword arguments can be
    specified using --field=value, -f value or --field value.  Positional
    arguments are specified just on the command line itself.

    If a keyword argument (`field`) is a boolean, it can be set to True by just passing
    --field or -f without needing to explicitly pass True unless this would cause
    ambiguity in parsing since the next expected positional argument is also a boolean
    or a string.

Args:
        func (callable): A function previously annotated with type information
        args (list): A list of all of the potential arguments to this function.

Returns:
        (args, kw_args, unused args): A tuple with a list of args, a dict of
            keyword args and a list of any unused args that were not processed.


def check(self, solution):
    return self.func(*(solution[v] for v in self.variables))

Check that a solution satisfies the constraint.

Args:
        solution (container):
            An assignment for the variables in the constraint.

Returns:
        bool: True if the solution satisfies the constraint; otherwise False.

Example:
        This example creates a constraint that :math:`a \\ne b` on binary variables
        and tests it for two candidate solutions, with additional unconstrained
        variable c.

        >>> import dwavebinarycsp
        >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],
        ...             ['a', 'b'], dwavebinarycsp.BINARY)
        >>> solution = {'a': 1, 'b': 1, 'c': 0}
        >>> const.check(solution)
        False
        >>> solution = {'a': 1, 'b': 0, 'c': 0}
        >>> const.check(solution)
        True


def get_oauth_data(self, code, client_id, client_secret, state):
    request = self._get_request()
    response = request.post(self.OAUTH_TOKEN_URL, {'state': state, 'code': code, 'grant_type': 'authorization_code', 'client_id': client_id, 'client_secret': client_secret})
    return HSAccessTokenAuth.from_response(response)

Get Oauth data from HelloSign

Args:
        code (str):             Code returned by HelloSign for our callback url

        client_id (str):        Client id of the associated app

        client_secret (str):    Secret token of the associated app

Returns:
        A HSAccessTokenAuth object


def has_axis(self, axis):
    if (self.type != EventType.POINTER_AXIS):
        raise AttributeError(_wrong_meth.format(self.type))
    return self._libinput.libinput_event_pointer_has_axis(self._handle, axis)

Check if the event has a valid value for the given axis.

    If this method returns True for an axis and :meth:`get_axis_value`
    returns a value of 0, the event is a scroll stop event.

    For pointer events that are not of type
    :attr:`~libinput.constant.EventType.POINTER_AXIS`, this method raises
    :exc:`AttributeError`.

Args:
    axis (~libinput.constant.PointerAxis): The axis to check.

Returns:
    bool: True if this event contains a value for this axis.

Raises:
    AttributeError


def archs(self, as_list=False):
    archs = self.arch_list().split('/')
    if as_list:
        return archs
    return set(archs)

Return all of the architectures for this target.

Args:
        as_list (bool): Return a list instead of the default set object.

Returns:
        set or list: All of the architectures used in this TargetSettings object.


def to_microseconds(value):
    if (not value.tzinfo):
        value = value.replace(tzinfo=pytz.utc)
    value = value.astimezone(pytz.utc)
    return (int((calendar.timegm(value.timetuple()) * 1000000.0)) + value.microsecond)

Convert a datetime to microseconds since the unix epoch.

Args:
        value (datetime.datetime): The datetime to covert.

Returns:
        int: Microseconds since the unix epoch.