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
python类Sized()的实例源码
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_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_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_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_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_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:
__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 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:
__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 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:
__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 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:
__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 _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 _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 _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 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 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)