def _kl_normal_normal(n_a, n_b, name=None):

  with tf.name_scope(name or "kl_normal_normal"):
    one = tf.constant(1, dtype=n_a.dtype)
    two = tf.constant(2, dtype=n_a.dtype)
    half = tf.constant(0.5, dtype=n_a.dtype)
    s_a_squared = tf.square(n_a.scale)
    s_b_squared = tf.square(n_b.scale)
    ratio = s_a_squared / s_b_squared
    return (tf.square(n_a.loc - n_b.loc) / (two * s_b_squared) + half *
            (ratio - one - tf.math.log(ratio)))

Calculate the batched KL divergence KL(n_a || n_b) with n_a and n_b Normal.

Args:
        n_a: instance of a Normal distribution object.
        n_b: instance of a Normal distribution object.
        name: (optional) Name to use for created operations.
        default is "kl_normal_normal".

Returns:
        Batchwise KL(n_a || n_b)


def get_conflicting_tools(self, request_only=False):

        from collections import defaultdict

        tool_sets = defaultdict(set)
        tools_dict = self.get_tools(request_only=request_only)
        for variant, tools in tools_dict.itervalues():
            for tool in tools:
                tool_sets[tool].add(variant)

        conflicts = dict((k, v) for k, v in tool_sets.iteritems() if len(v) > 1)
        return conflicts

Returns tools of the same name provided by more than one package.

Args:
        request_only: If True, only return the key from resolved packages
            that were also present in the request.

Returns:
        Dict of {tool-name: set([Variant])}.


def __init__(self, table_id=Meter.OFPM_ALL):

        super().__init__(InstructionType.OFPIT_GOTO_TABLE)
        self.table_id = table_id

Create a InstructionGotoTable with the optional parameters below.

Args:
        length (int): Length of this struct in bytes.
        table_id (int): set next table in the lookup pipeline.


def __init__(self, attention_logit_mod, name="attention"):

    super(AttentiveRead, self).__init__(name=name)

    self._attention_logit_mod = attention_logit_mod

Initialize AttentiveRead module.

Args:
        attention_logit_mod: Module that produces logit corresponding to a memory
        slot's compatibility. Must map a [batch_size * memory_size,
        memory_word_size + query_word_size]-shaped Tensor to a
        [batch_size * memory_size, 1] shape Tensor.
        name: string. Name for module.


def execute_no_wait(self, cmd, walltime, envs={}):

        current_env = copy.deepcopy(self._envs)
        current_env.update(envs)

        try:
            proc = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                cwd=self.userhome,
                env=current_env,
                shell=True,
                preexec_fn=os.setpgrp
            )
            pid = proc.pid

        except Exception as e:
            print("Caught exception : {0}".format(e))
            logger.warn("Execution of command [%s] failed due to \n %s ", (cmd, e))

        return pid, proc

Synchronously execute a commandline string on the shell.

Args:
        - cmd (string) : Commandline string to execute
        - walltime (int) : walltime in seconds, this is not really used now.

Returns:
        - retcode : Return code from the execution, -1 on fail
        - stdout  : stdout string
        - stderr  : stderr string

Raises:
    None.


def fields_equal(self, instance, fields_to_ignore=("id", "change_date", "changed_by")):

        for field in self._meta.get_fields():
            if not field.many_to_many and field.name not in fields_to_ignore:
                if getattr(instance, field.name) != getattr(self, field.name):
                    return False

        return True

Compares this instance's fields to the supplied instance to test for equality.
    This will ignore any fields in `fields_to_ignore`.

    Note that this method ignores many-to-many fields.

Args:
        instance: the model instance to compare
        fields_to_ignore: List of fields that should not be compared for equality. By default
        includes `id`, `change_date`, and `changed_by`.

    Returns: True if the checked fields are all equivalent, else False


def on(self, event_name, *args, **kwargs):

        def decorator(f):
            self.add_event_handler(event_name, f, *args, **kwargs)
            return f
        return decorator

Decorator shortcut for add_event_handler.

Args:
        event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or
            any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
        *args: optional args to be passed to `handler`.
        **kwargs: optional keyword args to be passed to `handler`.


def __init__(
        self,
        size,
        window=3,
        stride=1,
        padding='SAME',
        bias=True,
        activation='relu',
        l2_regularization=0.0,
        l1_regularization=0.0,
        named_tensors=None,
        scope='conv1d',
        summary_labels=()
    ):

        self.size = size
        self.window = window
        self.stride = stride
        self.padding = padding
        self.bias = bias
        self.l2_regularization = l2_regularization
        self.l1_regularization = l1_regularization
        self.nonlinearity = Nonlinearity(summary_labels=summary_labels, **util.prepare_kwargs(activation))
        super(Conv1d, self).__init__(named_tensors=named_tensors, scope=scope, summary_labels=summary_labels)

1D convolutional layer.

Args:
        size: Number of filters
        window: Convolution window size
        stride: Convolution stride
        padding: Convolution padding, one of 'VALID' or 'SAME'
        bias: If true, a bias is added
        activation: Type of nonlinearity, or dict with name & arguments
        l2_regularization: L2 regularization weight
        l1_regularization: L1 regularization weight


def __init__(self, host='localhost', port=12223):

        channel = grpc.insecure_channel('{}:{}'.format(host, port))
        self._stub = clearly_pb2_grpc.ClearlyServerStub(channel)

Constructs a client instance.

Args:
        host (str): the hostname of the server
        port (int): the port of the server


def indicators_from_tag(self, indicator, tag_name, filters=None, params=None):

        params = params or {}

        for t in self.pivot_from_tag(indicator, tag_name, filters=filters, params=params):
            yield t

Args:
    indicator:
    tag_name:
    filters:
    params:

    Return:


def reaction_formula(reaction, compound_formula):

    def multiply_formula(compound_list):
        for compound, count in compound_list:
            yield count * compound_formula[compound.name]

    for compound, _ in reaction.compounds:
        if compound.name not in compound_formula:
            return None
    else:
        left_form = reduce(
            operator.or_, multiply_formula(reaction.left), Formula())
        right_form = reduce(
            operator.or_, multiply_formula(reaction.right), Formula())
    return left_form, right_form

Calculate formula compositions for both sides of the specified reaction.

    If the compounds in the reaction all have formula, then calculate and
    return the chemical compositions for both sides, otherwise return `None`.

Args:
        reaction: :class:`psamm.reaction.Reaction`.
        compound_formula: a map from compound id to formula.


def seek(self, offset, whence=os.SEEK_SET):

    self._check_open()

    self._buffer.reset()
    self._buffer_future = None

    if whence == os.SEEK_SET:
      self._offset = offset
    elif whence == os.SEEK_CUR:
      self._offset += offset
    elif whence == os.SEEK_END:
      self._offset = self._file_size + offset
    else:
      raise ValueError('Whence mode %s is invalid.' % str(whence))

    self._offset = min(self._offset, self._file_size)
    self._offset = max(self._offset, 0)
    if self._remaining():
      self._request_next_buffer()

Set the file's current offset.

    Note if the new offset is out of bound, it is adjusted to either 0 or EOF.

Args:
        offset: seek offset as number.
        whence: seek mode. Supported modes are os.SEEK_SET (absolute seek),
        os.SEEK_CUR (seek relative to the current position), and os.SEEK_END
        (seek relative to the end, offset should be negative).

Raises:
        IOError: When this buffer is closed.
        ValueError: When whence is invalid.


def launch(self, workflow):

        # hit workflow api
        try:
            r = self.gbdx_connection.post(self.workflows_url, json=workflow)
            try:
                r.raise_for_status()
            except:
                print("GBDX API Status Code: %s" % r.status_code)
                print("GBDX API Response: %s" % r.text)
                r.raise_for_status()
            workflow_id = r.json()['id']
            return workflow_id
        except TypeError:
            self.logger.debug('Workflow not launched!')

Launches GBDX workflow.

Args:
        workflow (dict): Dictionary specifying workflow tasks.

Returns:
        Workflow id (str).


def EnrolFleetspeakClient(self, client_id):

    client_urn = rdf_client.ClientURN(client_id)

    # If already enrolled, return.
    if data_store.RelationalDBEnabled():
      try:
        data_store.REL_DB.ReadClientMetadata(client_id)
        return False
      except db.UnknownClientError:
        pass
    else:
      if aff4.FACTORY.ExistsWithType(
          client_urn, aff4_type=aff4_grr.VFSGRRClient, token=self.token):
        return False

    logging.info("Enrolling a new Fleetspeak client: %r", client_id)

    if data_store.RelationalDBEnabled():
      now = rdfvalue.RDFDatetime.Now()
      data_store.REL_DB.WriteClientMetadata(
          client_id, first_seen=now, fleetspeak_enabled=True, last_ping=now)

    if data_store.AFF4Enabled():
      # TODO(fleetspeak-team,grr-team): If aff4 isn't reliable enough, we can
      # catch exceptions from it and forward them to Fleetspeak by failing its
      # gRPC call. Fleetspeak will then retry with a random, perhaps healthier,
      # instance of the GRR frontend.
      with aff4.FACTORY.Create(
          client_urn,
          aff4_type=aff4_grr.VFSGRRClient,
          mode="rw",
          token=self.token) as client:

        client.Set(client.Schema.FLEETSPEAK_ENABLED, rdfvalue.RDFBool(True))

        index = client_index.CreateClientIndex(token=self.token)
        index.AddClient(client)
        if data_store.RelationalDBEnabled():
          client_obj = rdf_objects.ClientSnapshot(
              client_id=client_urn.Basename())
          index = client_index.ClientIndex()
          index.AddClient(client_obj)

    # Publish the client enrollment message.
    events.Events.PublishEvent("ClientEnrollment", client_urn, token=self.token)
    return True

Enrols a Fleetspeak-enabled client for use with GRR.

Args:
        client_id: GRR client-id for the client.

Returns:
        True if the client is new, and actually got enrolled. This method
        is a no-op if the client already exists (in which case False is returned).


def site_name(self, site_name):

        # Set base class property site_name
        _Pybooru.site_name.fset(self, site_name)

        if ('api_version' and 'hashed_string') in SITE_LIST[site_name]:
            self.api_version = SITE_LIST[site_name]['api_version']
            self.hash_string = SITE_LIST[site_name]['hashed_string']

Sets api_version and hash_string.

    Parameters:
        site_name (str): The site name in 'SITE_LIST', default sites.

