def subscribe_registration_ids_to_topic(self, registration_ids, topic_name):
    url = 'https://iid.googleapis.com/iid/v1:batchAdd'
    payload = {'to': ('/topics/' + topic_name), 'registration_tokens': registration_ids}
    response = self.requests_session.post(url, json=payload)
    if (response.status_code == 200):
        return True
    elif (response.status_code == 400):
        error = response.json()
        raise InvalidDataError(error['error'])
    else:
        raise FCMError()

Subscribes a list of registration ids to a topic

Args:
        registration_ids (list): ids to be subscribed
        topic_name (str): name of topic

Returns:
        True: if operation succeeded

Raises:
        InvalidDataError: data sent to server was incorrectly formatted
        FCMError: an error occured on the server


def download_archive(self, name, file_path):
    uri = ((self.URI + '/archive/') + name)
    return self._client.download(uri, file_path)

Download archived logs of the OS Volume.

Args:
        name: Name of the OS Volume.
        file_path (str): Destination file path.

Returns:
        bool: Indicates if the resource was successfully downloaded.


def _has_valid_abs_ref(self, i, construction_table):
    c_table = construction_table
    abs_refs = constants.absolute_refs
    A = np.empty((3, 3))
    row = c_table.index.get_loc(i)
    if (row > 2):
        message = 'The index {i} is not from the first three, rows'.format
        raise ValueError(message(i=i))
    for k in range(3):
        if (k < row):
            A[k] = self.loc[(c_table.iloc[(row, k)], ['x', 'y', 'z'])]
        else:
            A[k] = abs_refs[c_table.iloc[(row, k)]]
    (v1, v2) = ((A[2] - A[1]), (A[1] - A[0]))
    K = np.cross(v1, v2)
    zero = np.full(3, 0.0)
    return (not (np.allclose(K, zero) or np.allclose(v1, zero) or np.allclose(v2, zero)))

Checks, if ``i`` uses valid absolute references.

    Checks for each index from first to third row of the
    ``construction_table``, if the references are colinear.
    This case has to be specially treated, because the references
    are not only atoms (to fix internal degrees of freedom) but also points
    in cartesian space called absolute references.
    (to fix translational and rotational degrees of freedom)

Args:
        i (label): The label has to be in the first three rows.
        construction_table (pd.DataFrame):

Returns:
        bool:


def get_grouped_indices(self, voigt=False, **kwargs):
    if voigt:
        array = self.voigt
    else:
        array = self
    indices = list(itertools.product(*[range(n) for n in array.shape]))
    remaining = indices.copy()
    grouped = [list(zip(*np.where(np.isclose(array, 0, **kwargs))))]
    remaining = [i for i in remaining if (i not in grouped[0])]
    while remaining:
        new = list(zip(*np.where(np.isclose(array, array[remaining[0]], **kwargs))))
        grouped.append(new)
        remaining = [i for i in remaining if (i not in new)]
    return [g for g in grouped if g]

Gets index sets for equivalent tensor values

Args:
        voigt (bool): whether to get grouped indices
            of voigt or full notation tensor, defaults
            to false
        **kwargs: keyword args for np.isclose.  Can take atol
            and rtol for absolute and relative tolerance, e. g.

            >>> tensor.group_array_indices(atol=1e-8)

            or

            >>> tensor.group_array_indices(rtol=1e-5)

Returns:
        list of index groups where tensor values are equivalent to
        within tolerances


def find_sanitiser_nodes(sanitiser, sanitisers_in_file):
    for sanitiser_tuple in sanitisers_in_file:
        if (sanitiser == sanitiser_tuple.trigger_word):
            (yield sanitiser_tuple.cfg_node)

Find nodes containing a particular sanitiser.

Args:
        sanitiser(string): sanitiser to look for.
        sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser.

Returns:
        Iterable of sanitiser nodes.


def parse_hgnc_line(line, header):
    hgnc_gene = {}
    line = line.rstrip().split('\t')
    raw_info = dict(zip(header, line))
    if ('Withdrawn' in raw_info['status']):
        return hgnc_gene
    hgnc_symbol = raw_info['symbol']
    hgnc_gene['hgnc_symbol'] = hgnc_symbol
    hgnc_gene['hgnc_id'] = int(raw_info['hgnc_id'].split(':')[(- 1)])
    hgnc_gene['description'] = raw_info['name']
    aliases = set([hgnc_symbol, hgnc_symbol.upper()])
    previous_names = raw_info['prev_symbol']
    if previous_names:
        for alias in previous_names.strip('"').split('|'):
            aliases.add(alias)
    alias_symbols = raw_info['alias_symbol']
    if alias_symbols:
        for alias in alias_symbols.strip('"').split('|'):
            aliases.add(alias)
    hgnc_gene['previous_symbols'] = list(aliases)
    hgnc_gene['ensembl_gene_id'] = raw_info.get('ensembl_gene_id')
    omim_id = raw_info.get('omim_id')
    if omim_id:
        hgnc_gene['omim_id'] = int(omim_id.strip('"').split('|')[0])
    else:
        hgnc_gene['omim_id'] = None
    entrez_id = hgnc_gene['entrez_id'] = raw_info.get('entrez_id')
    if entrez_id:
        hgnc_gene['entrez_id'] = int(entrez_id)
    else:
        hgnc_gene['entrez_id'] = None
    ref_seq = raw_info.get('refseq_accession')
    if ref_seq:
        hgnc_gene['ref_seq'] = ref_seq.strip('"').split('|')
    else:
        hgnc_gene['ref_seq'] = []
    uniprot_ids = raw_info.get('uniprot_ids')
    if uniprot_ids:
        hgnc_gene['uniprot_ids'] = uniprot_ids.strip('""').split('|')
    else:
        hgnc_gene['uniprot_ids'] = []
    ucsc_id = raw_info.get('ucsc_id')
    if ucsc_id:
        hgnc_gene['ucsc_id'] = ucsc_id
    else:
        hgnc_gene['ucsc_id'] = None
    vega_id = raw_info.get('vega_id')
    if vega_id:
        hgnc_gene['vega_id'] = vega_id
    else:
        hgnc_gene['vega_id'] = None
    return hgnc_gene

Parse an hgnc formated line

Args:
        line(list): A list with hgnc gene info
        header(list): A list with the header info

Returns:
        hgnc_info(dict): A dictionary with the relevant info


def _get_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'):
    if (schema_dir is None):
        schema_dir = os.path.abspath((((os.path.dirname(__file__) + '/schemas-') + version) + '/'))
    try:
        schema_path = find_schema(schema_dir, type)
        schema = load_schema(schema_path)
    except (KeyError, TypeError):
        try:
            schema_path = find_schema(schema_dir, default)
            schema = load_schema(schema_path)
        except (KeyError, TypeError):
            if (schema_dir is not None):
                return None
            raise SchemaInvalidError("Cannot locate a schema for the object's type, nor the base schema ({}.json).".format(default))
    if ((type == 'observed-data') and (schema_dir is None)):
        schema['allOf'][1]['properties']['objects'] = {'objects': {'type': 'object', 'minProperties': 1}}
    validator = load_validator(schema_path, schema)
    try:
        error_gen = validator.iter_errors(obj)
    except schema_exceptions.RefResolutionError:
        raise SchemaInvalidError('Invalid JSON schema: a JSON reference failed to resolve')
    return error_gen

Get a generator for validating against the schema for the given object type.

Args:
        type (str): The object type to find the schema for.
        obj: The object to be validated.
        schema_dir (str): The path in which to search for schemas.
        version (str): The version of the STIX specification to validate
            against. Only used to find base schemas when schema_dir is None.
        default (str): If the schema for the given type cannot be found, use
            the one with this name instead.

Returns:
        A generator for errors found when validating the object against the
        appropriate schema, or None if schema_dir is None and the schema
        cannot be found.


def prange(N=1, dim=1):
    A = {}
    r = numpy.arange(N, dtype=int)
    key = numpy.zeros(dim, dtype=int)
    for i in range(N):
        key[(- 1)] = i
        A[tuple(key)] = (1 * (r == i))
    return Poly(A, dim, (N,), int)

Constructor to create a range of polynomials where the exponent vary.

Args:
        N (int):
            Number of polynomials in the array.
        dim (int):
            The dimension the polynomial should span.

Returns:
        (Poly):
            A polynomial array of length N containing simple polynomials with
            increasing exponent.

Example:
        >>> print(prange(4))
        [1, q0, q0^2, q0^3]
        >>> print(prange(4, dim=3))
        [1, q2, q2^2, q2^3]


def average_data(counts, observable):
    if (not isinstance(observable, dict)):
        observable = make_dict_observable(observable)
    temp = 0
    tot = sum(counts.values())
    for key in counts:
        if (key in observable):
            temp += ((counts[key] * observable[key]) / tot)
    return temp

Compute the mean value of an diagonal observable.

    Takes in a diagonal observable in dictionary, list or matrix format and then
    calculates the sum_i value(i) P(i) where value(i) is the value of the
    observable for state i.

Args:
        counts (dict): a dict of outcomes from an experiment
        observable (dict or matrix or list): The observable to be averaged over.
        As an example, ZZ on qubits can be given as:
        * dict: {"00": 1, "11": 1, "01": -1, "10": -1}
        * matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]]
        * matrix diagonal (list): [1, -1, -1, 1]

Returns:
        Double: Average of the observable


def get_choices(field):
    empty_label = getattr(field.field, 'empty_label', False)
    needs_empty_value = False
    choices = []
    if hasattr(field.field, '_choices'):
        choices = field.field._choices
    elif hasattr(field.field, '_queryset'):
        queryset = field.field._queryset
        field_name = (getattr(field.field, 'to_field_name') or 'pk')
        choices += ((getattr(obj, field_name), str(obj)) for obj in queryset)
    if (choices and ((choices[0][1] == BLANK_CHOICE_DASH[0][1]) or choices[0][0])):
        needs_empty_value = True
        if (not choices[0][0]):
            del choices[0]
    if (empty_label == BLANK_CHOICE_DASH[0][1]):
        empty_label = None
    if (empty_label or (not field.field.required)):
        if needs_empty_value:
            choices.insert(0, ('', (empty_label or BLANK_CHOICE_DASH[0][1])))
    return choices

Find choices of a field, whether it has choices or has a queryset.

Args:
    field (BoundField): Django form boundfield

Returns:
    list: List of choices


def get_mipmap_pixel(self, left: float, top: float, right: float, bottom: float) -> Tuple[(int, int, int)]:
    color = lib.TCOD_image_get_mipmap_pixel(self.image_c, left, top, right, bottom)
    return (color.r, color.g, color.b)

Get the average color of a rectangle in this Image.

    Parameters should stay within the following limits:
    * 0 <= left < right < Image.width
    * 0 <= top < bottom < Image.height

Args:
        left (float): Left corner of the region.
        top (float): Top corner of the region.
        right (float): Right corner of the region.
        bottom (float): Bottom corner of the region.

