我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用collections.Sized()。
def to_players(self, *players): """ Set the destination of the chat message. :param players: Player instance(s) or player login string(s). Can be a list, or a single entry. :return: Self reference. :rtype: pyplanet.contrib.chat.query.ChatQuery """ # Unpack list in unpacked list if given. if len(players) == 1 and isinstance(players[0], collections.Iterable): players = players[0] # Replace logins. if isinstance(players, Player): self._logins = set() self._logins.add(players.login) elif isinstance(players, str): self._logins = set() self._logins.add(players) elif isinstance(players, collections.Iterable) and isinstance(players, collections.Sized): self._logins = set() self.add_to(players) return self
def test_Sized(self): non_samples = [None, 42, 3.14, 1j, (lambda: (yield))(), (x for x in []), ] for x in non_samples: self.assertNotIsInstance(x, Sized) self.assertFalse(issubclass(type(x), Sized), repr(type(x))) samples = [bytes(), str(), tuple(), list(), set(), frozenset(), dict(), dict().keys(), dict().items(), dict().values(), ] for x in samples: self.assertIsInstance(x, Sized) self.assertTrue(issubclass(type(x), Sized), repr(type(x))) self.validate_abstract_methods(Sized, '__len__') self.validate_isinstance(Sized, '__len__')
def test_Sized(self): non_samples = [None, 42, 3.14, 1j, (lambda: (yield))(), (x for x in []), ] for x in non_samples: self.assertNotIsInstance(x, Sized) self.assertFalse(issubclass(type(x), Sized), repr(type(x))) samples = [str(), tuple(), list(), set(), frozenset(), dict(), dict().keys(), dict().items(), dict().values(), ] for x in samples: self.assertIsInstance(x, Sized) self.assertTrue(issubclass(type(x), Sized), repr(type(x))) self.validate_abstract_methods(Sized, '__len__') self.validate_isinstance(Sized, '__len__')
def test_abc_registry(self): d = dict(a=1) self.assertIsInstance(d.viewkeys(), collections.KeysView) self.assertIsInstance(d.viewkeys(), collections.MappingView) self.assertIsInstance(d.viewkeys(), collections.Set) self.assertIsInstance(d.viewkeys(), collections.Sized) self.assertIsInstance(d.viewkeys(), collections.Iterable) self.assertIsInstance(d.viewkeys(), collections.Container) self.assertIsInstance(d.viewvalues(), collections.ValuesView) self.assertIsInstance(d.viewvalues(), collections.MappingView) self.assertIsInstance(d.viewvalues(), collections.Sized) self.assertIsInstance(d.viewitems(), collections.ItemsView) self.assertIsInstance(d.viewitems(), collections.MappingView) self.assertIsInstance(d.viewitems(), collections.Set) self.assertIsInstance(d.viewitems(), collections.Sized) self.assertIsInstance(d.viewitems(), collections.Iterable) self.assertIsInstance(d.viewitems(), collections.Container)
def test_direct_subclassing(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C(B): pass self.assertTrue(issubclass(C, B)) self.assertFalse(issubclass(int, C))
def test_registration(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C: __hash__ = None # Make sure it isn't hashable by default self.assertFalse(issubclass(C, B), B.__name__) B.register(C) self.assertTrue(issubclass(C, B))
def ensure_flatlist(x): """Flattens a multi-list x to a single index list.""" if isinstance(x[0], Sized): return x[0] return x
def is_singleton(x): """Checks if x is list-like.""" return not isinstance(x, Sized)
def partial_shape(addr, full_shape): """ Calculate the size of the sub-array represented by `addr` """ def size(x, max): if isinstance(x, (int, long, numpy.integer)): return None elif isinstance(x, slice): y = min(max, x.stop or max) # slice limits can go past the bounds return 1 + (y - (x.start or 0) - 1) // (x.step or 1) elif isinstance(x, collections.Sized): if hasattr(x, 'dtype') and x.dtype == bool: return x.sum() else: return len(x) else: raise TypeError("Unsupported index type %s" % type(x)) addr = full_address(addr, full_shape) if isinstance(addr, numpy.ndarray) and addr.dtype == bool: return (addr.sum(),) elif all(isinstance(x, collections.Sized) for x in addr): return (len(addr[0]),) else: shape = [size(x, max) for (x, max) in zip(addr, full_shape)] return tuple([x for x in shape if x is not None]) # remove empty dimensions
def _array_indices(self, addr): self.check_bounds(addr) def axis_indices(x, max): if isinstance(x, (int, long, numpy.integer)): return x elif isinstance(x, slice): # need to handle negative values in slice return numpy.arange((x.start or 0), (x.stop or max), (x.step or 1), dtype=int) elif isinstance(x, collections.Sized): if hasattr(x, 'dtype') and x.dtype == bool: return numpy.arange(max)[x] else: return numpy.array(x) else: raise TypeError("Unsupported index type %s" % type(x)) addr = self._full_address(addr) if isinstance(addr, numpy.ndarray) and addr.dtype == bool: if addr.ndim == 1: return (numpy.arange(self._shape[0])[addr],) else: raise NotImplementedError() elif all(isinstance(x, collections.Sized) for x in addr): indices = [numpy.array(x) for x in addr] return indices else: indices = [axis_indices(x, max) for (x, max) in zip(addr, self._shape)] if len(indices) == 1: return indices elif len(indices) == 2: if isinstance(indices[0], collections.Sized): if isinstance(indices[1], collections.Sized): mesh_xy = numpy.meshgrid(*indices) return (mesh_xy[0].T, mesh_xy[1].T) # meshgrid works on (x,y), not (i,j) return indices else: raise NotImplementedError("Only 1D and 2D arrays supported")
def test_registration(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C: __metaclass__ = type __hash__ = None # Make sure it isn't hashable by default self.assertFalse(issubclass(C, B), B.__name__) B.register(C) self.assertTrue(issubclass(C, B))
def __instancecheck__(self, instance): return (isinstance(instance, collections.Iterable) and isinstance(instance, collections.Sized) and isinstance(instance, collections.Container) and all(isinstance(x, self._type) for x in instance))
def _assert_is_collection(obj): assert not isinstance(obj, basestring) # Module 'collections' has no 'Iterable' member # pylint: disable=no-member if hasattr(collections, 'Iterable') and hasattr(collections, 'Sized'): assert (isinstance(obj, collections.Iterable) and isinstance(obj, collections.Sized))
def is_list(obj): return isinstance(obj, collections.Iterable) and \ isinstance(obj, collections.Sized) and \ not isinstance(obj, (str, collections.Mapping))
def trigger(self, channels, event_name, data, socket_id=None): ''' Trigger an event on one or more channels, see: http://pusher.com/docs/rest_api#method-post-event ''' if isinstance(channels, six.string_types): channels = [channels] if isinstance(channels, dict) or not isinstance(channels, (collections.Sized, collections.Iterable)): raise TypeError("Expected a single or a list of channels") if len(channels) > 10: raise ValueError("Too many channels") channels = list(map(validate_channel, channels)) event_name = ensure_text(event_name, "event_name") if len(event_name) > 200: raise ValueError("event_name too long") if isinstance(data, six.string_types): data = ensure_text(data, "data") else: data = json.dumps(data, cls=self._json_encoder) if len(data) > 10240: raise ValueError("Too much data") params = { 'name': event_name, 'channels': channels, 'data': data } if socket_id: params['socket_id'] = validate_socket_id(socket_id) return Request(self, POST, "/apps/%s/events" % self.app_id, params)
def test_parameter_grid(): # Test basic properties of ParameterGrid. params1 = {"foo": [1, 2, 3]} grid1 = ParameterGrid(params1) assert_true(isinstance(grid1, Iterable)) assert_true(isinstance(grid1, Sized)) assert_equal(len(grid1), 3) assert_grid_iter_equals_getitem(grid1) params2 = {"foo": [4, 2], "bar": ["ham", "spam", "eggs"]} grid2 = ParameterGrid(params2) assert_equal(len(grid2), 6) # loop to assert we can iterate over the grid multiple times for i in xrange(2): # tuple + chain transforms {"a": 1, "b": 2} to ("a", 1, "b", 2) points = set(tuple(chain(*(sorted(p.items())))) for p in grid2) assert_equal(points, set(("bar", x, "foo", y) for x, y in product(params2["bar"], params2["foo"]))) assert_grid_iter_equals_getitem(grid2) # Special case: empty grid (useful to get default estimator settings) empty = ParameterGrid({}) assert_equal(len(empty), 1) assert_equal(list(empty), [{}]) assert_grid_iter_equals_getitem(empty) assert_raises(IndexError, lambda: empty[1]) has_empty = ParameterGrid([{'C': [1, 10]}, {}, {'C': [.5]}]) assert_equal(len(has_empty), 4) assert_equal(list(has_empty), [{'C': 1}, {'C': 10}, {}, {'C': .5}]) assert_grid_iter_equals_getitem(has_empty)
def __init__(self, value, shape=None, dtype=None): """ Create a new lazy array. `value` : may be an int, long, float, bool, NumPy array, iterator, generator or a function, `f(i)` or `f(i,j)`, depending on the dimensions of the array. `f(i,j)` should return a single number when `i` and `j` are integers, and a 1D array when either `i` or `j` or both is a NumPy array (in the latter case the two arrays must have equal lengths). """ self.dtype = dtype self.operations = [] if isinstance(value, basestring): raise TypeError("An larray cannot be created from a string") elif isinstance(value, larray): if shape is not None and value.shape is not None: assert shape == value.shape self._shape = shape or value.shape self.base_value = value.base_value self.dtype = dtype or value.dtype self.operations = value.operations # should deepcopy? elif isinstance(value, collections.Sized): # False for numbers, generators, functions, iterators if have_scipy and sparse.issparse(value): # For sparse matrices self.dtype = dtype or value.dtype elif not isinstance(value, numpy.ndarray): value = numpy.array(value, dtype=dtype) elif dtype is not None: assert numpy.can_cast(value.dtype, dtype, casting='safe') # or could convert value to the provided dtype if shape and value.shape != shape: raise ValueError("Array has shape %s, value has shape %s" % (shape, value.shape)) self._shape = value.shape self.base_value = value else: assert numpy.isreal(value) # also True for callables, generators, iterators self._shape = shape if dtype is None or isinstance(value, dtype): self.base_value = value else: try: self.base_value = dtype(value) except TypeError: self.base_value = value
def check_bounds(self, addr): """ Check whether the given address is within the array bounds. """ def is_boolean_array(arr): return hasattr(arr, 'dtype') and arr.dtype == bool def check_axis(x, size): if isinstance(x, (int, long, numpy.integer)): lower = upper = x elif isinstance(x, slice): lower = x.start or 0 upper = min(x.stop or size - 1, size - 1) # slices are allowed to go past the bounds elif isinstance(x, collections.Sized): if is_boolean_array(x): lower = 0 upper = x.size - 1 else: if len(x) == 0: raise ValueError("Empty address component (address was %s)" % str(addr)) if hasattr(x, "min"): lower = x.min() else: lower = min(x) if hasattr(x, "max"): upper = x.max() else: upper = max(x) else: raise TypeError("Invalid array address: %s (element of type %s)" % (str(addr), type(x))) if (lower < -size) or (upper >= size): raise IndexError("Index out of bounds") full_addr = self._full_address(addr) if isinstance(addr, numpy.ndarray) and addr.dtype == bool: if len(addr.shape) > len(self._shape): raise IndexError("Too many indices for array") for xmax, size in zip(addr.shape, self._shape): upper = xmax - 1 if upper >= size: raise IndexError("Index out of bounds") else: for i, size in zip(full_addr, self._shape): check_axis(i, size)
def __init__(self, iterable=None): r"""Create a new, empty Multiset object. And if given, initialize with elements from input iterable. Or, initialize from a mapping of elements to their multiplicity. Example: >>> ms = Multiset() # a new, empty multiset >>> ms = Multiset('abc') # a new multiset from an iterable >>> ms = Multiset({'a': 4, 'b': 2}) # a new multiset from a mapping Args: iterable: An optional iterable of elements or mapping of elements to multiplicity to initialize the multiset from. """ if isinstance(iterable, BaseMultiset): self._elements = iterable._elements.copy() self._total = iterable._total else: self._elements = _elements = defaultdict(int) _total = 0 if iterable is not None: if isinstance(iterable, _sequence_types): for element in iterable: _elements[element] += 1 _total = len(iterable) elif isinstance(iterable, dict): for element, multiplicity in iterable.items(): if multiplicity > 0: _elements[element] = multiplicity _total += multiplicity elif isinstance(iterable, _iter_types): for element in iterable: _elements[element] += 1 _total += 1 elif isinstance(iterable, Mapping): for element, multiplicity in iterable.items(): if multiplicity > 0: _elements[element] = multiplicity _total += multiplicity elif isinstance(iterable, Sized): for element in iterable: _elements[element] += 1 _total = len(iterable) else: for element in iterable: _elements[element] += 1 _total += 1 self._total = _total
def fit(self, X, y): """Actual fitting, performing the search over parameters.""" parameter_iterable = ParameterGrid(self.param_grid) estimator = self.estimator cv = self.cv n_samples = _num_samples(X) X, y = indexable(X, y) if y is not None: if len(y) != n_samples: raise ValueError('Target variable (y) has a different number ' 'of samples (%i) than data (X: %i samples)' % (len(y), n_samples)) cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) if self.verbose > 0: if isinstance(parameter_iterable, Sized): n_candidates = len(parameter_iterable) print("Fitting {0} folds for each of {1} candidates, totalling" " {2} fits".format(len(cv), n_candidates, n_candidates * len(cv))) base_estimator = clone(self.estimator) pre_dispatch = self.pre_dispatch out = Parallel( n_jobs=self.n_jobs, verbose=self.verbose, pre_dispatch=pre_dispatch )(delayed(cv_fit_and_score)(clone(base_estimator), X, y, self.scoring, parameters, cv=cv) for parameters in parameter_iterable) best = sorted(out, key=lambda x: x[0])[-1] self.best_params_ = best[1] self.best_score_ = best[0] if self.refit: # fit the best estimator using the entire dataset # clone first to work around broken estimators best_estimator = clone(base_estimator).set_params( **best[1]) if y is not None: best_estimator.fit(X, y, **self.fit_params) else: best_estimator.fit(X, **self.fit_params) self.best_estimator_ = best_estimator return self
def fit(self, X, y): """Actual fitting, performing the search over parameters.""" parameter_iterable = ParameterSampler(self.param_distributions, self.n_iter, random_state=self.random_state) estimator = self.estimator cv = self.cv n_samples = _num_samples(X) X, y = indexable(X, y) if y is not None: if len(y) != n_samples: raise ValueError('Target variable (y) has a different number ' 'of samples (%i) than data (X: %i samples)' % (len(y), n_samples)) cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) if self.verbose > 0: if isinstance(parameter_iterable, Sized): n_candidates = len(parameter_iterable) print("Fitting {0} folds for each of {1} candidates, totalling" " {2} fits".format(len(cv), n_candidates, n_candidates * len(cv))) base_estimator = clone(self.estimator) pre_dispatch = self.pre_dispatch out = Parallel( n_jobs=self.n_jobs, verbose=self.verbose, pre_dispatch=pre_dispatch )( delayed(cv_fit_and_score)(clone(base_estimator), X, y, self.scoring, parameters, cv=cv) for parameters in parameter_iterable) best = sorted(out, reverse=True)[0] self.best_params_ = best[1] self.best_score_ = best[0] if self.refit: # fit the best estimator using the entire dataset # clone first to work around broken estimators best_estimator = clone(base_estimator).set_params( **best[1]) if y is not None: best_estimator.fit(X, y, **self.fit_params) else: best_estimator.fit(X, **self.fit_params) self.best_estimator_ = best_estimator return self
def __call__(self, x): """ Evaluates the piecewise linear function using interpolation. This method supports vectorized function calls as the interpolation process can be expensive for high dimensional data. For the case when a single point is provided, the argument x should be a (D,) shaped numpy array or list, where D is the dimension of points in the triangulation. For the vectorized case, the argument x should be a (n,D)-shaped numpy array. """ assert isinstance(x, collections.Sized) if isinstance(x, pyomo.core.kernel.component_piecewise.\ util.numpy.ndarray): if x.shape != self._tri.points.shape[1:]: multi = True assert x.shape[1:] == self._tri.points[0].shape, \ "%s[1] != %s" % (x.shape, self._tri.points[0].shape) else: multi = False else: multi = False _, ndim = self._tri.points.shape i = self._tri.find_simplex(x) if multi: Tinv = self._tri.transform[i,:ndim] r = self._tri.transform[i,ndim] b = pyomo.core.kernel.component_piecewise.util.\ numpy.einsum('ijk,ik->ij', Tinv, x-r) b = pyomo.core.kernel.component_piecewise.util.\ numpy.c_[b, 1 - b.sum(axis=1)] s = self._tri.simplices[i] return (b*self._values[s]).sum(axis=1) else: b = self._tri.transform[i,:ndim,:ndim].dot( x - self._tri.transform[i,ndim,:]) s = self._tri.simplices[i] val = b.dot(self._values[s[:ndim]]) val += (1-b.sum())*self._values[s[ndim]] return val