Raises:
        PybooruError: When 'site_name' isn't valid.


def get_bytes(obj):

    try:
        obj = obj.read(_NUM_SIGNATURE_BYTES)
    except AttributeError:
        # duck-typing as readable failed - we'll try the other options
        pass

    kind = type(obj)

    if kind is bytearray:
        return signature(obj)

    if kind is str:
        return get_signature_bytes(obj)

    if kind is bytes:
        return signature(obj)

    if kind is memoryview:
        return signature(obj).tolist()

    raise TypeError('Unsupported type as file input: %s' % kind)

Infers the input type and reads the first 262 bytes,
    returning a sliced bytearray.

Args:
        obj: path to readable, file, bytes or bytearray.

Returns:
        First 262 bytes of the file content as bytearray type.

Raises:
        TypeError: if obj is not a supported type.


def ParseCloudEntryRow(
      self, parser_mediator, query, row, cache=None, database=None,
      **unused_kwargs):

    query_hash = hash(query)

    parent_resource_id = self._GetRowValue(
        query_hash, row, 'parent_resource_id')
    filename = self._GetRowValue(query_hash, row, 'filename')

    cloud_path = self.GetCloudPath(parent_resource_id, cache, database)
    cloud_filename = '{0:s}{1:s}'.format(cloud_path, filename)

    event_data = GoogleDriveSnapshotCloudEntryEventData()
    event_data.document_type = self._GetRowValue(query_hash, row, 'doc_type')
    event_data.path = cloud_filename
    event_data.query = query
    event_data.shared = bool(self._GetRowValue(query_hash, row, 'shared'))
    event_data.size = self._GetRowValue(query_hash, row, 'size')
    event_data.url = self._GetRowValue(query_hash, row, 'url')

    timestamp = self._GetRowValue(query_hash, row, 'modified')
    date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_MODIFICATION)
    parser_mediator.ProduceEventWithEventData(event, event_data)

    timestamp = self._GetRowValue(query_hash, row, 'created')
    if timestamp:
      date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a cloud entry row.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        query (str): query that created the row.
        row (sqlite3.Row): row.
        cache (SQLiteCache): cache.
        database (SQLiteDatabase): database.


def swap(self, left, right):

        if type(left) is not type(right):
            raise LayoutError('The method swap only works with elements of the same type.')
        temp = self[left]
        self[left] = self[right]
        self[right] = temp

Swaps the map between left and right.

Args:
        left (tuple or int): Item to swap with right.
        right (tuple or int): Item to swap with left.

Raises:
        LayoutError: If left and right have not the same type.


def _ParseRecord(
      self, parser_mediator, record_index, evtx_record, recovered=False):

    event_data = self._GetEventData(
        parser_mediator, record_index, evtx_record, recovered=recovered)

    try:
      written_time = evtx_record.get_written_time_as_integer()
    except OverflowError as exception:
      parser_mediator.ProduceExtractionWarning((
          'unable to read written time from event record: {0:d} '
          'with error: {1!s}').format(record_index, exception))

      written_time = None

    if not written_time:
      date_time = dfdatetime_semantic_time.SemanticTime('Not set')
    else:
      date_time = dfdatetime_filetime.Filetime(timestamp=written_time)

    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_WRITTEN)
    parser_mediator.ProduceEventWithEventData(event, event_data)

Extract data from a Windows XML EventLog (EVTX) record.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        record_index (int): event record index.
        evtx_record (pyevtx.record): event record.
        recovered (Optional[bool]): True if the record was recovered.


def list_attributes(self, name):

        result = self.client.service.getListAttributes(name, self.proxy_id)
        if isinstance(result, list) and len(result) == 1:
            return result[0]
        return result

Look up the attributes of a list.

Args:
        name (str): The name of the list

Returns:
        dict: attributes of the list


def _CheckStatusAnalysisProcess(self, pid):

    # TODO: Refactor this method, simplify and separate concerns (monitoring
    # vs management).
    self._RaiseIfNotRegistered(pid)

    if pid in self._completed_analysis_processes:
      status_indicator = definitions.STATUS_INDICATOR_COMPLETED
      process_status = {
          'processing_status': status_indicator}
      used_memory = 0

    else:
      process = self._processes_per_pid[pid]

      process_status = self._QueryProcessStatus(process)
      if process_status is None:
        process_is_alive = False
      else:
        process_is_alive = True

      process_information = self._process_information_per_pid[pid]
      used_memory = process_information.GetUsedMemory() or 0

      if self._worker_memory_limit and used_memory > self._worker_memory_limit:
        logger.warning((
            'Process: {0:s} (PID: {1:d}) killed because it exceeded the '
            'memory limit: {2:d}.').format(
                process.name, pid, self._worker_memory_limit))
        self._KillProcess(pid)

      if isinstance(process_status, dict):
        self._rpc_errors_per_pid[pid] = 0
        status_indicator = process_status.get('processing_status', None)

        if status_indicator == definitions.STATUS_INDICATOR_COMPLETED:
          self._completed_analysis_processes.add(pid)

      else:
        rpc_errors = self._rpc_errors_per_pid.get(pid, 0) + 1
        self._rpc_errors_per_pid[pid] = rpc_errors

        if rpc_errors > self._MAXIMUM_RPC_ERRORS:
          process_is_alive = False

        if process_is_alive:
          rpc_port = process.rpc_port.value
          logger.warning((
              'Unable to retrieve process: {0:s} (PID: {1:d}) status via '
              'RPC socket: http://localhost:{2:d}').format(
                  process.name, pid, rpc_port))

          processing_status_string = 'RPC error'
          status_indicator = definitions.STATUS_INDICATOR_RUNNING
        else:
          processing_status_string = 'killed'
          status_indicator = definitions.STATUS_INDICATOR_KILLED

        process_status = {
            'processing_status': processing_status_string}

    self._UpdateProcessingStatus(pid, process_status, used_memory)

    if status_indicator in definitions.ERROR_STATUS_INDICATORS:
      logger.error((
          'Process {0:s} (PID: {1:d}) is not functioning correctly. '
          'Status code: {2!s}.').format(
              process.name, pid, status_indicator))

      self._TerminateProcessByPid(pid)

Checks the status of an analysis process.

Args:
        pid (int): process ID (PID) of a registered analysis process.

Raises:
        KeyError: if the process is not registered with the engine.


def get_default_settings(sub_scripts, script_order, script_execution_freq, iterator_type):

        def populate_sweep_param(scripts, parameter_list, trace=''):

            def get_parameter_from_dict(trace, dic, parameter_list, valid_values=None):

                if valid_values is None and isinstance(dic, Parameter):
                    valid_values = dic.valid_values

                for key, value in dic.items():
                    if isinstance(value, dict):  # for nested parameters ex {point: {'x': int, 'y': int}}
                        parameter_list = get_parameter_from_dict(trace + '.' + key, value, parameter_list,
                                                                 dic.valid_values[key])
                    elif (valid_values[key] in (float, int)) or \
                            (isinstance(valid_values[key], list) and valid_values[key][0] in (float, int)):
                        parameter_list.append(trace + '.' + key)
                    else:  # once down to the form {key: value}
                        # in all other cases ignore parameter
                        print(('ignoring sweep parameter', key))

                return parameter_list

            for script_name in list(scripts.keys()):
                from pylabcontrol.core import ScriptIterator
                script_trace = trace
                if script_trace == '':
                    script_trace = script_name
                else:
                    script_trace = script_trace + '->' + script_name
                if issubclass(scripts[script_name], ScriptIterator):  # gets subscripts of ScriptIterator objects
                    populate_sweep_param(vars(scripts[script_name])['_SCRIPTS'], parameter_list=parameter_list,
                                         trace=script_trace)
                else:
                    # use inspect instead of vars to get _DEFAULT_SETTINGS also for classes that inherit _DEFAULT_SETTINGS from a superclass
                    for setting in \
                    [elem[1] for elem in inspect.getmembers(scripts[script_name]) if elem[0] == '_DEFAULT_SETTINGS'][0]:
                        parameter_list = get_parameter_from_dict(script_trace, setting, parameter_list)

            return parameter_list

        if iterator_type == 'loop':
            script_default_settings = [
                Parameter('script_order', script_order),
                Parameter('script_execution_freq', script_execution_freq),
                Parameter('num_loops', 0, int, 'times the subscripts will be executed'),
                Parameter('run_all_first', True, bool, 'Run all scripts with nonzero frequency in first pass')
            ]

        elif iterator_type == 'sweep':

            sweep_params = populate_sweep_param(sub_scripts, [])

            script_default_settings = [
                Parameter('script_order', script_order),
                Parameter('script_execution_freq', script_execution_freq),
                Parameter('sweep_param', sweep_params[0], sweep_params, 'variable over which to sweep'),
                Parameter('sweep_range',
                          [Parameter('min_value', 0, float, 'min parameter value'),
                           Parameter('max_value', 0, float, 'max parameter value'),
                           Parameter('N/value_step', 0, float,
                                     'either number of steps or parameter value step, depending on mode')]),
                Parameter('stepping_mode', 'N', ['N', 'value_step'],
                          'Switch between number of steps and step amount'),
                Parameter('run_all_first', True, bool, 'Run all scripts with nonzero frequency in first pass')
            ]
        else:
            print(('unknown iterator type ' + iterator_type))
            raise TypeError('unknown iterator type ' + iterator_type)

        return script_default_settings

assigning the actual script settings depending on the iterator type

    this might be overwritten by classes that inherit form ScriptIterator

Args:
        sub_scripts: dictionary with the subscripts
        script_order: execution order of subscripts
        script_execution_freq: execution frequency of subscripts

Returns:
        the default setting for the iterator


def set_position_p(self, pvalue):

        pvalue_msb = int(pvalue) >> 8
        pvalue_lsb = int(pvalue) & 0xff
        data = []
        data.append(0x0B)
        data.append(self.servoid)
        data.append(RAM_WRITE_REQ)
        data.append(POSITION_KP_RAM)
        data.append(BYTE2)
        data.append( pvalue_lsb)
        data.append( pvalue_msb)
        send_data(data)

Set the P gain of the  position PID

Args:
        pvalue (int): P value


def ed25519_public_key_to_string(key):

    return base64.b64encode(key.public_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PublicFormat.Raw,
    ), None).decode('utf-8')

Convert an ed25519 public key to a base64-encoded string.