Returns:
        Tuple[int, int, int]:
            An (r, g, b) tuple containing the averaged color value.
            Values are in a 0 to 255 range.


def _async_open(self, session_id, proto_version):
    try:
        (yield self.application_context.create_session_if_needed(session_id, self.request))
        session = self.application_context.get_session(session_id)
        protocol = Protocol(proto_version)
        self.receiver = Receiver(protocol)
        log.debug('Receiver created for %r', protocol)
        self.handler = ProtocolHandler()
        log.debug('ProtocolHandler created for %r', protocol)
        self.connection = self.application.new_connection(protocol, self, self.application_context, session)
        log.info('ServerConnection created')
    except ProtocolError as e:
        log.error('Could not create new server session, reason: %s', e)
        self.close()
        raise e
    msg = self.connection.protocol.create('ACK')
    (yield self.send_message(msg))
    raise gen.Return(None)

Perform the specific steps needed to open a connection to a Bokeh session

    Specifically, this method coordinates:

    * Getting a session for a session ID (creating a new one if needed)
    * Creating a protocol receiver and hander
    * Opening a new ServerConnection and sending it an ACK

Args:
        session_id (str) :
            A session ID to for a session to connect to

            If no session exists with the given ID, a new session is made

        proto_version (str):
            The protocol version requested by the connecting client.

Returns:
        None


def run(self, dag):
    for node in dag.op_nodes(self.gate):
        if (not node.op.definition):
            continue
        rule = node.op.definition
        decomposition = DAGCircuit()
        decomposition.add_qreg(rule[0][1][0][0])
        if rule[0][2]:
            decomposition.add_creg(rule[0][2][0][0])
        for inst in rule:
            decomposition.apply_operation_back(*inst)
        dag.substitute_node_with_dag(node, decomposition)
    return dag

Expand a given gate into its decomposition.

Args:
        dag(DAGCircuit): input dag

Returns:
        DAGCircuit: output dag where gate was expanded.


def monitor(self, field, callback, poll_interval=None):
    poll_interval = (poll_interval or self.api.poll_interval)
    monitor = self.monitor_class(resource=self, field=field, callback=callback, poll_interval=poll_interval, event_queue=self.api.event_queue, poll_pool=self.api.poll_pool)
    monitor.start()
    return monitor

Monitor `field` for change

    Will monitor ``field`` for change and execute ``callback`` when
    change is detected.

    Example usage::

        def handle(resource, field, previous, current):
            print "Change from {} to {}".format(previous, current)

        switch = TapSwitch.objects.get(id=3)
        # Note that we monitor the entire state of the Hue Tap
        # switch rather than a specific field
        switch.monitor(lambda sw: sw.state.as_dict(), handle, poll_interval=0.2)

        # Execution will stop here and the API client will begin polling for changes
        hue_api.start_monitor_loop()

Args:
        field (string): The name of the field to be monitored. This may also
            be a callable which will be called with the resource
            instance as its single argument and must return a
            value which can be compared to previous values.

        callback (callable): The callable to be called when a change is
            detected. It will be called with parameters
            as follows:

            * resource instance
            * field name,
            * previous value
            * current value.

        poll_interval (float): Interval between polling in seconds.
            Defaults to the API's `poll_interval` value (which defaults
            to 0.1 second.

Returns:
        Monitor:


def _ReadUnionDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
    return self._ReadDataTypeDefinitionWithMembers(definitions_registry, definition_values, data_types.UnionDefinition, definition_name, supports_conditions=False)

Reads an union 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:
        UnionDefinition: union data type definition.

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


def reset_folder(self, folder):
    warnings.warn('This is a destructive action that cannot be undone.')
    self.post('reset', data={}, params={'folder': folder})

Erase the database index from a given folder and restart Syncthing.

Args:
        folder (str): Folder ID.

Returns:
        None


def _FormatSocketUnixToken(self, token_data):
    protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN')
    return {'protocols': protocol, 'family': token_data.socket_family, 'path': token_data.socket_path}

Formats an Unix socket token as a dictionary of values.

Args:
        token_data (bsm_token_data_sockunix): AUT_SOCKUNIX token data.

Returns:
        dict[str, str]: token values.


def _execute(self, command, data=None, unpack=True):
    if (not data):
        data = {}
    if (self.session_id is not None):
        data.setdefault('session_id', self.session_id)
    data = self._wrap_el(data)
    res = self.remote_invoker.execute(command, data)
    ret = WebDriverResult.from_object(res)
    ret.raise_for_status()
    ret.value = self._unwrap_el(ret.value)
    if (not unpack):
        return ret
    return ret.value

Private method to execute command.

Args:
        command(Command): The defined command.
        data(dict): The uri variable and body.
        uppack(bool): If unpack value from result.

Returns:
        The unwrapped value field in the json response.


def Open(self, path, ascii_codepage='cp1252'):
    path_specification = self._path_resolver.ResolvePath(path)
    if (path_specification is None):
        return None
    return self._OpenPathSpec(path_specification)

Opens the Windows Registry file specified by the path.

Args:
        path (str): path of the Windows Registry file.
        ascii_codepage (Optional[str]): ASCII string codepage.

Returns:
        WinRegistryFile: Windows Registry file or None.


def get_device_name(self, cached=True):
    if (cached and (self.name is not None)):
        return self.name
    device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME)
    if (device_name is None):
        logger.warn('Failed to find handle for device name')
        return None
    self.name = self.dongle._read_attribute(self.conn_handle, device_name)
    return self.name

Returns the SK8 device BLE name.

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

Returns:
        str. The current device name. May be `None` if an error occurs.


def read_tracers_h5(xdmf_file, infoname, snapshot, position):
    xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
    tra = {}
    tra[infoname] = [{}, {}]
    if position:
        for axis in 'xyz':
            tra[axis] = [{}, {}]
    for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):
        ibk = int(elt_subdomain.get('Name').startswith('meshYang'))
        if position:
            for data_attr in elt_subdomain.findall('Geometry'):
                for (data_item, axis) in zip(data_attr.findall('DataItem'), 'xyz'):
                    (icore, data) = _get_field(xdmf_file, data_item)
                    tra[axis][ibk][icore] = data
        for data_attr in elt_subdomain.findall('Attribute'):
            if (data_attr.get('Name') != infoname):
                continue
            (icore, data) = _get_field(xdmf_file, data_attr.find('DataItem'))
            tra[infoname][ibk][icore] = data
    for info in tra:
        tra[info] = [trab for trab in tra[info] if trab]
        for (iblk, trab) in enumerate(tra[info]):
            tra[info][iblk] = np.concatenate([trab[icore] for icore in range(len(trab))])
    return tra

Extract tracers data from hdf5 files.

Args:
        xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
        infoname (str): name of information to extract.
        snapshot (int): snapshot number.
        position (bool): whether to extract position of tracers.

Returns:
        dict of list of numpy.array:
            Tracers data organized by attribute and block.


def swo_set_emu_buffer_size(self, buf_size):
    buf = ctypes.c_uint32(buf_size)
    res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_EMU, ctypes.byref(buf))
    if (res < 0):
        raise errors.JLinkException(res)
    return None

Sets the size of the buffer used by the J-Link to collect SWO data.

Args:
        self (JLink): the ``JLink`` instance
        buf_size (int): the new size of the emulator buffer

Returns:
        ``None``

Raises:
        JLinkException: on error


def _get_elmt_amt_in_rxt(self, rxt):
    return sum([rxt.get_el_amount(e) for e in self.pd.elements])

Computes total number of atoms in a reaction formula for elements
    not in external reservoir. This method is used in the calculation
    of reaction energy per mol of reaction formula.

Args:
        rxt (Reaction): a reaction.

Returns:
        Total number of atoms for non_reservoir elements.


def find_common_root(elements):
    if (not elements):
        raise UserWarning("Can't find common root - no elements suplied.")
    root_path = el_to_path_vector(elements.pop())
    for el in elements:
        el_path = el_to_path_vector(el)
        root_path = common_vector_root(root_path, el_path)
        if (not root_path):
            raise UserWarning(('Vectors without common root:\n%s' % str(el_path)))
    return root_path

Find root which is common for all `elements`.

Args:
        elements (list): List of double-linked HTMLElement objects.

Returns:
        list: Vector of HTMLElement containing path to common root.


def name(self):
    return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()

Returns the name of the device.

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

Returns:
        Device name.


def get_dim_label(js_dict, dim, input='dataset'):
    if (input == 'dataset'):
        input = js_dict['dimension'][dim]
        label_col = 'label'
    elif (input == 'dimension'):
        label_col = js_dict['label']
        input = js_dict
    else:
        raise ValueError
    try:
        dim_label = input['category']['label']
    except KeyError:
        dim_index = get_dim_index(js_dict, dim)
        dim_label = pd.concat([dim_index['id'], dim_index['id']], axis=1)
        dim_label.columns = ['id', 'label']
    else:
        dim_label = pd.DataFrame(list(zip(dim_label.keys(), dim_label.values())), index=dim_label.keys(), columns=['id', label_col])
    try:
        dim_index = input['category']['index']
    except KeyError:
        dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])), index=[0], columns=['id', 'index'])
    else:
        if (type(dim_index) is list):
            dim_index = pd.DataFrame(list(zip(dim_index, range(0, len(dim_index)))), index=dim_index, columns=['id', 'index'])
        else:
            dim_index = pd.DataFrame(list(zip(dim_index.keys(), dim_index.values())), index=dim_index.keys(), columns=['id', 'index'])
    dim_label = pd.merge(dim_label, dim_index, on='id').sort_index(by='index')
    return dim_label

Get label from a given dimension.

Args:
        js_dict (dict): dictionary containing dataset data and metadata.
        dim (string): dimension name obtained from JSON file.

Returns:
        dim_label(pandas.DataFrame): DataFrame with label-based dimension data.


def get_counters(counter_list):
    if (not isinstance(counter_list, list)):
        raise CommandExecutionError('counter_list must be a list of tuples')
    try:
        query = win32pdh.OpenQuery()
        counters = build_counter_list(counter_list)
        for counter in counters:
            counter.add_to_query(query)
        win32pdh.CollectQueryData(query)
        time.sleep(1)
        win32pdh.CollectQueryData(query)
        ret = {}
        for counter in counters:
            try:
                ret.update({counter.path: counter.value()})
            except pywintypes.error as exc:
                if (exc.strerror == 'No data to return.'):
                    continue
                else:
                    raise
    finally:
        win32pdh.CloseQuery(query)
    return ret

Get the values for the passes list of counters

Args:
        counter_list (list):
            A list of counters to lookup

Returns:
        dict: A dictionary of counters and their values


def is_storage(url, storage=None):
    if storage:
        return True
    split_url = url.split('://', 1)
    if ((len(split_url) == 2) and (split_url[0].lower() != 'file')):
        return True
    return False

Check if file is a local file or a storage file.

    File is considered local if:
        - URL is a local path.
        - URL starts by "file://"
        - a "storage" is provided.

