Python six.viewvalues() Examples

The following are 14 code examples of six.viewvalues(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module six , or try the search function .
Example #1
Source File: rewardplot.py    From striatum with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calculate_cum_reward(policy):

    """Calculate cumulative reward with respect to time.

        Parameters
        ----------
        policy: bandit object
            The bandit algorithm you want to evaluate.

        Return
        ---------
        cum_reward: dict
            The dict stores {history_id: cumulative reward} .

        cum_n_actions: dict
            The dict stores
            {history_id: cumulative number of recommended actions}.
    """
    cum_reward = {-1: 0.0}
    cum_n_actions = {-1: 0}
    for i in range(policy.history_storage.n_histories):
        reward = policy.history_storage.get_history(i).rewards
        cum_n_actions[i] = cum_n_actions[i - 1] + len(reward)
        cum_reward[i] = cum_reward[i - 1] + sum(six.viewvalues(reward))
    return cum_reward, cum_n_actions 
Example #2
Source File: b301_b302_b305.py    From flake8-bugbear with MIT License 6 votes vote down vote up
def this_is_okay():
    d = {}
    iterkeys(d)
    six.iterkeys(d)
    six.itervalues(d)
    six.iteritems(d)
    six.iterlists(d)
    six.viewkeys(d)
    six.viewvalues(d)
    six.viewlists(d)
    itervalues(d)
    future.utils.iterkeys(d)
    future.utils.itervalues(d)
    future.utils.iteritems(d)
    future.utils.iterlists(d)
    future.utils.viewkeys(d)
    future.utils.viewvalues(d)
    future.utils.viewlists(d)
    six.next(d)
    builtins.next(d) 
Example #3
Source File: network_service.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def _add_mark_rule(src_ip, environment):
    """Add an environment mark for all traffic coming from an IP.

    :param ``str`` src_ip:
        Source IP to be marked
    :param ``str`` environment:
        Environment to use for the mark
    """
    assert environment in _SET_BY_ENVIRONMENT, \
        'Unknown environment: %r' % environment

    target_set = _SET_BY_ENVIRONMENT[environment]
    _LOGGER.debug('Add %s ip %s to ipset %s', environment, src_ip, target_set)
    iptables.add_ip_set(target_set, src_ip)

    # Check that the IP is not marked in any other environment
    other_env_sets = {
        env_set for env_set in six.viewvalues(_SET_BY_ENVIRONMENT)
        if env_set != target_set
    }
    for other_set in other_env_sets:
        if iptables.test_ip_set(other_set, src_ip) is True:
            raise Exception('%r is already in %r' % (src_ip, other_set)) 
Example #4
Source File: capture_collector.py    From cloud-debug-python with Apache License 2.0 6 votes vote down vote up
def CaptureFrameLocals(self, frame):
    """Captures local variables and arguments of the specified frame.

    Args:
      frame: frame to capture locals and arguments.

    Returns:
      (arguments, locals) tuple.
    """
    # Capture all local variables (including method arguments).
    variables = {n: self.CaptureNamedVariable(n, v, 1,
                                              self.default_capture_limits)
                 for n, v in six.viewitems(frame.f_locals)}

    # Split between locals and arguments (keeping arguments in the right order).
    nargs = frame.f_code.co_argcount
    if frame.f_code.co_flags & inspect.CO_VARARGS: nargs += 1
    if frame.f_code.co_flags & inspect.CO_VARKEYWORDS: nargs += 1

    frame_arguments = []
    for argname in frame.f_code.co_varnames[:nargs]:
      if argname in variables: frame_arguments.append(variables.pop(argname))

    return (frame_arguments, list(six.viewvalues(variables))) 
Example #5
Source File: xdict.py    From python-esppy with Apache License 2.0 5 votes vote down vote up
def viewflatvalues(self):
        ''' Return view of flattened values '''
        return six.viewvalues(self.flattened()) 
Example #6
Source File: exp4p.py    From striatum with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _exp4p_score(self, context):
        """The main part of Exp4.P.
        """
        advisor_ids = list(six.viewkeys(context))

        w = self._modelstorage.get_model()['w']
        if len(w) == 0:
            for i in advisor_ids:
                w[i] = 1
        w_sum = sum(six.viewvalues(w))

        action_probs_list = []
        for action_id in self.action_ids:
            weighted_exp = [w[advisor_id] * context[advisor_id][action_id]
                            for advisor_id in advisor_ids]
            prob_vector = np.sum(weighted_exp) / w_sum
            action_probs_list.append((1 - self.n_actions * self.p_min)
                                     * prob_vector
                                     + self.p_min)
        action_probs_list = np.asarray(action_probs_list)
        action_probs_list /= action_probs_list.sum()

        estimated_reward = {}
        uncertainty = {}
        score = {}
        for action_id, action_prob in zip(self.action_ids, action_probs_list):
            estimated_reward[action_id] = action_prob
            uncertainty[action_id] = 0
            score[action_id] = action_prob
        self._modelstorage.save_model(
            {'action_probs': estimated_reward, 'w': w})

        return estimated_reward, uncertainty, score 
Example #7
Source File: exp3.py    From striatum with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _exp3_probs(self):
        """Exp3 algorithm.
        """
        w = self._model_storage.get_model()['w']
        w_sum = sum(six.viewvalues(w))

        probs = {}
        n_actions = self._action_storage.count()
        for action_id in self._action_storage.iterids():
            probs[action_id] = ((1 - self.gamma) * w[action_id]
                                / w_sum
                                + self.gamma / n_actions)

        return probs 
Example #8
Source File: action.py    From striatum with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __iter__(self):
        return iter(six.viewvalues(self._actions)) 
Example #9
Source File: earnings_estimates.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def required_estimates_fields(columns):
    """
    Compute the set of resource columns required to serve
    `columns`.
    """
    # We also expect any of the field names that our loadable columns
    # are mapped to.
    return metadata_columns.union(viewvalues(columns)) 
Example #10
Source File: b301_b302_b305.py    From flake8-bugbear with MIT License 5 votes vote down vote up
def everything_else_is_wrong():
    d = None  # note: bugbear is no type checker
    d.iterkeys()
    d.itervalues()
    d.iteritems()
    d.iterlists()  # Djangoism
    d.viewkeys()
    d.viewvalues()
    d.viewitems()
    d.viewlists()  # Djangoism
    d.next()
    d.keys().next() 
Example #11
Source File: program_reports.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_column_names():
        """
        List names of columns as they should appear in the CSV.
        """
        return six.viewvalues(BuildLearnerProgramReport.field_names_to_columns) 
Example #12
Source File: _interface.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __contains__(self, other):
        '''Returns True if the `other` register is a sub-part of `self`.'''
        return other in six.viewvalues(self.__children__) 
Example #13
Source File: network_service.py    From treadmill with Apache License 2.0 4 votes vote down vote up
def synchronize(self):
        """Cleanup state resource.
        """
        for app_unique_name in six.viewkeys(self._devices.copy()):
            if not self._devices[app_unique_name].get('stale', False):
                continue

            # This is a stale device, destroy it.
            self.on_delete_request(app_unique_name)

        # Reset the container environment sets to the IP we have now cleaned
        # up.  This is more complex than expected because multiple environment
        # can be merged in the same set in _SET_BY_ENVIRONMENT.
        container_env_ips = {}
        for set_name in set(_SET_BY_ENVIRONMENT.values()):
            key = sorted(
                [
                    env for env in _SET_BY_ENVIRONMENT
                    if _SET_BY_ENVIRONMENT[env] == set_name
                ]
            )
            container_env_ips[tuple(key)] = set()

        for set_envs, set_ips in six.viewitems(container_env_ips):
            for device in six.viewvalues(self._devices):
                if device['environment'] not in set_envs:
                    continue
                set_ips.add(device['ip'])

        for set_envs, set_ips in six.viewitems(container_env_ips):
            iptables.atomic_set(
                _SET_BY_ENVIRONMENT[set_envs[0]],
                set_ips,
                set_type='hash:ip',
                family='inet', hashsize=1024, maxelem=65536
            )

        # It is now safe to clean up all remaining vIPs without resource.
        self._vips.garbage_collect()

        # Read bridge status
        self._bridge_mtu = netdev.dev_mtu(self._TMBR_DEV) 
Example #14
Source File: __init__.py    From treadmill with Apache License 2.0 4 votes vote down vote up
def priv_utilization_queue(self):
        """Returns tuples for sorted by global utilization.

        Apps in the queue are ordered by priority, insertion order.

        Adding or removing maintains invariant that apps utilization
        monotonically increases as well.

        Returns local prioritization queue in a tuple where first element is
        utilization ratio, so that this queue is suitable for merging into
        global priority queue.
        """
        def _app_key(app):
            """Compares apps by priority, state, global index
            """
            return (-app.priority, 0 if app.server else 1,
                    app.global_order, app.name)

        prio_queue = sorted(six.viewvalues(self.apps), key=_app_key)

        acc_demand = zero_capacity()
        available = self.reserved + np.finfo(float).eps
        util_before = utilization(acc_demand, self.reserved, available)

        for app in prio_queue:
            acc_demand = acc_demand + app.demand
            util_after = utilization(acc_demand, self.reserved, available)
            # Priority 0 apps are treated specially - utilization is set to
            # max float.
            #
            # This ensures that they are at the end of the all queues.
            if app.priority == 0:
                util_before = _MAX_UTILIZATION
                util_after = _MAX_UTILIZATION

            # All things equal, already scheduled applications have priority
            # over pending.
            pending = 0 if app.server else 1
            if util_after <= self.max_utilization - 1:
                rank = self.rank
                if util_before < 0:
                    rank -= self.rank_adjustment
            else:
                rank = _UNPLACED_RANK

            entry = (rank, util_before, util_after, pending, app.global_order,
                     app)

            util_before = util_after
            yield entry