Args:
        key (Ed25519PublicKey): the key to write to the file.

Returns:
        str: the key representation as a str


def get_paths(self, key):

        final_paths = []

        if key in self.__cli:
            paths = self.__cli[key] or []
            from_conf = False
        else:
            paths = self.__config.get(key) or []
            from_conf = True

        for path in flatten_list(paths):
            final_path = self.__abspath(path, from_conf)
            if final_path:
                final_paths.append(final_path)

        return final_paths

Same as `ConfigParser.get_path` for a list of paths.

Args:
        key: str, the key to lookup the paths with

Returns:
        list: The paths.


def delete(filething):

    t = OggFLAC(filething)
    filething.fileobj.seek(0)
    t.delete(filething)

delete(filething)

Args:
        filething (filething)

Raises:
        mutagen.MutagenError

    Remove tags from a file.


def fib_iter(n):

    # precondition
    assert n >= 0, 'n must be positive integer'

    fib_1 = 0
    fib_2 = 1
    sum = 0
    if n <= 1:
        return n
    for _ in range(n-1):
        sum = fib_1 + fib_2
        fib_1 = fib_2
        fib_2 = sum
    return sum

[summary]
    Works iterative approximate O(n)

Args:
        n {[int]} -- [description]

Returns:
        [int] -- [description]


def session_ended(self, f):

        self._session_ended_view_func = f

        @wraps(f)
        def wrapper(*args, **kw):
            self._flask_view_func(*args, **kw)
        return f

Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill.

    @ask.session_ended
    def session_ended():
        return "{}", 200

    The wrapped function is registered as the session_ended view function
    and renders the response for requests to the end of the session.

Args:
        f {function} -- session_ended view function


def trace(state: State, fn: TransitionOperator, num_steps: IntTensor,
          trace_fn: Callable[[State, TensorNest], TensorNest]
         ) -> Tuple[State, TensorNest]:

  def fn_wrapper(args, _):
    return tf.nest.map_structure(tf.convert_to_tensor, call_fn(fn, args[0]))

  def trace_fn_wrapper(args):
    return tf.nest.map_structure(tf.convert_to_tensor, call_fn(trace_fn, args))

  state = call_fn(fn, state)
  first_trace = trace_fn_wrapper(state)

  state, full_trace = mcmc_util.trace_scan(
      fn_wrapper, state, tf.ones(num_steps - 1), trace_fn=trace_fn_wrapper)

  prepend = lambda x, y: tf.concat(  # pylint: disable=g-long-lambda
      [tf.convert_to_tensor(value=x)[tf.newaxis], y], 0)

  return state, tf.nest.map_structure(prepend, first_trace, full_trace)

`TransitionOperator` that runs `fn` repeatedly and traces its outputs.

Args:
        state: A nest of `Tensor`s or None.
        fn: A `TransitionOperator`.
        num_steps: Number of steps to run the function for. Must be greater than 1.
        trace_fn: Callable that the unpacked outputs of `fn` and returns a nest of
        `Tensor`s. These will be stacked and returned.

Returns:
        state: The final state returned by `fn`.
        traces: Stacked outputs of `trace_fn`.


def copy_function(func, name=None):

    code = func.__code__
    newname = name or func.__name__
    newcode = CodeType(
        code.co_argcount,
        code.co_kwonlyargcount,
        code.co_nlocals,
        code.co_stacksize,
        code.co_flags,
        code.co_code,
        code.co_consts,
        code.co_names,
        code.co_varnames,
        code.co_filename,
        newname,
        code.co_firstlineno,
        code.co_lnotab,
        code.co_freevars,
        code.co_cellvars,
    )
    newfunc = FunctionType(
        newcode,
        func.__globals__,
        newname,
        func.__defaults__,
        func.__closure__,
    )
    newfunc.__dict__.update(func.__dict__)
    return newfunc

Copy a function object with different name.

Args:
        func (function): Function to be copied.
        name (string, optional): Name of the new function.
            If not spacified, the same name of `func` will be used.

Returns:
        newfunc (function): New function with different name.


def _DefaultValueConstructorForField(field):

  if _IsMapField(field):
    return _GetInitializeDefaultForMap(field)

  if field.label == _FieldDescriptor.LABEL_REPEATED:
    if field.has_default_value and field.default_value != []:
      raise ValueError('Repeated field default value not empty list: %s' % (
          field.default_value))
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      # We can't look at _concrete_class yet since it might not have
      # been set.  (Depends on order in which we initialize the classes).
      message_type = field.message_type
      def MakeRepeatedMessageDefault(message):
        return containers.RepeatedCompositeFieldContainer(
            message._listener_for_children, field.message_type)
      return MakeRepeatedMessageDefault
    else:
      type_checker = type_checkers.GetTypeChecker(field)
      def MakeRepeatedScalarDefault(message):
        return containers.RepeatedScalarFieldContainer(
            message._listener_for_children, type_checker)
      return MakeRepeatedScalarDefault

  if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
    # _concrete_class may not yet be initialized.
    message_type = field.message_type
    def MakeSubMessageDefault(message):
      result = message_type._concrete_class()
      result._SetListener(
          _OneofListener(message, field)
          if field.containing_oneof is not None
          else message._listener_for_children)
      return result
    return MakeSubMessageDefault

  def MakeScalarDefault(message):
    # TODO(protobuf-team): This may be broken since there may not be
    # default_value.  Combine with has_default_value somehow.
    return field.default_value
  return MakeScalarDefault

Returns a function which returns a default value for a field.

Args:
        field: FieldDescriptor object for this field.

    The returned function has one argument:
        message: Message instance containing this field, or a weakref proxy
        of same.

    That function in turn returns a default value for this field.  The default
        value may refer back to |message| via a weak reference.


def write_env_vars(env_vars=None):  # type: (dict) -> None

    env_vars = env_vars or {}
    env_vars['PYTHONPATH'] = ':'.join(sys.path)

    for name, value in env_vars.items():
        os.environ[name] = value

Write the dictionary env_vars in the system, as environment variables.

Args:
        env_vars ():

    Returns:


def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str:

    dialect = get_dialect(mixed)
    # noinspection PyUnresolvedReferences
    return dialect.name

Finds the name of the SQLAlchemy dialect in use.

Args:
        mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
            :class:`Dialect` object

    Returns: the SQLAlchemy dialect name being used


def _get_class_frame_source(class_name):
    # type: (str) -> Optional[str]

    for frame_info in inspect.stack():
        try:
            with open(frame_info[1]) as fp:
                src = "".join(fp.readlines()[frame_info[2] - 1 :])
        except IOError:
            continue
        if re.search(r"\bclass\b\s+\b{}\b".format(class_name), src):
            reader = six.StringIO(src).readline
            tokens = tokenize.generate_tokens(reader)
            source_tokens = []
            indent_level = 0
            base_indent_level = 0
            has_base_level = False
            for token, value, _, _, _ in tokens:  # type: ignore
                source_tokens.append((token, value))
                if token == tokenize.INDENT:
                    indent_level += 1
                elif token == tokenize.DEDENT:
                    indent_level -= 1
                    if has_base_level and indent_level <= base_indent_level:
                        return (
                            tokenize.untokenize(source_tokens),
                            frame_info[0].f_globals,
                            frame_info[0].f_locals,
                        )
                elif not has_base_level:
                    has_base_level = True
                    base_indent_level = indent_level
    raise TypeError(
        'Unable to retrieve source for class "{}"'.format(class_name)
    )

Return the source code for a class by checking the frame stack.

    This is necessary because it is not possible to get the source of a class
    being created by a metaclass directly.

Args:
        class_name: The class to look for on the stack.

Returns:
        The source code for the requested class if the class was found and the
        source was accessible.


def _ProcessSources(
      self, source_path_specs, storage_writer, filter_find_specs=None):

    if self._processing_profiler:
      self._processing_profiler.StartTiming('process_sources')

    self._status = definitions.STATUS_INDICATOR_COLLECTING
    self._number_of_consumed_event_tags = 0
    self._number_of_consumed_events = 0
    self._number_of_consumed_reports = 0
    self._number_of_consumed_sources = 0
    self._number_of_consumed_warnings = 0
    self._number_of_produced_event_tags = 0
    self._number_of_produced_events = 0
    self._number_of_produced_reports = 0
    self._number_of_produced_sources = 0
    self._number_of_produced_warnings = 0

    path_spec_generator = self._path_spec_extractor.ExtractPathSpecs(
        source_path_specs, find_specs=filter_find_specs,
        recurse_file_system=False, resolver_context=self._resolver_context)

    for path_spec in path_spec_generator:
      if self._abort:
        break

      # TODO: determine if event sources should be DataStream or FileEntry
      # or both.
      event_source = event_sources.FileEntryEventSource(path_spec=path_spec)
      storage_writer.AddEventSource(event_source)

      self._number_of_produced_sources = storage_writer.number_of_event_sources

      # Update the foreman process status in case we are using a filter file.
      self._UpdateForemanProcessStatus()

      if self._status_update_callback:
        self._status_update_callback(self._processing_status)

    self._ScheduleTasks(storage_writer)

    if self._abort:
      self._status = definitions.STATUS_INDICATOR_ABORTED
    else:
      self._status = definitions.STATUS_INDICATOR_COMPLETED

    self._number_of_produced_events = storage_writer.number_of_events
    self._number_of_produced_sources = storage_writer.number_of_event_sources
    self._number_of_produced_warnings = storage_writer.number_of_warnings

    if self._processing_profiler:
      self._processing_profiler.StopTiming('process_sources')

    # Update the foreman process and task status in case we are using
    # a filter file.
    self._UpdateForemanProcessStatus()

    tasks_status = self._task_manager.GetStatusInformation()
    if self._task_queue_profiler:
      self._task_queue_profiler.Sample(tasks_status)

    self._processing_status.UpdateTasksStatus(tasks_status)

    if self._status_update_callback:
      self._status_update_callback(self._processing_status)

Processes the sources.

Args:
        source_path_specs (list[dfvfs.PathSpec]): path specifications of
        the sources to process.
        storage_writer (StorageWriter): storage writer for a session storage.
        filter_find_specs (Optional[list[dfvfs.FindSpec]]): find specifications
        used in path specification extraction. If set, path specifications
        that match the find specification will be processed.