Args:
        url (str): file path or URL
        storage (str): Storage name.

Returns:
        bool: return True if file is local.


def response(self, in_thread: Optional[bool]=None) -> 'Message':
    data = {'channel': self['channel']}
    if in_thread:
        if ('message' in self):
            data['thread_ts'] = (self['message'].get('thread_ts') or self['message']['ts'])
        else:
            data['thread_ts'] = (self.get('thread_ts') or self['ts'])
    elif (in_thread is None):
        if (('message' in self) and ('thread_ts' in self['message'])):
            data['thread_ts'] = self['message']['thread_ts']
        elif ('thread_ts' in self):
            data['thread_ts'] = self['thread_ts']
    return Message(data)

Create a response message.

    Depending on the incoming message the response can be in a thread. By default the response follow where the
    incoming message was posted.

Args:
        in_thread (boolean): Overwrite the `threading` behaviour

Returns:
        a new :class:`slack.event.Message`


def best_kmers(dt, response, sequence, k=6, consider_shift=True, n_cores=1, seq_align='start', trim_seq_len=None):
    y = dt[response]
    seq = dt[sequence]
    if (trim_seq_len is not None):
        seq = pad_sequences(seq, align=seq_align, maxlen=trim_seq_len)
        seq = [s.replace('N', '') for s in seq]
    dt_kmer = kmer_count(seq, k)
    Xsp = csc_matrix(dt_kmer)
    en = ElasticNet(alpha=1, standardize=False, n_splits=3)
    en.fit(Xsp, y)
    nonzero_kmers = dt_kmer.columns.values[(en.coef_ != 0)].tolist()

    def find_next_best(dt_kmer, y, selected_kmers, to_be_selected_kmers, consider_shift=True):
        '\n        perform stepwise model selection while preventing to add a motif similar to the\n        already selected motifs.\n        '
        (F, pval) = f_regression(dt_kmer[to_be_selected_kmers], y)
        kmer = to_be_selected_kmers.pop(pval.argmin())
        selected_kmers.append(kmer)

        def select_criterion(s1, s2, consider_shift=True):
            if (hamming_distance(s1, s2) <= 1):
                return False
            if (consider_shift and (hamming_distance(s1[1:], s2[:(- 1)]) == 0)):
                return False
            if (consider_shift and (hamming_distance(s1[:(- 1)], s2[1:]) == 0)):
                return False
            return True
        to_be_selected_kmers = [ckmer for ckmer in to_be_selected_kmers if select_criterion(ckmer, kmer, consider_shift)]
        if (len(to_be_selected_kmers) == 0):
            return selected_kmers
        else:
            lm = LinearRegression()
            lm.fit(dt_kmer[selected_kmers], y)
            y_new = (y - lm.predict(dt_kmer[selected_kmers]))
            return find_next_best(dt_kmer, y_new, selected_kmers, to_be_selected_kmers, consider_shift)
    selected_kmers = find_next_best(dt_kmer, y, [], nonzero_kmers, consider_shift)
    return selected_kmers

Find best k-mers for CONCISE initialization.

Args:
        dt (pd.DataFrame): Table containing response variable and sequence.
        response (str): Name of the column used as the reponse variable.
        sequence (str): Name of the column storing the DNA/RNA sequences.
        k (int): Desired k-mer length.
        n_cores (int): Number of cores to use for computation. It can use up to 3 cores.
        consider_shift (boolean): When performing stepwise k-mer selection. Is TATTTA similar to ATTTAG?
        seq_align (str): one of ``{"start", "end"}``. To which end should we align sequences?
        trim_seq_len (int): Consider only first `trim_seq_len` bases of each sequence when generating the sequence design matrix. If :python:`None`, set :py:attr:`trim_seq_len` to the longest sequence length, hence whole sequences are considered.

Returns:
        string list: Best set of motifs for this dataset sorted with respect to
                    confidence (best candidate occuring first).

    Details:
        First a lasso model gets fitted to get a set of initial motifs. Next, the best
        subset of unrelated motifs is selected by stepwise selection.


def check_R_package(self, package):
    test_package = (not bool(launch_R_script('{}/R_templates/test_import.R'.format(os.path.dirname(os.path.realpath(__file__))), {'{package}': package}, verbose=True)))
    return test_package

Execute a subprocess to check the package's availability.

Args:
        package (str): Name of the package to be tested.

Returns:
        bool: `True` if the package is available, `False` otherwise


def key_periods(ciphertext, max_key_period):
    if (max_key_period <= 0):
        raise ValueError('max_key_period must be a positive integer')
    key_scores = []
    for period in range(1, (min(max_key_period, len(ciphertext)) + 1)):
        score = abs((ENGLISH_IC - index_of_coincidence(*split_columns(ciphertext, period))))
        key_scores.append((period, score))
    return [p[0] for p in sorted(key_scores, key=(lambda x: x[1]))]

Rank all key periods for ``ciphertext`` up to and including ``max_key_period``

Example:
        >>> key_periods(ciphertext, 30)
        [2, 4, 8, 3, ...]

Args:
        ciphertext (str): The text to analyze
        max_key_period (int): The maximum period the key could be

Returns:
        Sorted list of keys

Raises:
        ValueError: If max_key_period is less than or equal to 0


def _CalculateNTFSTimeHash(self, file_entry):
    date_time_values = []
    access_time = getattr(file_entry, 'access_time', None)
    if access_time:
        date_time_string = access_time.CopyToDateTimeString()
        date_time_values.append('atime:{0:s}'.format(date_time_string))
    creation_time = getattr(file_entry, 'creation_time', None)
    if creation_time:
        date_time_string = creation_time.CopyToDateTimeString()
        date_time_values.append('crtime:{0:s}'.format(date_time_string))
    modification_time = getattr(file_entry, 'modification_time', None)
    if modification_time:
        date_time_string = modification_time.CopyToDateTimeString()
        date_time_values.append('mtime:{0:s}'.format(date_time_string))
    change_time = getattr(file_entry, 'change_time', None)
    if change_time:
        date_time_string = change_time.CopyToDateTimeString()
        date_time_values.append('ctime:{0:s}'.format(date_time_string))
    date_time_values = ''.join(date_time_values)
    date_time_values = date_time_values.encode('ascii')
    hash_value = hashlib.md5()
    hash_value.update(date_time_values)
    return hash_value.hexdigest()

Calculates an MD5 from the date and time value of a NTFS file entry.

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

Returns:
        str: hexadecimal representation of the MD5 hash value of the date and
        time values of the file entry.


def find_last(self, selector, **kwargs):
    self.debug_log(('Finding last element with selector: %s' % selector))
    elements = self.find_all(selector, **kwargs)
    if len(elements):
        self.debug_log(('find_last (%s): element found' % selector))
        return elements[(- 1)]
    else:
        self.debug_log(('find_last (%s): No element found' % selector))
        return None

Return the last element found with a selector

Args:
        selector (str): the selector used to find the element

    Kwargs:
        wait_until_present (bool)
        wait_until_visible (bool)
        raise_exception (bool)

Returns:
        None if no element was found
        proxy_element is an element was found

Raises:
        this function might raise an exception depending
            on the raise_exception kwargs
        or
        the config proxy_driver:raise_exception


def validate(filename=None, ocrd_page=None, ocrd_file=None, strictness='strict', strategy='index1'):
    if ocrd_page:
        validator = PageValidator(ocrd_page, strictness, strategy)
    elif ocrd_file:
        validator = PageValidator(page_from_file(ocrd_file), strictness, strategy)
    elif filename:
        validator = PageValidator(parse(filename, silence=True), strictness, strategy)
    else:
        raise Exception('At least one of ocrd_page, ocrd_file or filename must be set')
    return validator._validate()

Validates a PAGE file for consistency by filename, OcrdFile or passing OcrdPage directly.

Args:
        filename (string): Path to PAGE
        ocrd_page (OcrdPage): OcrdPage instance
        ocrd_file (OcrdFile): OcrdFile instance wrapping OcrdPage
        strictness (string): 'strict', 'lax', 'fix' or 'off'
        strategy (string): Currently only 'index1'

Returns:
        report (:class:`ValidationReport`) Report on the validity


def minimize_best_n(Members):
    return list(reversed(sorted(Members, key=(lambda Member: Member.fitness_score))))

Orders population members from lowest fitness to highest fitness

Args:
        Members (list): list of PyGenetics Member objects

Returns:
        lsit: ordered lsit of Members, from highest fitness to lowest fitness


def format_config(sensor_graph):
    cmdfile = CommandFile('Config Variables', '1.0')
    for slot in sorted(sensor_graph.config_database, key=(lambda x: x.encode())):
        for (conf_var, conf_def) in sorted(sensor_graph.config_database[slot].items()):
            (conf_type, conf_val) = conf_def
            if (conf_type == 'binary'):
                conf_val = ('hex:' + hexlify(conf_val))
            cmdfile.add('set_variable', slot, conf_var, conf_type, conf_val)
    return cmdfile.dump()

Extract the config variables from this sensor graph in ASCII format.

Args:
        sensor_graph (SensorGraph): the sensor graph that we want to format

Returns:
        str: The ascii output lines concatenated as a single string


def set_lacp_timeout(self, name, value=None):
    commands = [('interface %s' % name)]
    string = 'port-channel lacp fallback timeout'
    commands.append(self.command_builder(string, value=value))
    return self.configure(commands)

Configures the Port-Channel LACP fallback timeout
    The fallback timeout configures the period an interface in
    fallback mode remains in LACP mode without receiving a PDU.

Args:
    name(str): The Port-Channel interface name

    value(int): port-channel lacp fallback timeout in seconds

Returns:
    True if the operation succeeds otherwise False is returned


def get_continent(self, callsign, timestamp=timestamp_now):
    return self.get_all(callsign, timestamp)[const.CONTINENT]

Returns the continent Identifier of a callsign

Args:
        callsign (str): Amateur Radio callsign
        timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)

Returns:
        str: continent identified

Raises:
        KeyError: No Continent found for callsign

Note:
        The following continent identifiers are used:

        - EU: Europe
        - NA: North America
        - SA: South America
        - AS: Asia
        - AF: Africa
        - OC: Oceania
        - AN: Antarctica


def orthonormalize_righthanded(basis):
    (v1, v2) = (basis[(:, 0)], basis[(:, 1)])
    e1 = normalize(v1)
    e3 = normalize(np.cross(e1, v2))
    e2 = normalize(np.cross(e3, e1))
    return np.array([e1, e2, e3]).T

Orthonormalizes righthandedly a given 3D basis.

    This functions returns a right handed orthonormalize_righthandedd basis.
    Since only the first two vectors in the basis are used, it does not matter
    if you give two or three vectors.

    Right handed means, that:

    .. math::

        \\vec{e_1} \\times \\vec{e_2} &= \\vec{e_3} \\\\
        \\vec{e_2} \\times \\vec{e_3} &= \\vec{e_1} \\\\
        \\vec{e_3} \\times \\vec{e_1} &= \\vec{e_2} \\\\

Args:
        basis (np.array): An array of shape = (3,2) or (3,3)

Returns:
        new_basis (np.array): A right handed orthonormalized basis.


def disable_plugin(self, name):
    url = self._url('/plugins/{0}/disable', name)
    res = self._post(url)
    self._raise_for_status(res)
    return True

Disable an installed plugin.

Args:
        name (string): The name of the plugin. The ``:latest`` tag is
            optional, and is the default if omitted.

Returns:
        ``True`` if successful


def line_iter(xo: int, yo: int, xd: int, yd: int) -> Iterator[Tuple[(int, int)]]:
    data = ffi.new('TCOD_bresenham_data_t *')
    lib.TCOD_line_init_mt(xo, yo, xd, yd, data)
    x = ffi.new('int *')
    y = ffi.new('int *')
    (yield (xo, yo))
    while (not lib.TCOD_line_step_mt(x, y, data)):
        (yield (x[0], y[0]))

returns an Iterable

    This Iterable does not include the origin point.

Args:
        xo (int): X starting point.
        yo (int): Y starting point.
        xd (int): X destination point.
        yd (int): Y destination point.

Returns:
        Iterable[Tuple[int,int]]: An Iterable of (x,y) points.


def get(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs):
    if (user_agent or user_agent_config_yaml or ('user_agent' in UserAgent._environment_variables(**kwargs))):
        return UserAgent._create(user_agent, user_agent_config_yaml, user_agent_lookup, **kwargs)
    if cls.user_agent:
        return cls.user_agent
    else:
        raise UserAgentError('You must either set the global user agent: UserAgent.set_global(...) or pass in user agent parameters!')

Get full user agent string from parameters if supplied falling back on global user agent if set.

Args:
        user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed.
        user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml.
        user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied.

Returns:
        str: Full user agent string


def psd(data, dt, ndivide=1, window=hanning, overlap_half=False):
    logger = getLogger('decode.utils.ndarray.psd')
    if overlap_half:
        step = int((len(data) / (ndivide + 1)))
        size = (step * 2)
    else:
        step = int((len(data) / ndivide))
        size = step
    if (bin(len(data)).count('1') != 1):
        logger.warning('warning: length of data is not power of 2: {}'.format(len(data)))
    size = int((len(data) / ndivide))
    if (bin(size).count('1') != 1.0):
        if overlap_half:
            logger.warning('warning: ((length of data) / (ndivide+1)) * 2 is not power of 2: {}'.format(size))
        else:
            logger.warning('warning: (length of data) / ndivide is not power of 2: {}'.format(size))
    psd = np.zeros(size)
    T = ((size - 1) * dt)
    vs = (1 / dt)
    vk_ = fftfreq(size, dt)
    vk = vk_[np.where((vk_ >= 0))]
    for i in range(ndivide):
        d = data[(i * step):((i * step) + size)]
        if (window is None):
            w = np.ones(size)
            corr = 1.0
        else:
            w = window(size)
            corr = np.mean((w ** 2))
        psd = (psd + ((((2 * (np.abs(fft((d * w))) ** 2)) / size) * dt) / corr))
    return (vk, (psd[:len(vk)] / ndivide))

Calculate power spectrum density of data.

Args:
        data (np.ndarray): Input data.
        dt (float): Time between each data.
        ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
        ax (matplotlib.axes): Axis you want to plot on.
        doplot (bool): Plot how averaging works.
        overlap_half (bool): Split data to half-overlapped regions.

Returns:
        vk (np.ndarray): Frequency.
        psd (np.ndarray): PSD


def create_transfer_learning_tuner(parent, additional_parents=None, estimator=None, sagemaker_session=None):
    parent_tuner = HyperparameterTuner.attach(tuning_job_name=parent, sagemaker_session=sagemaker_session)
    return parent_tuner.transfer_learning_tuner(additional_parents=additional_parents, estimator=estimator)

Creates a new ``HyperParameterTuner`` by copying the request fields from the provided parent to the new instance
    of ``HyperparameterTuner`` followed by addition of warm start configuration with the type as "TransferLearning"
    and ``parents`` as the union of provided list of ``additional_parents`` and the ``parent``.

Args:
    parent (str): Primary parent tuning job's name from which the Tuner and Estimator configuration has to be copied
    additional_parents (set{str}): Set of additional parent tuning job's names along with the primary parent tuning
        job name to be used in warm starting the identical dataset and algorithm tuner.
    estimator (sagemaker.estimator.EstimatorBase): An estimator object that has been initialized with
            the desired configuration. There does not need to be a training job associated with this instance.
    sagemaker_session (sagemaker.session.Session): Session object which manages interactions with
            Amazon SageMaker APIs and any other AWS services needed. If not specified, one is created
            using the default AWS configuration chain.

Returns:
    sagemaker.tuner.HyperparameterTuner: New instance of warm started HyperparameterTuner


def get_config(filepath=None, default_loader=None, on_missing=None):
    cache_key = (filepath, default_loader, on_missing)
    if (CACHE.get(cache_key) is not None):
        return CACHE.get(cache_key)
    logger = logging.getLogger('birding')
    if (filepath is None):
        filepath = BIRDING_CONF
    if (default_loader is None):
        default_loader = get_defaults_file
    if (on_missing is None):
        on_missing = logger.info
    logger.info('Looking for configuration file: {}'.format(os.path.abspath(filepath)))
    if (not os.path.exists(filepath)):
        on_missing('No {} configuration file found.'.format(filepath))
        if (filepath != BIRDING_CONF_DEFAULT):
            os.stat(filepath)
    config = yaml.safe_load(default_loader())
    tv.validate(SCHEMA, config)
    if os.path.exists(filepath):
        file_config = yaml.safe_load(open(filepath))
        if file_config:
            config = overlay(file_config, config)
            tv.validate(SCHEMA, config)
    CACHE.put(cache_key, config)
    return config

Get a dict for the current birding configuration.

    The resulting dictionary is fully populated with defaults, such that all
    valid keys will resolve to valid values. Invalid and extra values in the
    configuration result in an exception.

    See :ref:`config` (module-level docstring) for discussion on how birding
    configuration works, including filepath loading. Note that a non-default
    filepath set via env results in a :py:exc:`OSError` when the file is
    missing, but the default filepath is ignored when missing.

    This function caches its return values as to only parse configuration once
    per set of inputs. As such, treat the resulting dictionary as read-only as
    not to accidentally write values which will be seen by other handles of the
    dictionary.

Args:
        filepath (str): path to birding configuration YAML file.
        default_loader (callable):
            callable which returns file descriptor with YAML data of default
            configuration values
        on_missing (callable): callback to call when file is missing.

Returns:
        dict: dict of current birding configuration; treat as read-only.


def connect(self, component):
    if (not isinstance(component, ThreadPool)):
        raise TypeError('"component" must be a ThreadPool object')
    component.in_queue = self.out_queue
    return component

Connect two ThreadPools.

    The ``in_queue`` of the second pool will be set as the ``out_queue`` of
    the current pool, thus all the output will be input to the second pool.

Args:
        component (ThreadPool): the ThreadPool to be connected.

Returns:
        ThreadPool: the modified second ThreadPool.


def as_tuning_range(self, name):
    return {'Name': name, 'MinValue': to_str(self.min_value), 'MaxValue': to_str(self.max_value), 'ScalingType': self.scaling_type}

Represent the parameter range as a dicionary suitable for a request to
    create an Amazon SageMaker hyperparameter tuning job.

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

Returns:
        dict[str, str]: A dictionary that contains the name and values of the hyperparameter.


def success(channel, title, datapacks):
    gui = ui_embed.UI(channel, title, '', modulename=modulename, datapacks=datapacks)
    return gui

Creates an embed UI containing the help message

Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        title (str): The title of the embed
        datapacks (list): The hex value

Returns:
        ui (ui_embed.UI): The embed UI object


def post(self, url, data=None, files=None, headers=None, get_json=True):
    if self.debug:
        print(('POST: %s, headers=%s' % (url, headers)))
    self.headers = self._get_default_headers()
    if (headers is not None):
        self.headers.update(headers)
    response = requests.post(url, headers=self.headers, data=data, auth=self.auth, files=files, verify=self.verify_ssl)
    json_response = self._process_json_response(response)
    return (json_response if (get_json is True) else response)

Make POST request to a url

Args:
        url (str): URL to send the request to
        data (dict, optional): Data to send
        files (dict, optional): Files to send with the request
        headers (str, optional): custom headers

Returns:
        A JSON object of the returned response if `get_json` is True,
        Requests' response object otherwise


def _VerifyRecord(self, pls_record):
    future_timestamp = (timelib.Timestamp.GetNow() + self._SIX_YEARS_IN_MICRO_SECONDS)
    if (pls_record.last_written_time > future_timestamp):
        return False
    (first_word, _, _) = pls_record.query.partition(' ')
    if (first_word.lower() not in self._PLS_KEYWORD):
        return False
    return True

Verifies a PLS Recall record.

Args:
        pls_record (pls_recall_record): a PLS Recall record to verify.

Returns:
        bool: True if this is a valid PLS Recall record, False otherwise.


def generate_pseudo(strain_states, order=3):
    s = sp.Symbol('s')
    nstates = len(strain_states)
    ni = (np.array(strain_states) * s)
    (mis, absent_syms) = ([], [])
    for degree in range(2, (order + 1)):
        (cvec, carr) = get_symbol_list(degree)
        sarr = np.zeros((nstates, 6), dtype=object)
        for (n, strain_v) in enumerate(ni):
            exps = carr.copy()
            for i in range((degree - 1)):
                exps = np.dot(exps, strain_v)
            exps /= np.math.factorial((degree - 1))
            sarr[n] = [sp.diff(exp, s, (degree - 1)) for exp in exps]
        svec = sarr.ravel()
        present_syms = set.union(*[exp.atoms(sp.Symbol) for exp in svec])
        absent_syms += [(set(cvec) - present_syms)]
        m = np.zeros(((6 * nstates), len(cvec)))
        for (n, c) in enumerate(cvec):
            m[(:, n)] = v_diff(svec, c)
        mis.append(np.linalg.pinv(m))
    return (mis, absent_syms)

Generates the pseudoinverse for a given set of strains.

Args:
        strain_states (6xN array like): a list of voigt-notation
            "strain-states", i. e. perturbed indices of the strain
            as a function of the smallest strain e. g. (0, 1, 0, 0, 1, 0)
        order (int): order of pseudoinverse to calculate

Returns:
        mis: pseudo inverses for each order tensor, these can
            be multiplied by the central difference derivative
            of the stress with respect to the strain state
        absent_syms: symbols of the tensor absent from the PI
            expression


def load_local_config(filename):
    if (not filename):
        return imp.new_module('local_pylint_config')
    module = imp.load_source('local_pylint_config', filename)
    return module