def __init__(self, channel):

        self.ListInstances = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/ListInstances",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.ListInstancesRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.ListInstancesResponse.FromString,
        )
        self.GetInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/GetInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.GetInstanceRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.Instance.FromString,
        )
        self.CreateInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/CreateInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.CreateInstanceRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )
        self.UpdateInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/UpdateInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.UpdateInstanceRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )
        self.DeleteInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/DeleteInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.DeleteInstanceRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )

Constructor.

Args:
        channel: A grpc.Channel.


def execute_by_options(args):

    if args['subcommand'] == 'sphinx':
        s = Sphinx(proj_info)
        if args['quickstart']:
            s.quickstart()
        elif args['gen_code_api']:
            s.gen_code_api()
        elif args['rst2html']:
            s.rst2html()
        pass
    elif args['subcommand'] == 'offline_dist':
        pod = PyOfflineDist()
        if args['freeze_deps']:
            pod.freeze_deps()
        elif args['download_deps']:
            pod.download_deps()
        elif args['install_deps']:
            pod.install_deps()
        elif args['clean_deps']:
            pod.clean_deps()
        elif args['mkbinary']:
            pod.pyinstaller_mkbinary(args['mkbinary'])
        elif args['clean_binary']:
            pod.clean_binary()

    pass

execute by argument dictionary

Args:
        args (dict): command line argument dictionary


def from_pil(pil, alpha=1.0, wref=_DEFAULT_WREF):

    return Color(pil_to_rgb(pil), 'rgb', alpha, wref)

Create a new instance based on the specifed PIL color.

    Parameters:
        :pil:
        A PIL compatible color representation (0xBBGGRR)
        :alpha:
        The color transparency [0...1], default is opaque
        :wref:
        The whitepoint reference, default is 2° D65.

Returns:
        A grapefruit.Color instance.

    >>> Color.from_pil(0x0080ff)
    Color(1.0, 0.501961, 0.0, 1.0)
    >>> Color.from_pil(0x0080ff, 0.5)
    Color(1.0, 0.501961, 0.0, 0.5)


def parse_response(service, response, search_type):

    _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response,
               service, search_type)
    items = []
    # The result to be parsed is in either searchResult or getMetadataResult
    if 'searchResult' in response:
        response = response['searchResult']
    elif 'getMetadataResult' in response:
        response = response['getMetadataResult']
    else:
        raise ValueError('"response" should contain either the key '
                         '"searchResult" or "getMetadataResult"')

    # Form the search metadata
    search_metadata = {
        'number_returned': response['count'],
        'total_matches': None,
        'search_type': search_type,
        'update_id': None,
    }

    for result_type in ('mediaCollection', 'mediaMetadata'):
        # Upper case the first letter (used for the class_key)
        result_type_proper = result_type[0].upper() + result_type[1:]
        raw_items = response.get(result_type, [])
        # If there is only 1 result, it is not put in an array
        if isinstance(raw_items, OrderedDict):
            raw_items = [raw_items]

        for raw_item in raw_items:
            # Form the class_key, which is a unique string for this type,
            # formed by concatenating the result type with the item type. Turns
            # into e.g: MediaMetadataTrack
            class_key = result_type_proper + raw_item['itemType'].title()
            cls = get_class(class_key)
            items.append(cls.from_music_service(service, raw_item))
    return SearchResult(items, **search_metadata)

Parse the response to a music service query and return a SearchResult

Args:
        service (MusicService): The music service that produced the response
        response (OrderedDict): The response from the soap client call
        search_type (str): A string that indicates the search type that the
            response is from

Returns:
        SearchResult: A SearchResult object


def __init__(self, mtf_graph, mesh_shape, mtf_outputs=()):

    self.mtf_graph = mtf_graph
    self.mesh_shape = mesh_shape
    self.mtf_outputs = mtf_outputs

    self._layout_validator = None  # valid_layouts.LayoutValidator
    self._graph_interface = None

Initializer.

Args:
        mtf_graph: a mtf.Graph.
        mesh_shape: an mtf.Shape.
        mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
        of the computation.


def build_graph(steps):

    graph = Graph()

    for step in steps:
        graph.add_step(step)

    for step in steps:
        for dep in step.requires:
            graph.connect(step.name, dep)

        for parent in step.required_by:
            graph.connect(parent, step.name)

    return graph

Builds a graph of steps.

Args:
        steps (list): a list of :class:`Step` objects to execute.


def _FormatSubjectExOrProcessExToken(self, token_data):

    if token_data.net_type == 4:
      ip_address = self._FormatPackedIPv4Address(token_data.ip_address)
    elif token_data.net_type == 16:
      ip_address = self._FormatPackedIPv6Address(token_data.ip_address)
    else:
      ip_address = 'unknown'

    return {
        'aid': token_data.audit_user_identifier,
        'euid': token_data.effective_user_identifier,
        'egid': token_data.effective_group_identifier,
        'uid': token_data.real_user_identifier,
        'gid': token_data.real_group_identifier,
        'pid': token_data.process_identifier,
        'session_id': token_data.session_identifier,
        'terminal_port': token_data.terminal_port,
        'terminal_ip': ip_address}

Formats a subject or process token as a dictionary of values.

Args:
        token_data (bsm_token_data_subject32_ex|bsm_token_data_subject64_ex):
        AUT_SUBJECT32_EX, AUT_PROCESS32_EX, AUT_SUBJECT64_EX or
        AUT_PROCESS64_EX token data.

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


def parse_args(args=None):

    parser = argparse.ArgumentParser(description="Main script to run LIVVkit.",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     fromfile_prefix_chars='@')

    parser.add_argument('-o', '--out-dir',
                        default=os.path.join(os.getcwd(), "vv_" + time.strftime("%Y-%m-%d")),
                        help='Location to output the LIVVkit webpages.'
                        )

    parser.add_argument('-v', '--verify',
                        nargs=2,
                        default=None,
                        help=' '.join(['Specify the locations of the test and bench bundle to',
                                       'compare (respectively).'
                                       ])
                        )

    parser.add_argument('-V', '--validate',
                        action='store',
                        nargs='+',
                        default=None,
                        help=' '.join(['Specify the location of the configuration files for',
                                       'validation tests.'
                                       ])
                        )

    # FIXME: this just short-circuits to the validation option, and should become its own module
    parser.add_argument('-e', '--extension',
                        action='store',
                        nargs='+',
                        default=None,
                        dest='validate',
                        metavar='EXTENSION',
                        help=' '.join(['Specify the location of the configuration files for',
                                       'LIVVkit extensions.'
                                       ])
                        )

    parser.add_argument('-p', '--publish',
                        action='store_true',
                        help=' '.join(['Also produce a publication quality copy of the figure in',
                                       'the output directory (eps, 600d pi).'
                                       ])
                        )

    parser.add_argument('-s', '--serve',
                        nargs='?', type=int, const=8000,
                        help=' '.join(['Start a simple HTTP server for the output website specified',
                                       'by OUT_DIR on port SERVE.'
                                       ])
                        )

    parser.add_argument('--version',
                        action='version',
                        version='LIVVkit {}'.format(livvkit.__version__),
                        help="Show LIVVkit's version number and exit"
                        )

    return init(parser.parse_args(args))

Handles the parsing of options for LIVVkit's command line interface

Args:
        args: The list of arguments, typically sys.argv[1:]


def ng(self, wavelength):

        return self.n(wavelength) - (wavelength*1.e-9)*self.nDer1(wavelength)

The group index with respect to wavelength.

Args:
        wavelength (float, list, None): The wavelength(s) the group
            index will be evaluated at.

Returns:
        float, list: The group index at the target wavelength(s).


def depth_october_average_ground_temperature(self, value=None):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError(
                    'value {} need to be of type float '
                    'for field `depth_october_average_ground_temperature`'.format(value))

        self._depth_october_average_ground_temperature = value

Corresponds to IDD Field `depth_october_average_ground_temperature`

Args:
        value (float): value for IDD Field `depth_october_average_ground_temperature`
            Unit: C
            if `value` is None it will not be checked against the
            specification and is assumed to be a missing value

Raises:
        ValueError: if `value` is not a valid value


def _spin_product(variables):

    multiplier, multiplicand, product, aux = variables

    return BinaryQuadraticModel({multiplier: -.5,
                                 multiplicand: -.5,
                                 product: -.5,
                                 aux: -1.},
                                {(multiplier, multiplicand): .5,
                                 (multiplier, product): .5,
                                 (multiplier, aux): 1.,
                                 (multiplicand, product): .5,
                                 (multiplicand, aux): 1.,
                                 (product, aux): 1.},
                                2.,
                                Vartype.SPIN)

Create a bqm with a gap of 2 that represents the product of two variables.

    Note that spin-product requires an auxiliary variable.

Args:
        variables (list):
            multiplier, multiplicand, product, aux

Returns:
        :obj:`.BinaryQuadraticModel`


def get_street_from_xy(self, **kwargs):

        # Endpoint parameters
        params = {
            'coordinateX': kwargs.get('longitude'),
            'coordinateY': kwargs.get('latitude'),
            'Radius': kwargs.get('radius'),
            'cultureInfo': util.language_code(kwargs.get('lang'))
        }

        # Request
        result = self.make_request('geo', 'get_street_from_xy', **params)

        # Funny endpoint, no status code
        if not util.check_result(result, 'site'):
            return False, 'UNKNOWN ERROR'

        # Parse
        values = util.response_list(result, 'site')
        return True, [emtype.Street(**a) for a in values]

Obtain a list of streets around the specified point.

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

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


def delete(self, wait_for_deletion=True):

    if self.exists():
      try:
        self._api.objects_delete(self._bucket, self._key)
      except Exception as e:
        raise e
      if wait_for_deletion:
        for _ in range(_MAX_POLL_ATTEMPTS):
          objects = Objects(self._bucket, prefix=self.key, delimiter='/',
                            context=self._context)
          if any(o.key == self.key for o in objects):
            time.sleep(_POLLING_SLEEP)
            continue
          break
        else:
          logging.error('Failed to see object deletion after %d attempts.',
                        _MAX_POLL_ATTEMPTS)

Deletes this object from its bucket.

Args:
        wait_for_deletion: If True, we poll until this object no longer appears in
        objects.list operations for this bucket before returning.

Raises:
        Exception if there was an error deleting the object.


def recursive_getitem(d: Mapping[str, Any], keys: Union[str, Sequence[str]]) -> Any:

    # If only a string, then just just return the item
    if isinstance(keys, str):
        return d[keys]
    else:
        return functools.reduce(operator.getitem, keys, d)