Loads the pylint.config.py file.

Args:
        filename (str): The python file containing the local configuration.

Returns:
        module: The loaded Python module.


def first_return_times(dts, c=None, d=0.0):
    if (c is None):
        c = dts.mean()
    vmrt = distob.vectorize(analyses1.first_return_times)
    all_intervals = vmrt(dts, c, d)
    if hasattr(type(all_intervals), '__array_interface__'):
        return np.ravel(all_intervals)
    else:
        return np.hstack([distob.gather(ilist) for ilist in all_intervals])

For an ensemble of time series, return the set of all time intervals
    between successive returns to value c for all instances in the ensemble.
    If c is not given, the default is the mean across all times and across all
    time series in the ensemble.

Args:
        dts (DistTimeseries)

        c (float): Optional target value (default is the ensemble mean value)

        d (float): Optional min distance from c to be attained between returns

Returns:
        array of time intervals (Can take the mean of these to estimate the
        expected first return time for the whole ensemble)


def save(self, clean=True):
    ret = {}
    if clean:
        self._dirty = False
    else:
        ret['_dirty'] = self._dirty
    return ret

Serialize into raw representation. Clears the dirty bit by default.

Args:
        clean (bool): Whether to clear the dirty bit.

Returns:
        dict: Raw.


def _merge_bee(self, bee):
    random_dimension = randint(0, (len(self._value_ranges) - 1))
    second_bee = randint(0, (self._num_employers - 1))
    while (bee.id == self._employers[second_bee].id):
        second_bee = randint(0, (self._num_employers - 1))
    new_bee = deepcopy(bee)
    new_bee.values[random_dimension] = self.__onlooker.calculate_positions(new_bee.values[random_dimension], self._employers[second_bee].values[random_dimension], self._value_ranges[random_dimension])
    fitness_score = new_bee.get_score(self._fitness_fxn(new_bee.values, **self._args))
    return (fitness_score, new_bee.values, new_bee.error)

Shifts a random value for a supplied bee with in accordance with
    another random bee's value

Args:
        bee (EmployerBee): supplied bee to merge

Returns:
        tuple: (score of new position, values of new position, fitness
            function return value of new position)


def from_string(cls, key, key_id=None):
    key = _helpers.from_bytes(key)
    (marker_id, key_bytes) = pem.readPemBlocksFromFile(six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)
    if (marker_id == 0):
        private_key = rsa.key.PrivateKey.load_pkcs1(key_bytes, format='DER')
    elif (marker_id == 1):
        (key_info, remaining) = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
        if (remaining != b''):
            raise ValueError('Unused bytes', remaining)
        private_key_info = key_info.getComponentByName('privateKey')
        private_key = rsa.key.PrivateKey.load_pkcs1(private_key_info.asOctets(), format='DER')
    else:
        raise ValueError('No key could be detected.')
    return cls(private_key, key_id=key_id)

Construct an Signer instance from a private key in PEM format.

Args:
        key (str): Private key in PEM format.
        key_id (str): An optional key id used to identify the private key.

Returns:
        google.auth.crypt.Signer: The constructed signer.

Raises:
        ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in
            PEM format.


def _bash_comp_command(self, cmd, add_help=True):
    out = (['-h', '--help'] if add_help else [])
    cmd_dict = (self._opt_cmds[cmd] if cmd else self._opt_bare)
    for (opt, sct) in cmd_dict:
        out.extend(_names(self._conf[sct], opt))
    return out

Build a list of all options for a given command.

Args:
        cmd (str): command name, set to None or '' for bare command.
        add_help (bool): add an help option.

Returns:
        list of str: list of CLI options strings.


def json_to_bulk(tc_data, value_fields, resource_type, resource_type_parent):
    if (not isinstance(tc_data, list)):
        tc_data = [tc_data]
    bulk_array = []
    for d in tc_data:
        values = []
        for field in value_fields:
            if (d.get(field) is not None):
                values.append(d.get(field))
                del d[field]
        if (resource_type_parent in ['Group', 'Task', 'Victim']):
            d['name'] = ' : '.join(values)
        elif (resource_type_parent in ['Indicator']):
            d['summary'] = ' : '.join(values)
        if ('owner' in d):
            d['ownerName'] = d['owner']['name']
            del d['owner']
        if (d.get('type') is None):
            d['type'] = resource_type
        bulk_array.append(d)
    return bulk_array

Convert ThreatConnect JSON response to a Bulk Format.

    .. 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 dictionary representing a TCEntityArray


def cidr(self, block, **kwargs):
    indicator_obj = CIDR(block, **kwargs)
    return self._indicator(indicator_obj)

Add CIDR data to Batch object.

Args:
        block (str): The value for this Indicator.
        confidence (str, kwargs): The threat confidence for this Indicator.
        date_added (str, kwargs): The date timestamp the Indicator was created.
        last_modified (str, kwargs): The date timestamp the Indicator was last modified.
        rating (str, kwargs): The threat rating for this Indicator.
        xid (str, kwargs): The external id for this Indicator.

Returns:
        obj: An instance of CIDR.


def get_single_item_from_sequence(sequence, condition, ErrorClass=ValueError, no_item_error_message='No item matched condition', too_many_item_error_message='Too many items matched condition', append_sequence_to_error_message=True):
    filtered_sequence = [item for item in sequence if condition(item)]
    number_of_items_in_filtered_sequence = len(filtered_sequence)
    if (number_of_items_in_filtered_sequence == 0):
        error_message = no_item_error_message
    elif (number_of_items_in_filtered_sequence > 1):
        error_message = too_many_item_error_message
    else:
        return filtered_sequence[0]
    if append_sequence_to_error_message:
        error_message = '{}. Given: {}'.format(error_message, sequence)
    raise ErrorClass(error_message)

Return an item from a python sequence based on the given condition.

Args:
        sequence (sequence): The sequence to filter
        condition: A function that serves to filter items from `sequence`. Function
            must have one argument (a single item from the sequence) and return a boolean.
        ErrorClass (Exception): The error type raised in case the item isn't unique
        no_item_error_message (str): The message raised when no item matched the condtion
        too_many_item_error_message (str): The message raised when more than one item matched the condition
        append_sequence_to_error_message (bool): Show or hide what was the tested sequence in the error message.
            Hiding it may prevent sensitive data (such as password) to be exposed to public logs

Returns:
        The only item in the sequence which matched the condition


def _run(self, data, store, signal, context, *, success_callback=None, stop_callback=None, abort_callback=None):
    if (data is None):
        data = MultiTaskData()
        data.add_dataset(self._name)
    try:
        if (self._callback_init is not None):
            self._callback_init(data, store, signal, context)
        result = self.run(data, store, signal, context)
        if (self._callback_finally is not None):
            self._callback_finally(TaskStatus.Success, data, store, signal, context)
        if (success_callback is not None):
            success_callback()
    except StopTask as err:
        if (self._callback_finally is not None):
            self._callback_finally(TaskStatus.Stopped, data, store, signal, context)
        if (stop_callback is not None):
            stop_callback(exc=err)
        result = (Action(data, limit=[]) if err.skip_successors else None)
    except AbortWorkflow as err:
        if (self._callback_finally is not None):
            self._callback_finally(TaskStatus.Aborted, data, store, signal, context)
        if (abort_callback is not None):
            abort_callback(exc=err)
        result = None
        signal.stop_workflow()
    except:
        if (self._callback_finally is not None):
            self._callback_finally(TaskStatus.Error, data, store, signal, context)
        signal.stop_workflow()
        raise
    if (result is None):
        data.flatten(in_place=True)
        data.add_task_history(self.name)
        return Action(data)
    else:
        if (not isinstance(result, Action)):
            raise TaskReturnActionInvalid()
        result.data.flatten(in_place=True)
        result.data.add_task_history(self.name)
        return result

The internal run method that decorates the public run method.

    This method makes sure data is being passed to and from the task.

Args:
        data (MultiTaskData): The data object that has been passed from the
                            predecessor task.
        store (DataStoreDocument): The persistent data store object that allows the
                                task to store data for access across the current
                                workflow run.
        signal (TaskSignal): The signal object for tasks. It wraps the construction
                            and sending of signals into easy to use methods.
        context (TaskContext): The context in which the tasks runs.
        success_callback: This function is called when the task completed successfully
        stop_callback: This function is called when a StopTask exception was raised.
        abort_callback: This function is called when an AbortWorkflow exception
                        was raised.

Raises:
        TaskReturnActionInvalid: If the return value of the task is not
                                an Action object.

Returns:
        Action: An Action object containing the data that should be passed on
                to the next task and optionally a list of successor tasks that
                should be executed.


def array_to_csv(array_like):
    stream = StringIO()
    np.savetxt(stream, array_like, delimiter=',', fmt='%s')
    return stream.getvalue()

Convert an array like object to CSV.

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

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

Returns:
        (str): object serialized to CSV


def helper_add(access_token, ck_id, path, body):
    full_path = ''.join([path, "('", ck_id, "')"])
    full_path_encoded = urllib.parse.quote(full_path, safe='')
    endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
    return do_ams_put(endpoint, full_path_encoded, body, access_token, 'json_only', '1.0;NetFx')

Helper Function to add strings to a URL path.

Args:
        access_token (str): A valid Azure authentication token.
        ck_id (str): A CK ID.
        path (str): A URL Path.
        body (str): A Body.

Returns:
        HTTP response. JSON body.


def trace_flush(self):
    cmd = enums.JLinkTraceCommand.FLUSH
    res = self._dll.JLINKARM_TRACE_Control(cmd, 0)
    if (res == 1):
        raise errors.JLinkException('Failed to flush the trace buffer.')
    return None

Flushes the trace buffer.

    After this method is called, the trace buffer is empty.  This method is
    best called when the device is reset.

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

Returns:
        ``None``


def zip_ll_row(params, data_row):
    l = params[0]
    pi = params[1]
    d0 = (data_row == 0)
    likelihood = ((d0 * pi) + ((1 - pi) * poisson.pmf(data_row, l)))
    return (- np.log((likelihood + eps)).sum())

Returns the negative log-likelihood of a row given ZIP data.

Args:
        params (list): [lambda zero-inf]
        data_row (array): 1d array

Returns:
        negative log-likelihood


def angle(x, y):
    dot = np.dot(x, y)
    x_mod = np.linalg.norm(x)
    y_mod = np.linalg.norm(y)
    cos_angle = (dot / (x_mod * y_mod))
    return np.degrees(np.arccos(cos_angle))

Calculate the angle between two vectors, in degrees.

Args:
        x (np.array): one vector.
        y (np.array): the other vector.

Returns:
        (float):      the angle between x and y in degrees.