Recursively retrieve an item from a nested dict.

    Credit to: https://stackoverflow.com/a/52260663

Args:
        d: Mapping of strings to objects.
        keys: Names of the keys under which the object is stored. Can also just be a single string.

Returns:
        The object stored under the keys.

Raises:
        KeyError: If one of the keys isnt' found.


def normalize(self, inplace=False):

        if inplace:
            nrm = self.norm()
            self.data /= nrm
            return None
        nrm = self.norm()
        data_copy = np.array(self.data, copy=True)
        data_copy /= nrm
        return Quaternion(data_copy)

Normalizes a Quaternion to unit length
    so that it represents a valid rotation.

Args:
        inplace (bool): Do an inplace normalization.

Returns:
        Quaternion: Normalized quaternion.


def generate_matches(self, nodes):

        if self.content is None:
            # Shortcut for special case (see __init__.__doc__)
            for count in xrange(self.min, 1 + min(len(nodes), self.max)):
                r = {}
                if self.name:
                    r[self.name] = nodes[:count]
                yield count, r
        elif self.name == "bare_name":
            yield self._bare_name_matches(nodes)
        else:
            # The reason for this is that hitting the recursion limit usually
            # results in some ugly messages about how RuntimeErrors are being
            # ignored. We don't do this on non-CPython implementation because
            # they don't have this problem.
            if hasattr(sys, "getrefcount"):
                save_stderr = sys.stderr
                sys.stderr = StringIO()
            try:
                for count, r in self._recursive_matches(nodes, 0):
                    if self.name:
                        r[self.name] = nodes[:count]
                    yield count, r
            except RuntimeError:
                # We fall back to the iterative pattern matching scheme if the recursive
                # scheme hits the recursion limit.
                for count, r in self._iterative_matches(nodes):
                    if self.name:
                        r[self.name] = nodes[:count]
                    yield count, r
            finally:
                if hasattr(sys, "getrefcount"):
                    sys.stderr = save_stderr

Generator yielding matches for a sequence of nodes.

Args:
        nodes: sequence of nodes

Yields:
        (count, results) tuples where:
        count: the match comprises nodes[:count];
        results: dict containing named submatches.


def __init__(self, storage_writer, path):

    super(SQLiteStorageMergeReader, self).__init__(storage_writer)
    self._active_container_type = None
    self._active_cursor = None
    self._add_active_container_method = None
    self._add_container_type_methods = {}
    self._compression_format = definitions.COMPRESSION_FORMAT_NONE
    self._connection = None
    self._container_types = None
    self._cursor = None
    self._event_data_identifier_mappings = {}
    self._path = path

    # Create a runtime lookup table for the add container type method. This
    # prevents having to create a series of if-else checks for container types.
    # The table is generated at runtime as there are no forward function
    # declarations in Python.
    for container_type, method_name in self._ADD_CONTAINER_TYPE_METHODS.items():
      method = getattr(self, method_name, None)
      if not method:
        raise RuntimeError(
            'Add method missing for container type: {0:s}'.format(
                container_type))

      self._add_container_type_methods[container_type] = method

Initializes a storage merge reader.

Args:
        storage_writer (StorageWriter): storage writer.
        path (str): path to the input file.

Raises:
        IOError: if the input file cannot be opened.
        RuntimeError: if an add container method is missing.


def process_tokens(self, tokens):

        for tok_type, token, (start_row, start_col), _, _ in tokens:
            if tok_type == tokenize.STRING:
                # 'token' is the whole un-parsed token; we can look at the start
                # of it to see whether it's a raw or unicode string etc.
                self._process_string_token(token, start_row, start_col)

Process the token stream.

    This is required to override the parent class' implementation.

Args:
        tokens: the tokens from the token stream to process.


def __init__(self,
                 html_id=None,
                 name=None,
                 content=None,
                 template=None,
                 classes=None,
                 **kwargs):

        if html_id is not None:
            try:
                self.html_id = html_id
            except AttributeError:
                self._html_id = html_id
        if name is not None:
            try:
                self.name = name
            except AttributeError:
                self._name = name
        if content is not None:
            try:
                self.content = content
            except AttributeError:
                self._content = content
        if template is not None:
            try:
                self.template = template
            except AttributeError:
                self._template = template
        if classes is not None:
            try:
                self.classes = classes
            except AttributeError:
                self._classes = classes

        if not hasattr(self, 'template'):
            raise AttributeError('template is a required widget attribute')

        for kw, arg in kwargs.items():
            setattr(self, kw, arg)

Init method.

Args:
        html_id (str): an ID to set on the HTML item.
        name (str): the name of the item, displayed in HTML.
        content (): suitable content according to chosen display.
        template (str): the template responsible for display.
        classes (str): additional classes to pass to the HTML item.


def __init__(self, component1=None, component2=None):

        if component1 is None and component2 is not None:
            component1 = component2
            component2 = None

        self._llhead = None
        self._lltail = None
        #self._length = 0
        #self._offset = 0

        if isinstance(component1, CompositeBitarray):
            self._llhead = component1._llhead
            self._lltail = component1._lltail
            self._offset = component1._offset
            self._tailbitsused = component1._tailbitsused
            self._length = len(component1)
        else:
            self._llhead = self._lltail = _DLLNode(component1)
            self._offset = 0
            self._tailbitsused = len(component1)
            self._length = self._tailbitsused

        if component2 is not None:
            oldtail = self._lltail
            if isinstance(component2, CompositeBitarray):
                if self._lltail is component2._llhead:
                    if self._tail_end != component2._offset:
                        raise ProteusDataJoinError()

                    if component2._is_single_llnode:
                        self._tailbitsused += component2._tailbitsused
                    else:
                        self._tailbitsused = component2._tailbitsused
                    self._lltail = component2._lltail
                    self._length += len(component2)
                elif self._lltail.next is component2._llhead and\
                         self._tailoffset == 0 and\
                         component2._offset == 0:
                    self._lltail = component2._lltail
                    self._tailbitsused = component2._tailbitsused
                    self._length += len(component2)
                elif component2._llhead.prev is not None or\
                     self._lltail.next is not None or\
                     component2._offset or self._tailoffset or\
                     self._llhead is component2._lltail:
                    #Will not catch everything. Good enough to
                    #prevent most accidents. A 'perfect' version
                    #would require walking the whole tree. No way.
                    raise ProteusDataJoinError()
                else:
                    self._length += len(component2)
                    self._lltail.next = component2._llhead
                    self._lltail = component2._lltail
                    self._tailbitsused = component2._tailbitsused
            else:
                if self._tailoffset or self._lltail.next is not None:
                    raise ProteusDataJoinError()
                self._tailbitsused = len(component2)
                self._length += self._tailbitsused
                node = _DLLNode(component2)
                node.prev = self._lltail
                self._lltail = node

            #WHEN IT IS OK TO MERGE
            #oldtail can merge right if (oldtail is not head or offset is 0) and (oldtail.next is not tail or tailbitsused is len of node) and data is combinable. Do it recursive?
            #Merging can happen right until can't. Move back node and merge until can't. Repeat till new left node is incompatible.
            #if merging with the tail node, the tail node is fully used
            #Merge will start at seam, or have nothing to do.
            if oldtail is not self._llhead or self._offset == 0:
                self._do_merge(oldtail)

Create a bitarray object that stores its components by reference).

Args:
        *components: Any number of bitarray instances to store in this composition.


def system_add_keyspace(self, ks_def):

    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_system_add_keyspace(ks_def)
    return d

adds a keyspace and any column families that are part of it. returns the new schema id.

    Parameters:
    - ks_def


def prune_graph(graph_str, package_name):

    # find nodes of interest
    g = read_dot(graph_str)
    nodes = set()

    for node, attrs in g.node_attr.iteritems():
        attr = [x for x in attrs if x[0] == "label"]
        if attr:
            label = attr[0][1]
            try:
                req_str = _request_from_label(label)
                request = PackageRequest(req_str)
            except PackageRequestError:
                continue

            if request.name == package_name:
                nodes.add(node)

    if not nodes:
        raise ValueError("The package %r does not appear in the graph."
                         % package_name)

    # find nodes upstream from these nodes
    g_rev = g.reverse()
    accessible_nodes = set()
    access = accessibility(g_rev)
    for node in nodes:
        nodes_ = access.get(node, [])
        accessible_nodes |= set(nodes_)

    # remove inaccessible nodes
    inaccessible_nodes = set(g.nodes()) - accessible_nodes
    for node in inaccessible_nodes:
        g.del_node(node)

    return write_dot(g)

Prune a package graph so it only contains nodes accessible from the
    given package.

Args:
        graph_str (str): Dot-language graph string.
        package_name (str): Name of package of interest.

Returns:
        Pruned graph, as a string.


def authenticated_request(self, endpoint, method='GET', params=None, data=None):

        headers = {
                'X-Access-Token' : self.access_token,
                'X-Client-ID' : self.client_id
                }
        return self.api.request(endpoint, method=method, headers=headers, params=params, data=data)

Send a request to the given Wunderlist API with 'X-Access-Token' and 'X-Client-ID' headers and ensure the response code is as expected given the request type

    Params:
    endpoint -- API endpoint to send request to

    Keyword Args:
    method -- GET, PUT, PATCH, DELETE, etc.
    params -- parameters to encode in the request
    data -- data to send with the request


def __init__(self, elements: Sequence[Union[DataSource, DataSink]], transformers: Iterable[DataTransformer] = None) -> None:

        if not elements:
            raise ValueError("Elements must be a non-empty sequence of DataSources and DataSinks")

        if transformers is None:
            transformers = set()

        sources = set()  # type: Set[DataSource]
        sinks = set()  # type: Set[DataSink]
        targets = []  # type: List[Tuple[DataSource, Set[DataSink]]]
        for element in elements:
            if isinstance(element, DataSource):
                sources.add(element)
                targets.append((element, set(sinks)))

            if isinstance(element, DataSink):
                sinks.add(element)

        LOGGER.info("Beginning construction of type graph")
        # noinspection PyTypeChecker
        self._type_graph = _build_type_graph(sources, sinks, transformers)
        LOGGER.info("Completed construction of type graph")
        self._sources = targets
        self._sinks = sinks
        self._get_types = {}
        self._put_types = {}

Initializes a data pipeline.

Args:
        elements: The data stores and data sinks for this pipeline.
        transformers: The data transformers for this pipeline.


def reindex(self, ind):

        if isinstance(ind, pd.MultiIndex):
            try:
                return self.new(self.data.reindex(ind))
            except:
                raise RuntimeError('QADATASTRUCT ERROR: CANNOT REINDEX')
        else:
            raise RuntimeError(
                'QADATASTRUCT ERROR: ONLY ACCEPT MULTI-INDEX FORMAT'
            )

reindex

Args:
        ind {[type]} -- [description]

Raises:
        RuntimeError -- [description]
        RuntimeError -- [description]

Returns:
        [type] -- [description]


def generate_markdown_doc(app_name, spec):

    # Apply standard headers.
    sections = [
        HEADER.format(app_name=app_name),
        SOURCES_HEADER.format(app_name=app_name)
    ]

    # Generate the sources section of the documentation
    sorted_labels = sorted(list(spec.sources))
    for label in sorted_labels:
        sections.append(
            _generate_source_section(label, spec.sources[label], app_name)
        )

    # Generate the config section.
    sections.append(CONFIG_HEADER.format(app_name=app_name))
    table_rows, item_sections = _generate_item_sections(
        _sorted_dict_values(spec.items),
        app_name
    )

    headers = {
        'name': 'Name',
        'type': 'Type',
        'default': 'Default',
        'description': 'Description'
    }

    sections.append(
        build_markdown_table(
            headers,
            table_rows,
            ['name', 'type', 'default', 'description'],
        )
    )
    for item_section in item_sections:
        sections.append(item_section)

    return '\n'.join([section for section in sections])

Generate Markdown Documentation for the given spec/app name.

Args:
        app_name (str): The name of the application.
        spec (YapconfSpec): A yapconf specification with sources loaded.

    Returns (str):
        A valid, markdown string representation of the documentation for
        the given specification.


def getToC(doc, simple = True):

    def recurse(olItem, liste, lvl):

        while olItem:
            if olItem.title:
                title = olItem.title
            else:
                title = " "

            if not olItem.isExternal:
                if olItem.uri:
                    page = olItem.page + 1
                else:
                    page = -1
            else:
                page = -1

            if not simple:
                link = getLinkDict(olItem)
                liste.append([lvl, title, page, link])
            else:
                liste.append([lvl, title, page])

            if olItem.down:
                liste = recurse(olItem.down, liste, lvl+1)
            olItem = olItem.next
        return liste

    # check if document is open and not encrypted
    if doc.isClosed:
        raise ValueError("illegal operation on closed document")

    olItem = doc.outline

    if not olItem: return []
    lvl = 1
    liste = []
    return recurse(olItem, liste, lvl)

Create a table of contents.

Args:
        simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.


def _initialize_memory(self, policy_params):

    # We store observation, action, policy parameters, and reward.
    template = (
        self._batch_env.observ[0],
        self._batch_env.action[0],
        tools.nested.map(lambda x: x[0, 0], policy_params),
        self._batch_env.reward[0])
    with tf.variable_scope('ppo_temporary'):
      self._current_episodes = parts.EpisodeMemory(
          template, len(self._batch_env), self._config.max_length, 'episodes')
    self._finished_episodes = parts.EpisodeMemory(
        template, self._config.update_every, self._config.max_length, 'memory')
    self._num_finished_episodes = tf.Variable(0, False)

Initialize temporary and permanent memory.

Args:
        policy_params: Nested tuple of policy parameters with all dimensions set.

    Initializes the attributes `self._current_episodes`,
    `self._finished_episodes`, and `self._num_finished_episodes`. The episodes
    memory serves to collect multiple episodes in parallel. Finished episodes
    are copied into the next free slot of the second memory. The memory index
    points to the next free slot.


def format_time(
        self,
        hour_expression,
        minute_expression,
        second_expression=''
    ):

        hour = int(hour_expression)

        period = ''
        if self._options.use_24hour_time_format is False:
            period = " PM" if (hour >= 12) else " AM"
            if hour > 12:
                hour -= 12

        minute = str(int(minute_expression))  # !FIXME WUT ???
        second = ''
        if second_expression is not None and second_expression:
            second = "{}{}".format(":", str(int(second_expression)).zfill(2))

        return "{0}:{1}{2}{3}".format(str(hour).zfill(2), minute.zfill(2), second, period)

Given time parts, will contruct a formatted time description

Args:
        hour_expression: Hours part
        minute_expression: Minutes part
        second_expression: Seconds part

Returns:
        Formatted time description


def rvs(self, size=1):

        return np.random.multivariate_normal(self.mean, self.cov, size)

Convenience method to sample from this distribution.

Args:
        size (int or tuple): Shape of return value. Each element is drawn
            independently from this distribution.


def store(self, df, attribute_columns):

        # ID start values depend on currently stored entities/attributes!
        entity_id_start = models.Entity.get_max_id(self.session) + 1
        attribute_id_start = models.Attribute.get_max_id(self.session) + 1

        # append ID and type columns
        df['id'] = range(entity_id_start, entity_id_start + len(df))
        df['type'] = self.type

        # store entities
        df[['id', 'type']].to_sql(name=models.Entity.__tablename__,
                                  con=self.client.engine,
                                  if_exists='append',
                                  index=False)

        # store attributes
        for col in attribute_columns:
            # ID column of df is the entity ID of the attribute
            attr_df = df[[col, 'id']].rename(columns={'id': 'entity_id',
                                                      col: 'value'})
            attr_df['name'] = col

            # add entity ID column, need to respect already existing entities
            attr_df['id'] = range(attribute_id_start, attribute_id_start + len(df))
            attribute_id_start += len(df)

            # store
            attr_df.to_sql(name=models.Attribute.__tablename__,
                           con=self.client.engine,
                           if_exists='append',
                           index=False)

Store entities and their attributes

Args:
        df (pandas.DataFrame): data to store (storing appends 'id' and 'type' columns!)
        attribute_columns (list(str)): list of column labels that define attributes


def from_node(cls, node):

        if not isinstance(node, aioxmpp.stanza.Message):
            raise AttributeError("node must be a aioxmpp.stanza.Message instance")
        msg = cls()
        msg._to = node.to
        msg._sender = node.from_
        if None in node.body:
            msg.body = node.body[None]
        else:
            for key in node.body.keys():
                msg.body = node.body[key]
                break

        for data in node.xep0004_data:
            if data.title == SPADE_X_METADATA:
                for field in data.fields:
                    if field.var != "_thread_node":
                        msg.set_metadata(field.var, field.values[0])
                    else:
                        msg.thread = field.values[0]

        return msg

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

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

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


def set_slats_level(self, slatsLevel=0.0, shutterLevel=None):

        if shutterLevel is None:
            shutterLevel = self.shutterLevel
        data = {
            "channelIndex": 1,
            "deviceId": self.id,
            "slatsLevel": slatsLevel,
            "shutterLevel": shutterLevel,
        }
        return self._restCall("device/control/setSlatsLevel", json.dumps(data))

sets the slats and shutter level

Args:
        slatsLevel(float): the new level of the slats. 0.0 = open, 1.0 = closed,
        shutterLevel(float): the new level of the shutter. 0.0 = open, 1.0 = closed, None = use the current value

Returns:
        the result of the _restCall


def update(self, span: typing.Tuple[int, int], line_type: LineType) -> None:

        first_block_line, last_block_line = span
        for i in range(first_block_line, last_block_line + 1):
            try:
                self.__setitem__(i, line_type)
            except ValueError as error:
                raise ValidationError(i + self.fn_offset, 1, 'AAA99 {}'.format(error))

Updates line types for a block's span.

Args:
        span: First and last relative line number of a Block.
        line_type: The type of line to update to.

Raises:
        ValidationError: A special error on collision. This prevents Flake8
            from crashing because it is converted to a Flake8 error tuple,
            but it indicates to the user that something went wrong with
            processing the function.


def DtypeToNumberConverter(self, dtype):

    if np.issubdtype(dtype, np.datetime64):

      def DatetimesToNumbers(dt_list):
        return np.array([pd.Timestamp(dt).value for dt in dt_list])

      return DatetimesToNumbers
    elif np.issubdtype(dtype, np.timedelta64):

      def TimedetlasToNumbers(td_list):
        return np.array([pd.Timedelta(td).value for td in td_list])

      return TimedetlasToNumbers
    else:
      return None

Converts a Numpy dtype to a converter method if applicable.
    The converter method takes in a numpy array of objects of the provided
    dtype
    and returns a numpy array of the numbers backing that object for
    statistical
    analysis. Returns None if no converter is necessary.

Args:
    dtype: The numpy dtype to make a converter for.

Returns:
    The converter method or None.


def p44(msg):

    d = hex2bin(data(msg))

    if d[34] == '0':
        return None

    p = bin2int(d[35:46])    # hPa

    return p

Static pressure.

Args:
        msg (String): 28 bytes hexadecimal message string

Returns:
        int: static pressure in hPa


def EqualTo(self, value):

    self._awql = self._CreateSingleValueCondition(value, '=')
    return self._query_builder

Sets the type of the WHERE clause as "equal to".

Args:
        value: The value to be used in the WHERE condition.

Returns:
        The query builder that this WHERE builder links to.


def ws45(msg):

    d = hex2bin(data(msg))
    if d[3] == '0':
        return None

    ws = bin2int(d[4:6])
    return ws

Wind shear.

Args:
        msg (String): 28 bytes hexadecimal message string

Returns:
        int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe


def extract_numerics_alert(event):

  value = event.summary.value[0]
  debugger_plugin_metadata_content = None
  if value.HasField("metadata"):
    plugin_data = value.metadata.plugin_data
    if plugin_data.plugin_name == constants.DEBUGGER_PLUGIN_NAME:
      debugger_plugin_metadata_content = plugin_data.content

  if not debugger_plugin_metadata_content:
    raise ValueError("Event proto input lacks debugger plugin SummaryMetadata.")

  debugger_plugin_metadata_content = tf.compat.as_text(
      debugger_plugin_metadata_content)
  try:
    content_object = json.loads(debugger_plugin_metadata_content)
    device_name = content_object["device"]
  except (KeyError, ValueError) as e:
    raise ValueError("Could not determine device from JSON string %r, %r" %
                     (debugger_plugin_metadata_content, e))

  debug_op_suffix = ":DebugNumericSummary"
  if not value.node_name.endswith(debug_op_suffix):
    raise ValueError(
        "Event proto input does not have the expected debug op suffix %s" %
        debug_op_suffix)
  tensor_name = value.node_name[:-len(debug_op_suffix)]

  elements = tf_debug.load_tensor_from_event(event)
  nan_count = elements[constants.NAN_NUMERIC_SUMMARY_OP_INDEX]
  neg_inf_count = elements[constants.NEG_INF_NUMERIC_SUMMARY_OP_INDEX]
  pos_inf_count = elements[constants.POS_INF_NUMERIC_SUMMARY_OP_INDEX]
  if nan_count > 0 or neg_inf_count > 0 or pos_inf_count > 0:
    return NumericsAlert(
        device_name, tensor_name, event.wall_time, nan_count, neg_inf_count,
        pos_inf_count)
  return None