def compare(a, b):
    a_is_text = isinstance(a, basestring)
    b_is_text = isinstance(b, basestring)
    if ((type(a) != type(b)) and (not (a_is_text and b_is_text))):
        _logger.error(u'Cannot compare %s to %s, types differ %s!=%s', a, b, type(a), type(b))
        raise ValueError(u'cannot compare inputs of differing types')
    if a_is_text:
        a = from_rfc3339(a, with_nanos=True)
        b = from_rfc3339(b, with_nanos=True)
    if (a < b):
        return (- 1)
    elif (a > b):
        return 1
    else:
        return 0

Compares two timestamps.

    ``a`` and ``b`` must be the same type, in addition to normal
    representations of timestamps that order naturally, they can be rfc3339
    formatted strings.

Args:
        a (string|object): a timestamp
        b (string|object): another timestamp

Returns:
        int: -1 if a < b, 0 if a == b or 1 if a > b

Raises:
        ValueError: if a or b are not the same type
        ValueError: if a or b strings but not in valid rfc3339 format


def pandas_mesh(df):
    xyz = [df[c].values for c in df.columns]
    index = pd.MultiIndex.from_tuples(zip(xyz[0], xyz[1]), names=['x', 'y'])
    series = [pd.Series(values, index=index) for values in xyz[2:]]
    (X, Y) = np.meshgrid(sorted(list(set(xyz[0]))), sorted(list(set(xyz[1]))))
    (N, M) = X.shape
    Zs = []
    for (k, s) in enumerate(series):
        Z = np.empty(X.shape)
        Z[:] = np.nan
        for (i, j) in itertools.product(range(N), range(M)):
            Z[(i, j)] = s.get((X[(i, j)], Y[(i, j)]), np.NAN)
        Zs += [Z]
    return OrderedDict(((df.columns[i], m) for (i, m) in enumerate(([X, Y] + Zs))))

Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame

Args:
        df (DataFrame): Must have 3 or 4 columns of numerical data

Returns:
        OrderedDict: column labels from the data frame are the keys, values are 2-D matrices
        All matrices have shape NxM, where N = len(set(df.iloc[:,0])) and M = len(set(df.iloc[:,1]))

    >>> pandas_mesh(pd.DataFrame(np.arange(18).reshape(3,6),
    ...                          columns=list('ABCDEF'))).values()  # doctest: +NORMALIZE_WHITESPACE
    [array([[ 0,  6, 12],
            [ 0,  6, 12],
            [ 0,  6, 12]]),
    array([[ 1,  1,  1],
            [ 7,  7,  7],
            [13, 13, 13]]),
    array([[  2.,  nan,  nan],
            [ nan,   8.,  nan],
            [ nan,  nan,  14.]]),
    array([[  3.,  nan,  nan],
            [ nan,   9.,  nan],
            [ nan,  nan,  15.]]),
    array([[  4.,  nan,  nan],
            [ nan,  10.,  nan],
            [ nan,  nan,  16.]]),
    array([[  5.,  nan,  nan],
            [ nan,  11.,  nan],
            [ nan,  nan,  17.]])]


def get_dc_keywords(index_page):
    keyword_lists = (keyword_list.split() for keyword_list in parse_meta(index_page, 'dc.keywords', 'DC'))
    return [SourceString(keyword, source='DC') for keyword in sum(keyword_lists, [])]

Return list of `keywords` parsed from Dublin core.

Args:
        index_page (str): Content of the page as UTF-8 string

Returns:
        list: List of :class:`.SourceString` objects.


def disassemble(self, annotate=False, blocks=False):
    ops = disassemble(self.co_code, self.internals)
    if annotate:
        ops = [self.annotate_op(op) for op in ops]
    if blocks:
        return blocks_from_ops(ops)
    else:
        return ops

Disassemble the bytecode of this code object into a series of
    opcodes and labels. Can also annotate the opcodes and group
    the opcodes into blocks based on the labels.

Args:
        annotate(bool): Whether to annotate the operations.
        blocks(bool): Whether to group the operations into blocks.

Returns:
        list: A list of :class:`Op` (or :class:`AnnotatedOp`) instances
        and labels.


def grab_data(self, f_start=None, f_stop=None, t_start=None, t_stop=None, if_id=0):
    self.freqs = self.populate_freqs()
    self.timestamps = self.populate_timestamps()
    if (f_start is None):
        f_start = self.freqs[0]
    if (f_stop is None):
        f_stop = self.freqs[(- 1)]
    i0 = np.argmin(np.abs((self.freqs - f_start)))
    i1 = np.argmin(np.abs((self.freqs - f_stop)))
    if (i0 < i1):
        plot_f = self.freqs[i0:(i1 + 1)]
        plot_data = np.squeeze(self.data[(t_start:t_stop, ..., i0:(i1 + 1))])
    else:
        plot_f = self.freqs[i1:(i0 + 1)]
        plot_data = np.squeeze(self.data[(t_start:t_stop, ..., i1:(i0 + 1))])
    return (plot_f, plot_data)

Extract a portion of data by frequency range.

Args:
        f_start (float): start frequency in MHz
        f_stop (float): stop frequency in MHz
        if_id (int): IF input identification (req. when multiple IFs in file)

Returns:
        (freqs, data) (np.arrays): frequency axis in MHz and data subset


def is_in_path(program):
    if (sys.version_info.major == 2):
        path = os.getenv('PATH')
        if (os.name == 'nt'):
            path = path.split(';')
        else:
            path = path.split(':')
    else:
        path = os.get_exec_path()
    for i in path:
        if os.path.isdir(i):
            if (program in os.listdir(i)):
                return True

Check if a program is in the system ``PATH``.

    Checks if a given program is in the user's ``PATH`` or not.

Args:
        program (str): The program to try to find in ``PATH``.

Returns:
        bool: Is the program in ``PATH``?


def verified(self, institute_id):
    query = {'verb': 'validate', 'institute': institute_id}
    res = []
    validate_events = self.event_collection.find(query)
    for validated in list(validate_events):
        case_id = validated['case']
        var_obj = self.variant(case_id=case_id, document_id=validated['variant_id'])
        case_obj = self.case(case_id=case_id)
        if ((not case_obj) or (not var_obj)):
            continue
        var_obj['case_obj'] = {'display_name': case_obj['display_name'], 'individuals': case_obj['individuals']}
        res.append(var_obj)
    return res

Return all verified variants for a given institute

Args:
        institute_id(str): institute id

Returns:
        res(list): a list with validated variants


def detailed_log_handler(self, handler):
    if (not self.opened()):
        handler = (handler or util.noop)
        self._detailed_log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
        self._dll.JLINKARM_EnableLogCom(self._detailed_log_handler)

Setter for the detailed log handler function.

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

Returns:
        ``None``


def crack(ciphertext, *fitness_functions, min_key=0, max_key=26, shift_function=shift_case_english):
    if (min_key >= max_key):
        raise ValueError('min_key cannot exceed max_key')
    decryptions = []
    for key in range(min_key, max_key):
        plaintext = decrypt(key, ciphertext, shift_function=shift_function)
        decryptions.append(Decryption(plaintext, key, score(plaintext, *fitness_functions)))
    return sorted(decryptions, reverse=True)

Break ``ciphertext`` by enumerating keys between ``min_key`` and ``max_key``.

Example:
        >>> decryptions = crack("KHOOR", fitness.english.quadgrams)
        >>> print(''.join(decryptions[0].plaintext))
        HELLO

Args:
        ciphertext (iterable): The symbols to decrypt
        *fitness_functions (variable length argument list): Functions to score decryption with

    Keyword Args:
        min_key (int): Key to start with
        max_key (int): Key to stop at (exclusive)
        shift_function (function(shift, symbol)): Shift function to use

Returns:
        Sorted list of decryptions

Raises:
        ValueError: If min_key exceeds max_key
        ValueError: If no fitness_functions are given


def sort_dict(d, desc=True):
    sort = sorted(d.items(), key=(lambda x: x[1]), reverse=desc)
    return OrderedDict(sort)

Sort an ordered dictionary by value, descending.

Args:
        d (OrderedDict): An ordered dictionary.
        desc (bool): If true, sort desc.

Returns:
        OrderedDict: The sorted dictionary.


def marginalize_out(node_indices, tpm):
    return (tpm.sum(tuple(node_indices), keepdims=True) / np.array(tpm.shape)[list(node_indices)].prod())

Marginalize out nodes from a TPM.

Args:
        node_indices (list[int]): The indices of nodes to be marginalized out.
        tpm (np.ndarray): The TPM to marginalize the node out of.

Returns:
        np.ndarray: A TPM with the same number of dimensions, with the nodes
        marginalized out.


def sampler(dataframe, modulo, column='client_id', sample_id=42):
    return dataframe.withColumn('sampler', udf((lambda key: ((crc32((key or '')) & 4294967295) % modulo)))(column)).where(('sampler = %s' % sample_id)).drop('sampler')

Collect a sample of clients given an input column

    Filter dataframe based on the modulus of the CRC32 of a given string
    column matching a given sample_id. if dataframe has already been filtered
    by sample_id, then modulo should be a multiple of 100, column should be
    "client_id", and the given sample_id should match the value previously
    used, optionally plus multiples of 100.

Args:
        dataframe: A Dataframe to be sampled
        modulo (int): selects a 1/modulo sampling of dataframe
        column (str): name of a string column to sample on
        sample_id (int): modulus result to select for sampling

Returns:
        A DataFrame sampled on the given inputs.


def _send_message(self, method, endpoint, params=None, data=None):
    url = (self.url + endpoint)
    r = self.session.request(method, url, params=params, data=data, auth=self.auth, timeout=30)
    return r.json()

Send API request.

Args:
        method (str): HTTP method (get, post, delete, etc.)
        endpoint (str): Endpoint (to be added to base URL)
        params (Optional[dict]): HTTP request parameters
        data (Optional[str]): JSON-encoded string payload for POST

Returns:
        dict/list: JSON response


def delete_resource_view(self, resource_view):
    if isinstance(resource_view, str):
        if (is_valid_uuid(resource_view) is False):
            raise HDXError(('%s is not a valid resource view id!' % resource_view))
        resource_view = ResourceView({'id': resource_view}, configuration=self.configuration)
    else:
        resource_view = self._get_resource_view(resource_view)
        if ('id' not in resource_view):
            found = False
            title = resource_view.get('title')
            for rv in self.get_resource_views():
                if (resource_view['title'] == rv['title']):
                    resource_view = rv
                    found = True
                    break
            if (not found):
                raise HDXError(('No resource views have title %s in this resource!' % title))
    resource_view.delete_from_hdx()

Delete a resource view from the resource and HDX

Args:
        resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary

Returns:
        None


def xmoe2_dense(sz):
    hparams = mtf_transformer.mtf_transformer_paper_lm(sz)
    hparams.attention_dropout = 0.0
    hparams.relu_dropout = 0.0
    hparams.layer_prepostprocess_dropout = 0.0
    hparams.max_length = 1024
    hparams.batch_size = 128
    hparams.learning_rate_schedule = 'rsqrt_decay*linear_decay'
    hparams.learning_rate_decay_steps = 65536
    hparams.layout = 'batch:batch;vocab:model;d_ff:model;heads:model'
    hparams.mesh_shape = 'batch:32'
    return hparams