Determines whether a health pill event contains bad values.

    A bad value is one of NaN, -Inf, or +Inf.

Args:
        event: (`Event`) A `tensorflow.Event` proto from `DebugNumericSummary`
        ops.

Returns:
        An instance of `NumericsAlert`, if bad values are found.
        `None`, if no bad values are found.

Raises:
        ValueError: if the event does not have the expected tag prefix or the
        debug op name is not the expected debug op name suffix.


def flash(self, partition, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK):

    return self._simple_command('flash', arg=partition, info_cb=info_cb,
                                timeout_ms=timeout_ms)

Flashes the last downloaded file to the given partition.

Args:
        partition: Partition to flash.
        timeout_ms: Optional timeout in milliseconds to wait for it to finish.
        info_cb: See Download. Usually no messages.

Returns:
        Response to a download request, normally nothing.


def initialize_particle(rng, domain, fitness_function):

    position = rng.uniform(domain.lower, domain.upper, domain.dimension)
    fitness = fitness_function(position)
    return Particle(position=position,
                    velocity=np.zeros(domain.dimension),
                    fitness=fitness,
                    best_fitness=fitness,
                    best_position=position)

Initializes a particle within a domain.

Args:
        rng: numpy.random.RandomState: The random number generator.
        domain: cipy.problems.core.Domain: The domain of the problem.

Returns:
        cipy.algorithms.pso.Particle: A new, fully initialized particle.


def AnalyzeClient(self, client):

    client_id = self._ClientIdFromURN(client.urn)

    # Start with both the client id itself, and a universal keyword, used to
    # find all clients.
    #
    # TODO(user): Remove the universal keyword once we have a better way
    # to do this, i.e., once we have a storage library which can list all
    # clients directly.

    keywords = [self._NormalizeKeyword(client_id), "."]

    def TryAppend(prefix, keyword):
      precondition.AssertType(prefix, Text)
      if keyword:
        keyword_string = self._NormalizeKeyword(Text(keyword))
        keywords.append(keyword_string)
        if prefix:
          keywords.append(prefix + ":" + keyword_string)

    def TryAppendPrefixes(prefix, keyword, delimiter):
      if keyword is None:
        return 0
      TryAppend(prefix, keyword)
      segments = keyword.split(delimiter)
      for i in range(1, len(segments)):
        TryAppend(prefix, delimiter.join(segments[0:i]))
      return len(segments)

    def TryAppendIP(ip):
      TryAppend("ip", ip)
      # IP4v?
      if TryAppendPrefixes("ip", str(ip), ".") == 4:
        return
      # IP6v?
      TryAppendPrefixes("ip", str(ip), ":")

    def TryAppendMac(mac):
      TryAppend("mac", mac)
      if len(mac) == 12:
        # If looks like a mac address without ":" symbols, also add the keyword
        # with them.
        TryAppend("mac", ":".join([mac[i:i + 2] for i in range(0, 12, 2)]))

    s = client.Schema
    TryAppend("host", client.Get(s.HOSTNAME))
    TryAppendPrefixes("host", client.Get(s.HOSTNAME), "-")
    TryAppend("host", client.Get(s.FQDN))
    TryAppendPrefixes("host", client.Get(s.FQDN), ".")
    TryAppend("", client.Get(s.SYSTEM))
    TryAppend("", client.Get(s.UNAME))
    TryAppend("", client.Get(s.OS_RELEASE))
    TryAppend("", client.Get(s.OS_VERSION))
    TryAppend("", client.Get(s.KERNEL))
    TryAppend("", client.Get(s.ARCH))

    kb = client.Get(s.KNOWLEDGE_BASE)
    if kb:
      for user in kb.users:
        TryAppend("user", user.username)
        TryAppend("", user.full_name)
        if user.full_name:
          for name in user.full_name.split():
            # full_name often includes nicknames and similar, wrapped in
            # punctuation, e.g. "Thomas 'TJ' Jones". We remove the most common
            # wrapping characters.
            TryAppend("", name.strip("\"'()"))

    for username in client.Get(s.USERNAMES, []):
      TryAppend("user", username)

    for interface in client.Get(s.INTERFACES, []):
      if interface.mac_address:
        TryAppendMac(interface.mac_address.human_readable_address)
      for ip in interface.GetIPAddresses():
        TryAppendIP(ip)

    # We should have all mac and ip addresses already, but some test data only
    # has it attached directly, so just in case we look there also.
    if client.Get(s.MAC_ADDRESS):
      for mac in str(client.Get(s.MAC_ADDRESS)).split("\n"):
        TryAppendMac(mac)
    ip_list = client.Get(s.HOST_IPS, "")
    for ip in str(ip_list).split("\n"):
      TryAppendIP(ip)

    client_info = client.Get(s.CLIENT_INFO)
    if client_info:
      TryAppend("client", client_info.client_name)
      TryAppend("client", client_info.client_version)
      if client_info.labels:
        for label in client_info.labels:
          TryAppend("label", label)

    for label in client.GetLabelsNames():
      TryAppend("label", label)

    return client_id, keywords

Finds the client_id and keywords for a client.

Args:
        client: A VFSGRRClient record to find keywords for.

Returns:
        A tuple (client_id, keywords) where client_id is the client identifier and
    keywords is a list of keywords related to client.


def write(self, output):

        view_str = output.encode('ascii', 'ignore')
        if (len(view_str) > 0):
            self.m_ser.write(view_str)
            self.m_ser.flush()
            self.m_ser.reset_input_buffer()
            time.sleep(self.m_force_wait)
        pass

Passthrough for pyserial Serial.write().

Args:
        output (str): Block to write to port


def read(self, len=1024, buffer=None):

        try:
            return self._wrap_socket_library_call(
                lambda: SSL_read(self._ssl.value, len, buffer), ERR_READ_TIMEOUT)
        except openssl_error() as err:
            if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
                raise_ssl_error(ERR_PORT_UNREACHABLE, err)
            raise

Read data from connection

    Read up to len bytes and return them.

Args:
    len -- maximum number of bytes to read

    Return value:
    string containing read bytes


def parse_clnsig(acc, sig, revstat, transcripts):

    clnsig_accsessions = []

    if acc:
    # New format of clinvar allways have integers as accession numbers
        try:
            acc = int(acc)
        except ValueError:
            pass
        # There are sometimes different separators so we need to check which
        # one to use
        if isinstance(acc, int):
            revstat_groups = []
            if revstat:
                revstat_groups = [rev.lstrip('_') for rev in revstat.split(',')]

            sig_groups = []
            if sig:
                for significance in sig.split('/'):
                    splitted_word = significance.split('_')
                    sig_groups.append(' '.join(splitted_word[:2]))

            for sign_term in sig_groups:
                clnsig_accsessions.append({
                    'value': sign_term,
                    'accession': int(acc),
                    'revstat': ', '.join(revstat_groups),
                })
        else:
            # There are sometimes different separators so we need to check which
            # one to use
            acc_groups = acc.split('|')
            sig_groups = sig.split('|')
            revstat_groups = revstat.split('|')
            for acc_group, sig_group, revstat_group in zip(acc_groups, sig_groups, revstat_groups):
                accessions = acc_group.split(',')
                significances = sig_group.split(',')
                revstats = revstat_group.split(',')
                for accession, significance, revstat in zip(accessions, significances, revstats):
                    clnsig_accsessions.append({
                        'value': int(significance),
                        'accession': accession,
                        'revstat': revstat,
                    })

    elif transcripts:
        clnsig = set()
        for transcript in transcripts:
            for annotation in transcript.get('clinsig', []):
                clnsig.add(annotation)
        for annotation in clnsig:
            clnsig_accsessions.append({'value': annotation})

    return clnsig_accsessions

Get the clnsig information

Args:
        acc(str): The clnsig accession number, raw from vcf
        sig(str): The clnsig significance score, raw from vcf
        revstat(str): The clnsig revstat, raw from vcf
        transcripts(iterable(dict))

Returns:
        clnsig_accsessions(list): A list with clnsig accessions


def _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator):

  for idx, func in enumerate(iterator):
    assert callable(func), 'Test generators must yield callables, got %r' % (
        func,)
    if getattr(func, '__x_use_name__', False):
      new_name = func.__name__
    else:
      new_name = '%s%s%d' % (name, _SEPARATOR, idx)
    assert new_name not in dct, (
        'Name of parameterized test case "%s" not unique' % (new_name,))
    dct[new_name] = func
    id_suffix[new_name] = getattr(func, '__x_extra_id__', '')

Adds individual test cases to a dictionary.

Args:
        dct: The target dictionary.
        id_suffix: The dictionary for mapping names to test IDs.
        name: The original name of the test case.
        iterator: The iterator generating the individual test cases.


def ParseFileDownloadedRow(
      self, parser_mediator, query, row, **unused_kwargs):

    query_hash = hash(query)

    event_data = ChromeHistoryFileDownloadedEventData()
    event_data.full_path = self._GetRowValue(query_hash, row, 'target_path')
    event_data.offset = self._GetRowValue(query_hash, row, 'id')
    event_data.query = query
    event_data.received_bytes = self._GetRowValue(
        query_hash, row, 'received_bytes')
    event_data.total_bytes = self._GetRowValue(query_hash, row, 'total_bytes')
    event_data.url = self._GetRowValue(query_hash, row, 'url')

    timestamp = self._GetRowValue(query_hash, row, 'start_time')
    date_time = dfdatetime_webkit_time.WebKitTime(timestamp=timestamp)
    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_FILE_DOWNLOADED)
    parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a file downloaded row.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        query (str): query that created the row.
        row (sqlite3.Row): row.