Series of architectural experiments on language modeling.

    Larger models than the ones above.

    All models are trained on sequences of 1024 tokens.

    We assume infinite training data, so no dropout necessary.
    We process 2^36 tokens in training = 524288 steps at batch size 128

    TODO(noam): find a large enough dataset for these experiments.

    You can use languagemodel_wiki_noref_v32k_l1k, but this is too small,
    (1 epoch = ~46000 steps) so training will cover about 11 epochs.

    Note: configurations and code are likely to change without notice.

    Run on TPU 4x4 for 524288 steps unless otherwise indicated.

Args:
        sz: an integer

Returns:
        a hparams


def macro_state(self, micro_state):
    assert (len(micro_state) == len(self.micro_indices))
    reindexed = self.reindex()
    micro_state = np.array(micro_state)
    return tuple(((0 if (sum(micro_state[list(reindexed.partition[i])]) in self.grouping[i][0]) else 1) for i in self.macro_indices))

Translate a micro state to a macro state

Args:
        micro_state (tuple[int]): The state of the micro nodes in this
            coarse-graining.

Returns:
        tuple[int]: The state of the macro system, translated as specified
        by this coarse-graining.

Example:
        >>> coarse_grain = CoarseGrain(((1, 2),), (((0,), (1, 2)),))
        >>> coarse_grain.macro_state((0, 0))
        (0,)
        >>> coarse_grain.macro_state((1, 0))
        (1,)
        >>> coarse_grain.macro_state((1, 1))
        (1,)


def api_request(self, method_name, params):
    url = self._method_url(method_name)
    data = json.dumps(params)
    return self._make_request(url=url, method='post', data=data)

Execute an arbitrary method.

Args:
        method_name (str): include the controller name: 'devices/search'
        params (dict): the method parameters

Returns:
        A dict with the response

Raises:
        requests.exceptions.HTTPError


def get_geno_marker(self, marker, return_index=False):
    if (self._mode != 'r'):
        raise UnsupportedOperation("not available in 'w' mode")
    if (marker not in self._bim.index):
        raise ValueError('{}: marker not in BIM'.format(marker))
    seek_index = self._bim.loc[(marker, 'i')]
    self.seek(seek_index)
    if return_index:
        return (self._read_current_marker(), seek_index)
    return self._read_current_marker()

Gets the genotypes for a given marker.

Args:
        marker (str): The name of the marker.
        return_index (bool): Wether to return the marker's index or not.

Returns:
        numpy.ndarray: The genotypes of the marker (additive format).


def get_product_order_book(self, product_id, level=1):
    params = {'level': level}
    return self._send_message('get', '/products/{}/book'.format(product_id), params=params)

Get a list of open orders for a product.

    The amount of detail shown can be customized with the `level`
    parameter:
    * 1: Only the best bid and ask
    * 2: Top 50 bids and asks (aggregated)
    * 3: Full order book (non aggregated)

    Level 1 and Level 2 are recommended for polling. For the most
    up-to-date data, consider using the websocket stream.

    **Caution**: Level 3 is only recommended for users wishing to
    maintain a full real-time order book using the websocket
    stream. Abuse of Level 3 via polling will cause your access to
    be limited or blocked.

Args:
        product_id (str): Product
        level (Optional[int]): Order book level (1, 2, or 3).
            Default is 1.

Returns:
        dict: Order book. Example for level 1::
            {
                "sequence": "3",
                "bids": [
                    [ price, size, num-orders ],
                ],
                "asks": [
                    [ price, size, num-orders ],
                ]
            }


def concat(cartesians, ignore_index=False, keys=None):
    frames = [molecule._frame for molecule in cartesians]
    new = pd.concat(frames, ignore_index=ignore_index, keys=keys, verify_integrity=True)
    if (type(ignore_index) is bool):
        new = pd.concat(frames, ignore_index=ignore_index, keys=keys, verify_integrity=True)
    else:
        new = pd.concat(frames, ignore_index=True, keys=keys, verify_integrity=True)
        if (type(ignore_index) is int):
            new.index = range(ignore_index, (ignore_index + len(new)))
        else:
            new.index = ignore_index
    return cartesians[0].__class__(new)

Join list of cartesians into one molecule.

    Wrapper around the :func:`pandas.concat` function.
    Default values are the same as in the pandas function except for
    ``verify_integrity`` which is set to true in case of this library.

Args:
        ignore_index (sequence, bool, int): If it is a boolean, it
            behaves like in the description of
            :meth:`pandas.DataFrame.append`.
            If it is a sequence, it becomes the new index.
            If it is an integer,
            ``range(ignore_index, ignore_index + len(new))``
            becomes the new index.
        keys (sequence): If multiple levels passed, should contain tuples.
            Construct hierarchical index using the passed keys as
            the outermost level

Returns:
        Cartesian:


def create_handler(Model, name=None, **kwds):

    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        if (action_type == get_crud_action('create', (name or Model))):
            try:
                message_props = {}
                if ('correlation_id' in props):
                    message_props['correlation_id'] = props['correlation_id']
                for requirement in Model.required_fields():
                    field_name = requirement.name
                    if ((not (field_name in payload)) and (field_name != 'id')):
                        raise ValueError(('Required field not found in payload: %s' % field_name))
                new_model = Model(**payload)
                new_model.save()
                if notify:
                    (await service.event_broker.send(payload=ModelSerializer().serialize(new_model), action_type=change_action_status(action_type, success_status()), **message_props))
            except Exception as err:
                if notify:
                    (await service.event_broker.send(payload=str(err), action_type=change_action_status(action_type, error_status()), **message_props))
                else:
                    raise err
    return action_handler

This factory returns an action handler that creates a new instance of
    the specified model when a create action is recieved, assuming the
    action follows nautilus convetions.

Args:
        Model (nautilus.BaseModel): The model to create when the action
            received.

Returns:
        function(action_type, payload): The action handler for this model


def has_access(user, required_roles, match_all=True):
    if (ROLE_ADMIN in user.roles):
        return True
    if isinstance(required_roles, str):
        if (required_roles in user.roles):
            return True
        return False
    if match_all:
        for role in required_roles:
            if (role not in user.roles):
                return False
        return True
    else:
        for role in required_roles:
            if (role in user.roles):
                return True
        return False

Check if the user meets the role requirements. If mode is set to AND, all the provided roles must apply

Args:
        user (:obj:`User`): User object
        required_roles (`list` of `str`): List of roles that the user must have applied
        match_all (`bool`): If true, all the required_roles must be applied to the user, else any one match will
        return `True`

Returns:
        `bool`


def dt_dt(sdat, tstart=None, tend=None):
    tseries = sdat.tseries_between(tstart, tend)
    time = tseries['t'].values
    temp = tseries['Tmean'].values
    dtdt = ((temp[1:] - temp[:(- 1)]) / (time[1:] - time[:(- 1)]))
    return (dtdt, time[:(- 1)])

Derivative of temperature.

    Compute dT/dt as a function of time using an explicit Euler scheme.

Args:
        sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
        tstart (float): time at which the computation should start. Use the
            beginning of the time series data if set to None.
        tend (float): time at which the computation should end. Use the
            end of the time series data if set to None.

Returns:
        tuple of :class:`numpy.array`: derivative of temperature and time
        arrays.


def getMonthsBuffer(self, direction):
    if (direction == ReadMonths.kWhReverse):
        return self.m_rev_mons
    return self.m_mons

Get the months tariff SerialBlock for meter.

Args:
        direction (int): A :class:`~ekmmeters.ReadMonths` value.

Returns:
        SerialBlock: Requested months tariffs buffer.


def Mint(self, wallet, mint_to_addr, attachment_args, invoke_attrs=None):
    invoke_args = [self.ScriptHash.ToString(), 'mintTokens', []]
    invoke_args = (invoke_args + attachment_args)
    (tx, fee, results, num_ops, engine_success) = TestInvokeContract(wallet, invoke_args, None, True, from_addr=mint_to_addr, invoke_attrs=invoke_attrs)
    return (tx, fee, results)

Call the "mintTokens" function of the smart contract.

Args:
        wallet (neo.Wallets.Wallet): a wallet instance.
        mint_to_addr (str): public address of the account to mint the tokens to.
        attachment_args: (list): a list of arguments used to attach neo and/or gas to an invoke, eg ['--attach-gas=10.0','--attach-neo=3']
        invoke_attrs: (list): a list of TransactionAttributes to be attached to the mint transaction

Returns:
        tuple:
            InvocationTransaction: the transaction.
            int: the transaction fee.
            list: the neo VM evaluation stack results.


def exhaust(fn, transform=None, *args, **kwargs):
    while True:
        iterRes = fn(*args, **kwargs)
        if iterRes:
            for item in (transform(iterRes) if transform else iterRes):
                (yield item)
        else:
            break

Repeatedly call a function, starting with init, until false-y, yielding each item in turn.

    The ``transform`` parameter can be used to map a collection to another format, for example iterating over a
    :class:`dict` by value rather than key.

    Use with state-synced functions to retrieve all results.

Args:
        fn (method): function to call
        transform (method): secondary function to convert result into an iterable
        args (list): positional arguments to pass to ``fn``
        kwargs (dict): keyword arguments to pass to ``fn``

Returns:
        generator: generator of objects produced from the method


def set_trunk_groups(self, vid, value=None, default=False, disable=False):
    if default:
        return self.configure_vlan(vid, 'default trunk group')
    if disable:
        return self.configure_vlan(vid, 'no trunk group')
    current_value = self.get(vid)['trunk_groups']
    failure = False
    value = make_iterable(value)
    for name in set(value).difference(current_value):
        if (not self.add_trunk_group(vid, name)):
            failure = True
    for name in set(current_value).difference(value):
        if (not self.remove_trunk_group(vid, name)):
            failure = True
    return (not failure)

Configures the list of trunk groups support on a vlan

    This method handles configuring the vlan trunk group value to default
    if the default flag is set to True.  If the default flag is set
    to False, then this method will calculate the set of trunk
    group names to be added and to be removed.

    EosVersion:
        4.13.7M

Args:
        vid (str): The VLAN ID to configure
        value (str): The list of trunk groups that should be configured
            for this vlan id.
        default (bool): Configures the trunk group value to default if
            this value is true
        disable (bool): Negates the trunk group value if set to true

Returns:
        True if the operation was successful otherwise False


def get_surface_sites(self, tag=False):
    from pymatgen.analysis.local_env import VoronoiNN
    a = SpacegroupAnalyzer(self.oriented_unit_cell)
    ucell = a.get_symmetrized_structure()
    cn_dict = {}
    v = VoronoiNN()
    unique_indices = [equ[0] for equ in ucell.equivalent_indices]
    for i in unique_indices:
        el = ucell[i].species_string
        if (el not in cn_dict.keys()):
            cn_dict[el] = []
        cn = v.get_cn(ucell, i, use_weights=True)
        cn = float(('%.5f' % round(cn, 5)))
        if (cn not in cn_dict[el]):
            cn_dict[el].append(cn)
    v = VoronoiNN()
    (surf_sites_dict, properties) = ({'top': [], 'bottom': []}, [])
    for (i, site) in enumerate(self):
        top = (True if (site.frac_coords[2] > self.center_of_mass[2]) else False)
        try:
            cn = float(('%.5f' % round(v.get_cn(self, i, use_weights=True), 5)))
            if (cn < min(cn_dict[site.species_string])):
                properties.append(True)
                key = ('top' if top else 'bottom')
                surf_sites_dict[key].append([site, i])
            else:
                properties.append(False)
        except RuntimeError:
            properties.append(True)
            key = ('top' if top else 'bottom')
            surf_sites_dict[key].append([site, i])
    if tag:
        self.add_site_property('is_surf_site', properties)
    return surf_sites_dict

Returns the surface sites and their indices in a dictionary. The
    oriented unit cell of the slab will determine the coordination number
    of a typical site. We use VoronoiNN to determine the
    coordination number of bulk sites and slab sites. Due to the
    pathological error resulting from some surface sites in the
    VoronoiNN, we assume any site that has this error is a surface
    site as well. This will work for elemental systems only for now. Useful
    for analysis involving broken bonds and for finding adsorption sites.

Args:
            tag (bool): Option to adds site attribute "is_surfsite" (bool)
                to all sites of slab. Defaults to False

Returns:
            A dictionary grouping sites on top and bottom of the slab
            together.
            {"top": [sites with indices], "bottom": [sites with indices}

    TODO:
        Is there a way to determine site equivalence between sites in a slab
        and bulk system? This would allow us get the coordination number of
        a specific site for multi-elemental systems or systems with more
        than one unequivalent site. This will allow us to use this for
        compound systems.


def inputs_valid(self, outputs=None):
    if (self.operation == Transaction.CREATE):
        return self._inputs_valid(['dummyvalue' for _ in self.inputs])
    elif (self.operation == Transaction.TRANSFER):
        return self._inputs_valid([output.fulfillment.condition_uri for output in outputs])
    else:
        allowed_ops = ', '.join(self.__class__.ALLOWED_OPERATIONS)
        raise TypeError('`operation` must be one of {}'.format(allowed_ops))

Validates the Inputs in the Transaction against given
    Outputs.

Note:
            Given a `CREATE` Transaction is passed,
            dummy values for Outputs are submitted for validation that
            evaluate parts of the validation-checks to `True`.

Args:
            outputs (:obj:`list` of :class:`~bigchaindb.common.
                transaction.Output`): A list of Outputs to check the
                Inputs against.

Returns:
            bool: If all Inputs are valid.


def memory_write32(self, addr, data, zone=None):
    return self.memory_write(addr, data, zone, 32)

Writes words to memory of a target system.

Args:
        self (JLink): the ``JLink`` instance
        addr (int): start address to write to
        data (list): list of words to write
        zone (str): optional memory zone to access

Returns:
        Number of words written to target.

Raises:
        JLinkException: on memory access error.


def __checkDecisionParameters(self, result, **values):
    error = []
    if (not result):
        error.append('Function parameter (result array) should contain one or more header string!')
    if (not values):
        error.append('Function parameter (values variables) should contain one or more variable')
    for header in result:
        if (not (header in self.header)):
            error.append((('String (' + header) + ') in result is not in header!'))
    for header in values:
        if (not (header in self.header)):
            error.append((('Variable (' + header) + ') in values is not in header!'))
        elif (not values[header].split()):
            error.append((('Variable (' + header) + ') in values is empty string'))
    if error:
        return error

Checker of decision parameters, it will raise ValueError if finds something wrong.

Args:
    result (array of str): See public decision methods
    **values (array of str): See public decision methods

Raises:
    ValueError: Result array none.
    ValueError: Values dict none.
    ValueError: Not find result key in header.
    ValueError: Result value is empty.

Returns:
    Error array values


def get_proj(prj_code):
    if (prj_code in CUSTOM_PRJ):
        proj = pyproj.Proj(CUSTOM_PRJ[prj_code])
    else:
        proj = pyproj.Proj(init=prj_code)
    return proj

Helper method for handling projection codes that are unknown to pyproj

Args:
        prj_code (str): an epsg proj code

Returns:
        projection: a pyproj projection


def signCertAs(self, cert, signas):
    cakey = self.getCaKey(signas)
    if (cakey is None):
        raise s_exc.NoCertKey(('Missing .key for %s' % signas))
    cacert = self.getCaCert(signas)
    if (cacert is None):
        raise s_exc.NoCertKey(('Missing .crt for %s' % signas))
    cert.set_issuer(cacert.get_subject())
    cert.sign(cakey, self.signing_digest)

Signs a certificate with a CA keypair.

Args:
        cert (OpenSSL.crypto.X509): The certificate to sign.
        signas (str): The CA keypair name to sign the new keypair with.

Example:
        Sign a certificate with the CA "myca":

            cdir.signCertAs(mycert, 'myca')

Returns:
        None


def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
    gradients = (((np.array(make_gradients(dims)) - offset) * scale) * np.pi)
    return np.sin(np.linalg.norm(gradients, axis=0))

Makes a surface from the 3D sine function.

Args:
        dims (pair): the dimensions of the surface to create
        offset (float): an offset applied to the function
        scale (float): a scale applied to the sine frequency

Returns:
        surface: A surface.


def fit_transform(self, tables=None, transformer_dict=None, transformer_list=None, missing=None):
    if (missing is None):
        missing = self.missing
    else:
        self.missing = missing
        warnings.warn(DEPRECATION_MESSAGE.format('fit_transform'), DeprecationWarning)
    transformed = {}
    if (tables is None):
        tables = self.table_dict
    if ((transformer_dict is None) and (transformer_list is None)):
        transformer_dict = self.transformer_dict
    for table_name in tables:
        (table, table_meta) = tables[table_name]
        transformed_table = self.fit_transform_table(table, table_meta, transformer_dict, transformer_list)
        transformed[table_name] = transformed_table
    return transformed

Create, apply and store the specified transformers for the given tables.

Args:
        tables(dict):   Mapping of table names to `tuple` where each tuple is on the form
                        (`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data
                        and the `dict` the corresponding meta information.
                        If not specified, the tables will be retrieved using the meta_file.

        transformer_dict(dict):     Mapping  `tuple(str, str)` -> `str` where the tuple is
                                    (table_name, column_name).

        transformer_list(list):     List of transformers to use. Overrides the transformers in
                                    the meta_file.

        missing(bool):      Wheter or not use NullTransformer to handle missing values.

Returns:
        dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).


def google_maps_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
    loc = ('%s,%s' % (lat, lon))
    return ('https://www.google.com/maps/place/@%s,17z/data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d%s' % (loc, lat, lon))

Get a link to google maps pointing on this IP's geolocation.

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

Returns:
        str: a link to google maps pointing on this IP's geolocation.


def get_extra_managed_storage_volume_paths(self, start=0, count=(- 1), filter='', sort=''):
    uri = (self.URI + '/repair?alertFixType=ExtraManagedStorageVolumePaths')
    return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri)

Gets the list of extra managed storage volume paths.

Args:
        start:
            The first item to return, using 0-based indexing.
            If not specified, the default is 0 - start with the first available item.
        count:
            The number of resources to return. A count of -1 requests all items.
            The actual number of items in the response might differ from the requested
            count if the sum of start and count exceeds the total number of items.
        filter (list or str):
            A general filter/query string to narrow the list of items returned. The
            default is no filter; all resources are returned.
        sort:
            The sort order of the returned data set. By default, the sort order is based
            on create time with the oldest entry first.

Returns:
        list: A list of extra managed storage volume paths.


def __batch_evaluate(self, test_events):
    percentiles = np.zeros(len(test_events))
    all_items = set(self.item_buffer)
    for (i, e) in enumerate(test_events):
        unobserved = all_items
        if (not self.repeat):
            unobserved -= self.rec.users[e.user.index]['known_items']
            unobserved.add(e.item.index)
        candidates = np.asarray(list(unobserved))
        (recos, scores) = self.__recommend(e, candidates)
        pos = np.where((recos == e.item.index))[0][0]
        percentiles[i] = ((pos / (len(recos) - 1)) * 100)
    return np.mean(percentiles)

Evaluate the current model by using the given test events.

Args:
        test_events (list of Event): Current model is evaluated by these events.

Returns:
        float: Mean Percentile Rank for the test set.


def bootstrap(score_objs, n_boot=1000):
    all_samples = np.random.choice(score_objs, size=(n_boot, len(score_objs)), replace=True)
    return all_samples.sum(axis=1)

Given a set of DistributedROC or DistributedReliability objects, this function performs a
    bootstrap resampling of the objects and returns n_boot aggregations of them.

Args:
        score_objs: A list of DistributedROC or DistributedReliability objects. Objects must have an __add__ method
        n_boot (int): Number of bootstrap samples

Returns:
        An array of DistributedROC or DistributedReliability


def __cloudflare_request(self, *, account, path, args=None):
    if (not args):
        args = {}
    if (not self.cloudflare_initialized[account.account_id]):
        self.cloudflare_session[account.account_id] = requests.Session()
        self.cloudflare_session[account.account_id].headers.update({'X-Auth-Email': account.email, 'X-Auth-Key': account.api_key, 'Content-Type': 'application/json'})
        self.cloudflare_initialized[account.account_id] = True
    if ('per_page' not in args):
        args['per_page'] = 100
    response = self.cloudflare_session[account.account_id].get((account.endpoint + path), params=args)
    if (response.status_code != 200):
        raise CloudFlareError('Request failed: {}'.format(response.text))
    return response.json()

Helper function to interact with the CloudFlare API.

Args:
        account (:obj:`CloudFlareAccount`): CloudFlare Account object
        path (`str`): URL endpoint to communicate with
        args (:obj:`dict` of `str`: `str`): A dictionary of arguments for the endpoint to consume

Returns:
        `dict`


def check_candidate_exists(self, basepath, candidates):
    checked = []
    for item in candidates:
        abspath = os.path.join(basepath, item)
        if os.path.exists(abspath):
            checked.append(abspath)
    return checked

Check that at least one candidate exist into a directory.

Args:
        basepath (str): Directory path where to search for candidate.
        candidates (list): List of candidate file paths.

Returns:
        list: List of existing candidates.


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

Retrieves a list of the target servers and empty device bays that are available for assignment to the server
    profile.

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

Returns:
        list: List of available servers and bays.


def inspect_image(self, image):
    return self._result(self._get(self._url('/images/{0}/json', image)), True)

Get detailed information about an image. Similar to the ``docker
    inspect`` command, but only for images.

Args:
        image (str): The image to inspect

Returns:
        (dict): Similar to the output of ``docker inspect``, but as a
    single dict

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