def SetHeaders(self, soap_headers, http_headers):

    self.suds_client.set_options(soapheaders=soap_headers, headers=http_headers)

Set the headers for the underlying client.

Args:
        soap_headers: A SOAP element for the SOAP headers.
        http_headers: A dictionary for the http headers.


def fill_treeview(self, tree, input_dict):

        tree.model().removeRows(0, tree.model().rowCount())

        def add_element(item, key, value):
            child_name = QtWidgets.QStandardItem(key)

            if isinstance(value, dict):
                for key_child, value_child in value.items():
                    add_element(child_name, key_child, value_child)
                item.appendRow(child_name)
            else:
                child_value = QtWidgets.QStandardItem(str(value))

                item.appendRow([child_name, child_value])

        for index, (key, value) in enumerate(input_dict.items()):

            if isinstance(value, dict):
                item = QtWidgets.QStandardItem(key)
                for sub_key, sub_value in value.items():
                    add_element(item, sub_key, sub_value)
                tree.model().appendRow(item)
            elif isinstance(value, str):
                item = QtGui.QStandardItem(key)
                item_value = QtGui.QStandardItem(value)
                item_value.setEditable(True)
                item_value.setSelectable(True)
                tree.model().appendRow([item, item_value])

fills a treeview with nested parameters

Args:
        tree: QtWidgets.QTreeView
        parameters: dictionary or Parameter object

    Returns:


def parse_cgmlst_alleles(cgmlst_fasta):

    out = defaultdict(list)
    for header, seq in parse_fasta(cgmlst_fasta):
        if not '|' in header:
            raise Exception('Unexpected format for cgMLST fasta file header. No "|" (pipe) delimiter present! Header="{}"'.format(header))
        marker_name, allele_name = header.split('|')
        out[marker_name].append(seq)
    return out

Parse cgMLST alleles from fasta file
    cgMLST FASTA file must have a header format of ">{marker name}|{allele name}"

Args:
        cgmlst_fasta (str): cgMLST fasta file path

Returns:
        dict of list: Marker name to list of allele sequences


def __init__(self, maximum_number_of_items=50000):

    super(_EventSourceHeap, self).__init__()
    self._heap = []
    self._maximum_number_of_items = maximum_number_of_items

Initializes an event source heap.

Args:
        maximum_number_of_items (Optional[int]): maximum number of items
        in the heap.


def sections_list(self, cmd=None):

        sections = list(self.common.sections)
        if not cmd:
            if self.bare is not None:
                sections.extend(self.bare.sections)
                return sections
            return []
        sections.extend(self.subcmds[cmd].sections)
        if cmd in self._conf:
            sections.append(cmd)
        return sections

List of config sections used by a command.

Args:
        cmd (str): command name, set to ``None`` or ``''`` for the bare
            command.

Returns:
        list of str: list of configuration sections used by that command.


def github_belspec_files(spec_dir, force: bool = False):

    if not force:
        dtnow = datetime.datetime.utcnow()
        delta = datetime.timedelta(1)
        yesterday = dtnow - delta

        for fn in glob.glob(f"{spec_dir}/bel*yaml"):
            if datetime.datetime.fromtimestamp(os.path.getmtime(fn)) > yesterday:
                log.info("Skipping BEL Specification update - specs less than 1 day old")
                return

    repo_url = "https://api.github.com/repos/belbio/bel_specifications/contents/specifications"
    params = {}
    github_access_token = os.getenv("GITHUB_ACCESS_TOKEN", "")
    if github_access_token:
        params = {"access_token": github_access_token}

    r = requests.get(repo_url, params=params)
    if r.status_code == 200:
        results = r.json()
        for f in results:
            url = f["download_url"]
            fn = os.path.basename(url)

            if "yaml" not in fn and "yml" in fn:
                fn = fn.replace("yml", "yaml")

            r = requests.get(url, params=params, allow_redirects=True)
            if r.status_code == 200:
                open(f"{spec_dir}/{fn}", "wb").write(r.content)
            else:
                sys.exit(
                    f"Could not get BEL Spec file {url} from Github -- Status: {r.status_code}  Msg: {r.content}"
                )
    else:
        sys.exit(
            f"Could not get BEL Spec directory listing from Github -- Status: {r.status_code}  Msg: {r.content}"
        )

Get belspec files from Github repo

Args:
        spec_dir: directory to store the BEL Specification and derived files
        force: force update of BEL Specifications from Github - skipped if local files less than 1 day old


def drop_account(self, account_cookie):

        if account_cookie in self.account_list:
            res = self.account_list.remove(account_cookie)
            self.cash.append(
                self.cash[-1] + self.get_account_by_cookie(res).init_cash)
            return True
        else:
            raise RuntimeError(
                'account {} is not in the portfolio'.format(account_cookie)
            )

删除一个account

Args:
        account_cookie {[type]} -- [description]

Raises:
        RuntimeError -- [description]


def artist_commentary_revert(self, id_, version_id):

        params = {'version_id': version_id}
        return self._get('artist_commentaries/{0}/revert.json'.format(id_),
                         params, method='PUT', auth=True)

Revert artist commentary (Requires login) (UNTESTED).

    Parameters:
        id_ (int): The artist commentary id.
        version_id (int): The artist commentary version id to
                        revert to.


def do_hook_actions(self, actions, hook_type):

        logger.log_debug("call {} hook actions.".format(hook_type))
        for action in actions:

            if isinstance(action, dict) and len(action) == 1:
                # format 1
                # {"var": "${func()}"}
                var_name, hook_content = list(action.items())[0]
                hook_content_eval = self.session_context.eval_content(hook_content)
                logger.log_debug(
                    "assignment with hook: {} = {} => {}".format(
                        var_name, hook_content, hook_content_eval
                    )
                )
                self.session_context.update_test_variables(
                    var_name, hook_content_eval
                )
            else:
                # format 2
                logger.log_debug("call hook function: {}".format(action))
                # TODO: check hook function if valid
                self.session_context.eval_content(action)

call hook actions.

Args:
        actions (list): each action in actions list maybe in two format.

            format1 (dict): assignment, the value returned by hook function will be assigned to variable.
                {"var": "${func()}"}
            format2 (str): only call hook functions.
                ${func()}

        hook_type (enum): setup/teardown


def __init__(self, logger):

    self.logger = logger
    self.oslogin_installed = True
    self.update_time = 0

Constructor.

Args:
        logger: logger object, used to write to SysLog and serial port.


def add_permission(self, perm):

        self.Permissions(permission=perm)
        PermissionCache.flush()
        self.save()

Soyut Role Permission nesnesi tanımlamayı sağlar.

Args:
        perm (object):


def asset(self, asset_id, asset_type, action='GET'):

        if not self.can_update():
            self._tcex.handle_error(910, [self.type])

        if asset_type == 'PHONE':
            return self.tc_requests.adversary_phone_asset(
                self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
            )
        if asset_type == 'HANDLER':
            return self.tc_requests.adversary_handle_asset(
                self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
            )
        if asset_type == 'URL':
            return self.tc_requests.adversary_url_asset(
                self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
            )
        self._tcex.handle_error(
            925, ['asset_type', 'assets', 'asset_type', 'asset_type', asset_type]
        )
        return None

Gets the asset with the provided id

Args:
        asset_id: The id of the asset to be retrieved
        asset_type: (str) Either PHONE, HANDLER, or URL
        action:

    Returns:


def __init__(self, server):

        self.ready = False
        self.server = server

        self.requests_seen = 0
        self.bytes_read = 0
        self.bytes_written = 0
        self.start_time = None
        self.work_time = 0
        self.stats = {
            'Requests': lambda s: self.requests_seen + (
                self.start_time is None
                and trueyzero
                or self.conn.requests_seen
            ),
            'Bytes Read': lambda s: self.bytes_read + (
                self.start_time is None
                and trueyzero
                or self.conn.rfile.bytes_read
            ),
            'Bytes Written': lambda s: self.bytes_written + (
                self.start_time is None
                and trueyzero
                or self.conn.wfile.bytes_written
            ),
            'Work Time': lambda s: self.work_time + (
                self.start_time is None
                and trueyzero
                or time.time() - self.start_time
            ),
            'Read Throughput': lambda s: s['Bytes Read'](s) / (
                s['Work Time'](s) or 1e-6
            ),
            'Write Throughput': lambda s: s['Bytes Written'](s) / (
                s['Work Time'](s) or 1e-6
            ),
        }
        threading.Thread.__init__(self)

Initialize WorkerThread instance.

Args:
        server (cheroot.server.HTTPServer): web server object
            receiving this request


def find_exe(name, filepath=None):

    if filepath:
        if not os.path.exists(filepath):
            open(filepath)  # raise IOError
        elif not os.path.isfile(filepath):
            raise RezBindError("not a file: %s" % filepath)
    else:
        filepath = which(name)
        if not filepath:
            raise RezBindError("could not find executable: %s" % name)

    return filepath

Find an executable.

Args:
        name: Name of the program, eg 'python'.
        filepath: Path to executable, a search is performed if None.

Returns:
        Path to the executable if found, otherwise an error is raised.


def isfile(self, path, follow_symlinks=True):

        return self._is_of_type(path, S_IFREG, follow_symlinks)

Determine if path identifies a regular file.

Args:
        path: Path to filesystem object.

Returns:
        `True` if path points to a regular file (following symlinks).

Raises:
        TypeError: if path is None.


def get_logging_metric_hook(benchmark_log_dir=None,
                            tensors_to_log=None,
                            every_n_secs=600,
                            **kwargs):  # pylint: disable=unused-argument

  if benchmark_log_dir is None:
    raise ValueError("metric_log_dir should be provided to use metric logger")
  if tensors_to_log is None:
    tensors_to_log = _TENSORS_TO_LOG
  return metric_hook.LoggingMetricHook(
      tensors=tensors_to_log,
      log_dir=benchmark_log_dir,
      every_n_secs=every_n_secs)

Function to get LoggingMetricHook.

Args:
        benchmark_log_dir: `string`, directory path to save the metric log.
        tensors_to_log: List of tensor names or dictionary mapping labels to tensor
        names. If not set, log _TENSORS_TO_LOG by default.
        every_n_secs: `int`, the frequency for logging the metric. Default to every
        10 mins.

Returns:
        Returns a ProfilerHook that writes out timelines that can be loaded into
        profiling tools like chrome://tracing.