id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,500
tensorflow/lucid
lucid/misc/io/serialize_array.py
_normalize_array
def _normalize_array(array, domain=(0, 1)): """Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a dtype of uint8 and a domain of 0-255. Args: array: NumPy array representing the image domain: expected range of values in array, defaults to (0, 1), if explicitly set to None will use the array's own range of values and normalize them. Returns: normalized PIL.Image """ # first copy the input so we're never mutating the user's data array = np.array(array) # squeeze helps both with batch=1 and B/W and PIL's mode inference array = np.squeeze(array) assert len(array.shape) <= 3 assert np.issubdtype(array.dtype, np.number) assert not np.isnan(array).any() low, high = np.min(array), np.max(array) if domain is None: message = "No domain specified, normalizing from measured (~%.2f, ~%.2f)" log.debug(message, low, high) domain = (low, high) # clip values if domain was specified and array contains values outside of it if low < domain[0] or high > domain[1]: message = "Clipping domain from (~{:.2f}, ~{:.2f}) to (~{:.2f}, ~{:.2f})." log.info(message.format(low, high, domain[0], domain[1])) array = array.clip(*domain) min_value, max_value = np.iinfo(np.uint8).min, np.iinfo(np.uint8).max # 0, 255 # convert signed to unsigned if needed if np.issubdtype(array.dtype, np.inexact): offset = domain[0] if offset != 0: array -= offset log.debug("Converting inexact array by subtracting -%.2f.", offset) scalar = max_value / (domain[1] - domain[0]) if scalar != 1: array *= scalar log.debug("Converting inexact array by scaling by %.2f.", scalar) return array.clip(min_value, max_value).astype(np.uint8)
python
def _normalize_array(array, domain=(0, 1)): """Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a dtype of uint8 and a domain of 0-255. Args: array: NumPy array representing the image domain: expected range of values in array, defaults to (0, 1), if explicitly set to None will use the array's own range of values and normalize them. Returns: normalized PIL.Image """ # first copy the input so we're never mutating the user's data array = np.array(array) # squeeze helps both with batch=1 and B/W and PIL's mode inference array = np.squeeze(array) assert len(array.shape) <= 3 assert np.issubdtype(array.dtype, np.number) assert not np.isnan(array).any() low, high = np.min(array), np.max(array) if domain is None: message = "No domain specified, normalizing from measured (~%.2f, ~%.2f)" log.debug(message, low, high) domain = (low, high) # clip values if domain was specified and array contains values outside of it if low < domain[0] or high > domain[1]: message = "Clipping domain from (~{:.2f}, ~{:.2f}) to (~{:.2f}, ~{:.2f})." log.info(message.format(low, high, domain[0], domain[1])) array = array.clip(*domain) min_value, max_value = np.iinfo(np.uint8).min, np.iinfo(np.uint8).max # 0, 255 # convert signed to unsigned if needed if np.issubdtype(array.dtype, np.inexact): offset = domain[0] if offset != 0: array -= offset log.debug("Converting inexact array by subtracting -%.2f.", offset) scalar = max_value / (domain[1] - domain[0]) if scalar != 1: array *= scalar log.debug("Converting inexact array by scaling by %.2f.", scalar) return array.clip(min_value, max_value).astype(np.uint8)
[ "def", "_normalize_array", "(", "array", ",", "domain", "=", "(", "0", ",", "1", ")", ")", ":", "# first copy the input so we're never mutating the user's data", "array", "=", "np", ".", "array", "(", "array", ")", "# squeeze helps both with batch=1 and B/W and PIL's mode inference", "array", "=", "np", ".", "squeeze", "(", "array", ")", "assert", "len", "(", "array", ".", "shape", ")", "<=", "3", "assert", "np", ".", "issubdtype", "(", "array", ".", "dtype", ",", "np", ".", "number", ")", "assert", "not", "np", ".", "isnan", "(", "array", ")", ".", "any", "(", ")", "low", ",", "high", "=", "np", ".", "min", "(", "array", ")", ",", "np", ".", "max", "(", "array", ")", "if", "domain", "is", "None", ":", "message", "=", "\"No domain specified, normalizing from measured (~%.2f, ~%.2f)\"", "log", ".", "debug", "(", "message", ",", "low", ",", "high", ")", "domain", "=", "(", "low", ",", "high", ")", "# clip values if domain was specified and array contains values outside of it", "if", "low", "<", "domain", "[", "0", "]", "or", "high", ">", "domain", "[", "1", "]", ":", "message", "=", "\"Clipping domain from (~{:.2f}, ~{:.2f}) to (~{:.2f}, ~{:.2f}).\"", "log", ".", "info", "(", "message", ".", "format", "(", "low", ",", "high", ",", "domain", "[", "0", "]", ",", "domain", "[", "1", "]", ")", ")", "array", "=", "array", ".", "clip", "(", "*", "domain", ")", "min_value", ",", "max_value", "=", "np", ".", "iinfo", "(", "np", ".", "uint8", ")", ".", "min", ",", "np", ".", "iinfo", "(", "np", ".", "uint8", ")", ".", "max", "# 0, 255", "# convert signed to unsigned if needed", "if", "np", ".", "issubdtype", "(", "array", ".", "dtype", ",", "np", ".", "inexact", ")", ":", "offset", "=", "domain", "[", "0", "]", "if", "offset", "!=", "0", ":", "array", "-=", "offset", "log", ".", "debug", "(", "\"Converting inexact array by subtracting -%.2f.\"", ",", "offset", ")", "scalar", "=", "max_value", "/", "(", "domain", "[", "1", "]", "-", "domain", "[", "0", "]", ")", "if", "scalar", "!=", "1", ":", "array", "*=", "scalar", "log", ".", "debug", "(", "\"Converting inexact array by scaling by %.2f.\"", ",", "scalar", ")", "return", "array", ".", "clip", "(", "min_value", ",", "max_value", ")", ".", "astype", "(", "np", ".", "uint8", ")" ]
Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a dtype of uint8 and a domain of 0-255. Args: array: NumPy array representing the image domain: expected range of values in array, defaults to (0, 1), if explicitly set to None will use the array's own range of values and normalize them. Returns: normalized PIL.Image
[ "Given", "an", "arbitrary", "rank", "-", "3", "NumPy", "array", "produce", "one", "representing", "an", "image", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L31-L77
26,501
tensorflow/lucid
lucid/misc/io/serialize_array.py
_serialize_normalized_array
def _serialize_normalized_array(array, fmt='png', quality=70): """Given a normalized array, returns byte representation of image encoding. Args: array: NumPy array of dtype uint8 and range 0 to 255 fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from 0 to 100 for lossy formats Returns: image data as BytesIO buffer """ dtype = array.dtype assert np.issubdtype(dtype, np.unsignedinteger) assert np.max(array) <= np.iinfo(dtype).max assert array.shape[-1] > 1 # array dims must have been squeezed image = PIL.Image.fromarray(array) image_bytes = BytesIO() image.save(image_bytes, fmt, quality=quality) # TODO: Python 3 could save a copy here by using `getbuffer()` instead. image_data = image_bytes.getvalue() return image_data
python
def _serialize_normalized_array(array, fmt='png', quality=70): """Given a normalized array, returns byte representation of image encoding. Args: array: NumPy array of dtype uint8 and range 0 to 255 fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from 0 to 100 for lossy formats Returns: image data as BytesIO buffer """ dtype = array.dtype assert np.issubdtype(dtype, np.unsignedinteger) assert np.max(array) <= np.iinfo(dtype).max assert array.shape[-1] > 1 # array dims must have been squeezed image = PIL.Image.fromarray(array) image_bytes = BytesIO() image.save(image_bytes, fmt, quality=quality) # TODO: Python 3 could save a copy here by using `getbuffer()` instead. image_data = image_bytes.getvalue() return image_data
[ "def", "_serialize_normalized_array", "(", "array", ",", "fmt", "=", "'png'", ",", "quality", "=", "70", ")", ":", "dtype", "=", "array", ".", "dtype", "assert", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "unsignedinteger", ")", "assert", "np", ".", "max", "(", "array", ")", "<=", "np", ".", "iinfo", "(", "dtype", ")", ".", "max", "assert", "array", ".", "shape", "[", "-", "1", "]", ">", "1", "# array dims must have been squeezed", "image", "=", "PIL", ".", "Image", ".", "fromarray", "(", "array", ")", "image_bytes", "=", "BytesIO", "(", ")", "image", ".", "save", "(", "image_bytes", ",", "fmt", ",", "quality", "=", "quality", ")", "# TODO: Python 3 could save a copy here by using `getbuffer()` instead.", "image_data", "=", "image_bytes", ".", "getvalue", "(", ")", "return", "image_data" ]
Given a normalized array, returns byte representation of image encoding. Args: array: NumPy array of dtype uint8 and range 0 to 255 fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from 0 to 100 for lossy formats Returns: image data as BytesIO buffer
[ "Given", "a", "normalized", "array", "returns", "byte", "representation", "of", "image", "encoding", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L80-L101
26,502
tensorflow/lucid
lucid/misc/io/serialize_array.py
serialize_array
def serialize_array(array, domain=(0, 1), fmt='png', quality=70): """Given an arbitrary rank-3 NumPy array, returns the byte representation of the encoded image. Args: array: NumPy array of dtype uint8 and range 0 to 255 domain: expected range of values in array, see `_normalize_array()` fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from 0 to 100 for lossy formats Returns: image data as BytesIO buffer """ normalized = _normalize_array(array, domain=domain) return _serialize_normalized_array(normalized, fmt=fmt, quality=quality)
python
def serialize_array(array, domain=(0, 1), fmt='png', quality=70): """Given an arbitrary rank-3 NumPy array, returns the byte representation of the encoded image. Args: array: NumPy array of dtype uint8 and range 0 to 255 domain: expected range of values in array, see `_normalize_array()` fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from 0 to 100 for lossy formats Returns: image data as BytesIO buffer """ normalized = _normalize_array(array, domain=domain) return _serialize_normalized_array(normalized, fmt=fmt, quality=quality)
[ "def", "serialize_array", "(", "array", ",", "domain", "=", "(", "0", ",", "1", ")", ",", "fmt", "=", "'png'", ",", "quality", "=", "70", ")", ":", "normalized", "=", "_normalize_array", "(", "array", ",", "domain", "=", "domain", ")", "return", "_serialize_normalized_array", "(", "normalized", ",", "fmt", "=", "fmt", ",", "quality", "=", "quality", ")" ]
Given an arbitrary rank-3 NumPy array, returns the byte representation of the encoded image. Args: array: NumPy array of dtype uint8 and range 0 to 255 domain: expected range of values in array, see `_normalize_array()` fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from 0 to 100 for lossy formats Returns: image data as BytesIO buffer
[ "Given", "an", "arbitrary", "rank", "-", "3", "NumPy", "array", "returns", "the", "byte", "representation", "of", "the", "encoded", "image", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L104-L118
26,503
tensorflow/lucid
lucid/misc/channel_reducer.py
ChannelReducer._apply_flat
def _apply_flat(cls, f, acts): """Utility for applying f to inner dimension of acts. Flattens acts into a 2D tensor, applies f, then unflattens so that all dimesnions except innermost are unchanged. """ orig_shape = acts.shape acts_flat = acts.reshape([-1, acts.shape[-1]]) new_flat = f(acts_flat) if not isinstance(new_flat, np.ndarray): return new_flat shape = list(orig_shape[:-1]) + [-1] return new_flat.reshape(shape)
python
def _apply_flat(cls, f, acts): """Utility for applying f to inner dimension of acts. Flattens acts into a 2D tensor, applies f, then unflattens so that all dimesnions except innermost are unchanged. """ orig_shape = acts.shape acts_flat = acts.reshape([-1, acts.shape[-1]]) new_flat = f(acts_flat) if not isinstance(new_flat, np.ndarray): return new_flat shape = list(orig_shape[:-1]) + [-1] return new_flat.reshape(shape)
[ "def", "_apply_flat", "(", "cls", ",", "f", ",", "acts", ")", ":", "orig_shape", "=", "acts", ".", "shape", "acts_flat", "=", "acts", ".", "reshape", "(", "[", "-", "1", ",", "acts", ".", "shape", "[", "-", "1", "]", "]", ")", "new_flat", "=", "f", "(", "acts_flat", ")", "if", "not", "isinstance", "(", "new_flat", ",", "np", ".", "ndarray", ")", ":", "return", "new_flat", "shape", "=", "list", "(", "orig_shape", "[", ":", "-", "1", "]", ")", "+", "[", "-", "1", "]", "return", "new_flat", ".", "reshape", "(", "shape", ")" ]
Utility for applying f to inner dimension of acts. Flattens acts into a 2D tensor, applies f, then unflattens so that all dimesnions except innermost are unchanged.
[ "Utility", "for", "applying", "f", "to", "inner", "dimension", "of", "acts", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/channel_reducer.py#L52-L64
26,504
tensorflow/lucid
lucid/misc/io/showing.py
_image_url
def _image_url(array, fmt='png', mode="data", quality=90, domain=None): """Create a data URL representing an image from a PIL.Image. Args: image: a numpy mode: presently only supports "data" for data URL Returns: URL representing image """ supported_modes = ("data") if mode not in supported_modes: message = "Unsupported mode '%s', should be one of '%s'." raise ValueError(message, mode, supported_modes) image_data = serialize_array(array, fmt=fmt, quality=quality) base64_byte_string = base64.b64encode(image_data).decode('ascii') return "data:image/" + fmt.upper() + ";base64," + base64_byte_string
python
def _image_url(array, fmt='png', mode="data", quality=90, domain=None): """Create a data URL representing an image from a PIL.Image. Args: image: a numpy mode: presently only supports "data" for data URL Returns: URL representing image """ supported_modes = ("data") if mode not in supported_modes: message = "Unsupported mode '%s', should be one of '%s'." raise ValueError(message, mode, supported_modes) image_data = serialize_array(array, fmt=fmt, quality=quality) base64_byte_string = base64.b64encode(image_data).decode('ascii') return "data:image/" + fmt.upper() + ";base64," + base64_byte_string
[ "def", "_image_url", "(", "array", ",", "fmt", "=", "'png'", ",", "mode", "=", "\"data\"", ",", "quality", "=", "90", ",", "domain", "=", "None", ")", ":", "supported_modes", "=", "(", "\"data\"", ")", "if", "mode", "not", "in", "supported_modes", ":", "message", "=", "\"Unsupported mode '%s', should be one of '%s'.\"", "raise", "ValueError", "(", "message", ",", "mode", ",", "supported_modes", ")", "image_data", "=", "serialize_array", "(", "array", ",", "fmt", "=", "fmt", ",", "quality", "=", "quality", ")", "base64_byte_string", "=", "base64", ".", "b64encode", "(", "image_data", ")", ".", "decode", "(", "'ascii'", ")", "return", "\"data:image/\"", "+", "fmt", ".", "upper", "(", ")", "+", "\";base64,\"", "+", "base64_byte_string" ]
Create a data URL representing an image from a PIL.Image. Args: image: a numpy mode: presently only supports "data" for data URL Returns: URL representing image
[ "Create", "a", "data", "URL", "representing", "an", "image", "from", "a", "PIL", ".", "Image", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L39-L56
26,505
tensorflow/lucid
lucid/misc/io/showing.py
image
def image(array, domain=None, width=None, format='png', **kwargs): """Display an image. Args: array: NumPy array representing the image fmt: Image format e.g. png, jpeg domain: Domain of pixel values, inferred from min & max values if None w: width of output image, scaled using nearest neighbor interpolation. size unchanged if None """ image_data = serialize_array(array, fmt=format, domain=domain) image = IPython.display.Image(data=image_data, format=format, width=width) IPython.display.display(image)
python
def image(array, domain=None, width=None, format='png', **kwargs): """Display an image. Args: array: NumPy array representing the image fmt: Image format e.g. png, jpeg domain: Domain of pixel values, inferred from min & max values if None w: width of output image, scaled using nearest neighbor interpolation. size unchanged if None """ image_data = serialize_array(array, fmt=format, domain=domain) image = IPython.display.Image(data=image_data, format=format, width=width) IPython.display.display(image)
[ "def", "image", "(", "array", ",", "domain", "=", "None", ",", "width", "=", "None", ",", "format", "=", "'png'", ",", "*", "*", "kwargs", ")", ":", "image_data", "=", "serialize_array", "(", "array", ",", "fmt", "=", "format", ",", "domain", "=", "domain", ")", "image", "=", "IPython", ".", "display", ".", "Image", "(", "data", "=", "image_data", ",", "format", "=", "format", ",", "width", "=", "width", ")", "IPython", ".", "display", ".", "display", "(", "image", ")" ]
Display an image. Args: array: NumPy array representing the image fmt: Image format e.g. png, jpeg domain: Domain of pixel values, inferred from min & max values if None w: width of output image, scaled using nearest neighbor interpolation. size unchanged if None
[ "Display", "an", "image", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L62-L75
26,506
tensorflow/lucid
lucid/misc/io/showing.py
show
def show(thing, domain=(0, 1), **kwargs): """Display a nupmy array without having to specify what it represents. This module will attempt to infer how to display your tensor based on its rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank 2 and 3 tensors as images. """ if isinstance(thing, np.ndarray): rank = len(thing.shape) if rank == 4: log.debug("Show is assuming rank 4 tensor to be a list of images.") images(thing, domain=domain, **kwargs) elif rank in (2, 3): log.debug("Show is assuming rank 2 or 3 tensor to be an image.") image(thing, domain=domain, **kwargs) else: log.warning("Show only supports numpy arrays of rank 2-4. Using repr().") print(repr(thing)) elif isinstance(thing, (list, tuple)): log.debug("Show is assuming list or tuple to be a collection of images.") images(thing, domain=domain, **kwargs) else: log.warning("Show only supports numpy arrays so far. Using repr().") print(repr(thing))
python
def show(thing, domain=(0, 1), **kwargs): """Display a nupmy array without having to specify what it represents. This module will attempt to infer how to display your tensor based on its rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank 2 and 3 tensors as images. """ if isinstance(thing, np.ndarray): rank = len(thing.shape) if rank == 4: log.debug("Show is assuming rank 4 tensor to be a list of images.") images(thing, domain=domain, **kwargs) elif rank in (2, 3): log.debug("Show is assuming rank 2 or 3 tensor to be an image.") image(thing, domain=domain, **kwargs) else: log.warning("Show only supports numpy arrays of rank 2-4. Using repr().") print(repr(thing)) elif isinstance(thing, (list, tuple)): log.debug("Show is assuming list or tuple to be a collection of images.") images(thing, domain=domain, **kwargs) else: log.warning("Show only supports numpy arrays so far. Using repr().") print(repr(thing))
[ "def", "show", "(", "thing", ",", "domain", "=", "(", "0", ",", "1", ")", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "thing", ",", "np", ".", "ndarray", ")", ":", "rank", "=", "len", "(", "thing", ".", "shape", ")", "if", "rank", "==", "4", ":", "log", ".", "debug", "(", "\"Show is assuming rank 4 tensor to be a list of images.\"", ")", "images", "(", "thing", ",", "domain", "=", "domain", ",", "*", "*", "kwargs", ")", "elif", "rank", "in", "(", "2", ",", "3", ")", ":", "log", ".", "debug", "(", "\"Show is assuming rank 2 or 3 tensor to be an image.\"", ")", "image", "(", "thing", ",", "domain", "=", "domain", ",", "*", "*", "kwargs", ")", "else", ":", "log", ".", "warning", "(", "\"Show only supports numpy arrays of rank 2-4. Using repr().\"", ")", "print", "(", "repr", "(", "thing", ")", ")", "elif", "isinstance", "(", "thing", ",", "(", "list", ",", "tuple", ")", ")", ":", "log", ".", "debug", "(", "\"Show is assuming list or tuple to be a collection of images.\"", ")", "images", "(", "thing", ",", "domain", "=", "domain", ",", "*", "*", "kwargs", ")", "else", ":", "log", ".", "warning", "(", "\"Show only supports numpy arrays so far. Using repr().\"", ")", "print", "(", "repr", "(", "thing", ")", ")" ]
Display a nupmy array without having to specify what it represents. This module will attempt to infer how to display your tensor based on its rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank 2 and 3 tensors as images.
[ "Display", "a", "nupmy", "array", "without", "having", "to", "specify", "what", "it", "represents", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L102-L125
26,507
tensorflow/lucid
lucid/misc/io/showing.py
_strip_consts
def _strip_consts(graph_def, max_const_size=32): """Strip large constant values from graph_def. This is mostly a utility function for graph(), and also originates here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb """ strip_def = tf.GraphDef() for n0 in graph_def.node: n = strip_def.node.add() n.MergeFrom(n0) if n.op == 'Const': tensor = n.attr['value'].tensor size = len(tensor.tensor_content) if size > max_const_size: tensor.tensor_content = tf.compat.as_bytes("<stripped %d bytes>"%size) return strip_def
python
def _strip_consts(graph_def, max_const_size=32): """Strip large constant values from graph_def. This is mostly a utility function for graph(), and also originates here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb """ strip_def = tf.GraphDef() for n0 in graph_def.node: n = strip_def.node.add() n.MergeFrom(n0) if n.op == 'Const': tensor = n.attr['value'].tensor size = len(tensor.tensor_content) if size > max_const_size: tensor.tensor_content = tf.compat.as_bytes("<stripped %d bytes>"%size) return strip_def
[ "def", "_strip_consts", "(", "graph_def", ",", "max_const_size", "=", "32", ")", ":", "strip_def", "=", "tf", ".", "GraphDef", "(", ")", "for", "n0", "in", "graph_def", ".", "node", ":", "n", "=", "strip_def", ".", "node", ".", "add", "(", ")", "n", ".", "MergeFrom", "(", "n0", ")", "if", "n", ".", "op", "==", "'Const'", ":", "tensor", "=", "n", ".", "attr", "[", "'value'", "]", ".", "tensor", "size", "=", "len", "(", "tensor", ".", "tensor_content", ")", "if", "size", ">", "max_const_size", ":", "tensor", ".", "tensor_content", "=", "tf", ".", "compat", ".", "as_bytes", "(", "\"<stripped %d bytes>\"", "%", "size", ")", "return", "strip_def" ]
Strip large constant values from graph_def. This is mostly a utility function for graph(), and also originates here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
[ "Strip", "large", "constant", "values", "from", "graph_def", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L272-L287
26,508
tensorflow/lucid
lucid/misc/ndimage_utils.py
composite
def composite( background_image, foreground_image, foreground_width_ratio=0.25, foreground_position=(0.0, 0.0), ): """Takes two images and composites them.""" if foreground_width_ratio <= 0: return background_image composite = background_image.copy() width = int(foreground_width_ratio * background_image.shape[1]) foreground_resized = resize(foreground_image, width) size = foreground_resized.shape x = int(foreground_position[1] * (background_image.shape[1] - size[1])) y = int(foreground_position[0] * (background_image.shape[0] - size[0])) # TODO: warn if resulting coordinates are out of bounds? composite[y : y + size[0], x : x + size[1]] = foreground_resized return composite
python
def composite( background_image, foreground_image, foreground_width_ratio=0.25, foreground_position=(0.0, 0.0), ): """Takes two images and composites them.""" if foreground_width_ratio <= 0: return background_image composite = background_image.copy() width = int(foreground_width_ratio * background_image.shape[1]) foreground_resized = resize(foreground_image, width) size = foreground_resized.shape x = int(foreground_position[1] * (background_image.shape[1] - size[1])) y = int(foreground_position[0] * (background_image.shape[0] - size[0])) # TODO: warn if resulting coordinates are out of bounds? composite[y : y + size[0], x : x + size[1]] = foreground_resized return composite
[ "def", "composite", "(", "background_image", ",", "foreground_image", ",", "foreground_width_ratio", "=", "0.25", ",", "foreground_position", "=", "(", "0.0", ",", "0.0", ")", ",", ")", ":", "if", "foreground_width_ratio", "<=", "0", ":", "return", "background_image", "composite", "=", "background_image", ".", "copy", "(", ")", "width", "=", "int", "(", "foreground_width_ratio", "*", "background_image", ".", "shape", "[", "1", "]", ")", "foreground_resized", "=", "resize", "(", "foreground_image", ",", "width", ")", "size", "=", "foreground_resized", ".", "shape", "x", "=", "int", "(", "foreground_position", "[", "1", "]", "*", "(", "background_image", ".", "shape", "[", "1", "]", "-", "size", "[", "1", "]", ")", ")", "y", "=", "int", "(", "foreground_position", "[", "0", "]", "*", "(", "background_image", ".", "shape", "[", "0", "]", "-", "size", "[", "0", "]", ")", ")", "# TODO: warn if resulting coordinates are out of bounds?", "composite", "[", "y", ":", "y", "+", "size", "[", "0", "]", ",", "x", ":", "x", "+", "size", "[", "1", "]", "]", "=", "foreground_resized", "return", "composite" ]
Takes two images and composites them.
[ "Takes", "two", "images", "and", "composites", "them", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/ndimage_utils.py#L51-L73
26,509
tensorflow/lucid
lucid/optvis/param/lowres.py
lowres_tensor
def lowres_tensor(shape, underlying_shape, offset=None, sd=None): """Produces a tensor paramaterized by a interpolated lower resolution tensor. This is like what is done in a laplacian pyramid, but a bit more general. It can be a powerful way to describe images. Args: shape: desired shape of resulting tensor underlying_shape: shape of the tensor being resized into final tensor offset: Describes how to offset the interpolated vector (like phase in a Fourier transform). If None, apply no offset. If a scalar, apply the same offset to each dimension; if a list use each entry for each dimension. If a int, offset by that much. If False, do not offset. If True, offset by half the ratio between shape and underlying shape (analagous to 90 degrees). sd: Standard deviation of initial tensor variable. Returns: A tensor paramaterized by a lower resolution tensorflow variable. """ sd = sd or 0.01 init_val = sd * np.random.randn(*underlying_shape).astype("float32") underlying_t = tf.Variable(init_val) t = resize_bilinear_nd(underlying_t, shape) if offset is not None: # Deal with non-list offset if not isinstance(offset, list): offset = len(shape) * [offset] # Deal with the non-int offset entries for n in range(len(offset)): if offset[n] is True: offset[n] = shape[n] / underlying_shape[n] / 2 if offset[n] is False: offset[n] = 0 offset[n] = int(offset[n]) # Actually apply offset by padding and then croping off the excess. padding = [(pad, 0) for pad in offset] t = tf.pad(t, padding, "SYMMETRIC") begin = len(shape) * [0] t = tf.slice(t, begin, shape) return t
python
def lowres_tensor(shape, underlying_shape, offset=None, sd=None): """Produces a tensor paramaterized by a interpolated lower resolution tensor. This is like what is done in a laplacian pyramid, but a bit more general. It can be a powerful way to describe images. Args: shape: desired shape of resulting tensor underlying_shape: shape of the tensor being resized into final tensor offset: Describes how to offset the interpolated vector (like phase in a Fourier transform). If None, apply no offset. If a scalar, apply the same offset to each dimension; if a list use each entry for each dimension. If a int, offset by that much. If False, do not offset. If True, offset by half the ratio between shape and underlying shape (analagous to 90 degrees). sd: Standard deviation of initial tensor variable. Returns: A tensor paramaterized by a lower resolution tensorflow variable. """ sd = sd or 0.01 init_val = sd * np.random.randn(*underlying_shape).astype("float32") underlying_t = tf.Variable(init_val) t = resize_bilinear_nd(underlying_t, shape) if offset is not None: # Deal with non-list offset if not isinstance(offset, list): offset = len(shape) * [offset] # Deal with the non-int offset entries for n in range(len(offset)): if offset[n] is True: offset[n] = shape[n] / underlying_shape[n] / 2 if offset[n] is False: offset[n] = 0 offset[n] = int(offset[n]) # Actually apply offset by padding and then croping off the excess. padding = [(pad, 0) for pad in offset] t = tf.pad(t, padding, "SYMMETRIC") begin = len(shape) * [0] t = tf.slice(t, begin, shape) return t
[ "def", "lowres_tensor", "(", "shape", ",", "underlying_shape", ",", "offset", "=", "None", ",", "sd", "=", "None", ")", ":", "sd", "=", "sd", "or", "0.01", "init_val", "=", "sd", "*", "np", ".", "random", ".", "randn", "(", "*", "underlying_shape", ")", ".", "astype", "(", "\"float32\"", ")", "underlying_t", "=", "tf", ".", "Variable", "(", "init_val", ")", "t", "=", "resize_bilinear_nd", "(", "underlying_t", ",", "shape", ")", "if", "offset", "is", "not", "None", ":", "# Deal with non-list offset", "if", "not", "isinstance", "(", "offset", ",", "list", ")", ":", "offset", "=", "len", "(", "shape", ")", "*", "[", "offset", "]", "# Deal with the non-int offset entries", "for", "n", "in", "range", "(", "len", "(", "offset", ")", ")", ":", "if", "offset", "[", "n", "]", "is", "True", ":", "offset", "[", "n", "]", "=", "shape", "[", "n", "]", "/", "underlying_shape", "[", "n", "]", "/", "2", "if", "offset", "[", "n", "]", "is", "False", ":", "offset", "[", "n", "]", "=", "0", "offset", "[", "n", "]", "=", "int", "(", "offset", "[", "n", "]", ")", "# Actually apply offset by padding and then croping off the excess.", "padding", "=", "[", "(", "pad", ",", "0", ")", "for", "pad", "in", "offset", "]", "t", "=", "tf", ".", "pad", "(", "t", ",", "padding", ",", "\"SYMMETRIC\"", ")", "begin", "=", "len", "(", "shape", ")", "*", "[", "0", "]", "t", "=", "tf", ".", "slice", "(", "t", ",", "begin", ",", "shape", ")", "return", "t" ]
Produces a tensor paramaterized by a interpolated lower resolution tensor. This is like what is done in a laplacian pyramid, but a bit more general. It can be a powerful way to describe images. Args: shape: desired shape of resulting tensor underlying_shape: shape of the tensor being resized into final tensor offset: Describes how to offset the interpolated vector (like phase in a Fourier transform). If None, apply no offset. If a scalar, apply the same offset to each dimension; if a list use each entry for each dimension. If a int, offset by that much. If False, do not offset. If True, offset by half the ratio between shape and underlying shape (analagous to 90 degrees). sd: Standard deviation of initial tensor variable. Returns: A tensor paramaterized by a lower resolution tensorflow variable.
[ "Produces", "a", "tensor", "paramaterized", "by", "a", "interpolated", "lower", "resolution", "tensor", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/lowres.py#L24-L66
26,510
tensorflow/lucid
lucid/misc/tfutil.py
create_session
def create_session(target='', timeout_sec=10): '''Create an intractive TensorFlow session. Helper function that creates TF session that uses growing GPU memory allocation and opration timeout. 'allow_growth' flag prevents TF from allocating the whole GPU memory an once, which is useful when having multiple python sessions sharing the same GPU. ''' graph = tf.Graph() config = tf.ConfigProto() config.gpu_options.allow_growth = True config.operation_timeout_in_ms = int(timeout_sec*1000) return tf.InteractiveSession(target=target, graph=graph, config=config)
python
def create_session(target='', timeout_sec=10): '''Create an intractive TensorFlow session. Helper function that creates TF session that uses growing GPU memory allocation and opration timeout. 'allow_growth' flag prevents TF from allocating the whole GPU memory an once, which is useful when having multiple python sessions sharing the same GPU. ''' graph = tf.Graph() config = tf.ConfigProto() config.gpu_options.allow_growth = True config.operation_timeout_in_ms = int(timeout_sec*1000) return tf.InteractiveSession(target=target, graph=graph, config=config)
[ "def", "create_session", "(", "target", "=", "''", ",", "timeout_sec", "=", "10", ")", ":", "graph", "=", "tf", ".", "Graph", "(", ")", "config", "=", "tf", ".", "ConfigProto", "(", ")", "config", ".", "gpu_options", ".", "allow_growth", "=", "True", "config", ".", "operation_timeout_in_ms", "=", "int", "(", "timeout_sec", "*", "1000", ")", "return", "tf", ".", "InteractiveSession", "(", "target", "=", "target", ",", "graph", "=", "graph", ",", "config", "=", "config", ")" ]
Create an intractive TensorFlow session. Helper function that creates TF session that uses growing GPU memory allocation and opration timeout. 'allow_growth' flag prevents TF from allocating the whole GPU memory an once, which is useful when having multiple python sessions sharing the same GPU.
[ "Create", "an", "intractive", "TensorFlow", "session", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/tfutil.py#L19-L31
26,511
tensorflow/lucid
lucid/misc/io/reading.py
read
def read(url, encoding=None, cache=None, mode="rb"): """Read from any URL. Internally differentiates between URLs supported by tf.gfile, such as URLs with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP URLs. This way users don't need to know about the underlying fetch mechanism. Args: url: a URL including scheme or a local path mode: mode in which to open the file. defaults to binary ('rb') encoding: if specified, encoding that should be used to decode read data if mode is specified to be text ('r'), this defaults to 'utf-8'. cache: whether to attempt caching the resource. Defaults to True only if the given URL specifies a remote resource. Returns: All bytes form the specified resource, or a decoded string of those. """ with read_handle(url, cache, mode=mode) as handle: data = handle.read() if encoding: data = data.decode(encoding) return data
python
def read(url, encoding=None, cache=None, mode="rb"): """Read from any URL. Internally differentiates between URLs supported by tf.gfile, such as URLs with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP URLs. This way users don't need to know about the underlying fetch mechanism. Args: url: a URL including scheme or a local path mode: mode in which to open the file. defaults to binary ('rb') encoding: if specified, encoding that should be used to decode read data if mode is specified to be text ('r'), this defaults to 'utf-8'. cache: whether to attempt caching the resource. Defaults to True only if the given URL specifies a remote resource. Returns: All bytes form the specified resource, or a decoded string of those. """ with read_handle(url, cache, mode=mode) as handle: data = handle.read() if encoding: data = data.decode(encoding) return data
[ "def", "read", "(", "url", ",", "encoding", "=", "None", ",", "cache", "=", "None", ",", "mode", "=", "\"rb\"", ")", ":", "with", "read_handle", "(", "url", ",", "cache", ",", "mode", "=", "mode", ")", "as", "handle", ":", "data", "=", "handle", ".", "read", "(", ")", "if", "encoding", ":", "data", "=", "data", ".", "decode", "(", "encoding", ")", "return", "data" ]
Read from any URL. Internally differentiates between URLs supported by tf.gfile, such as URLs with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP URLs. This way users don't need to know about the underlying fetch mechanism. Args: url: a URL including scheme or a local path mode: mode in which to open the file. defaults to binary ('rb') encoding: if specified, encoding that should be used to decode read data if mode is specified to be text ('r'), this defaults to 'utf-8'. cache: whether to attempt caching the resource. Defaults to True only if the given URL specifies a remote resource. Returns: All bytes form the specified resource, or a decoded string of those.
[ "Read", "from", "any", "URL", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/reading.py#L48-L71
26,512
tensorflow/lucid
lucid/misc/io/reading.py
read_handle
def read_handle(url, cache=None, mode="rb"): """Read from any URL with a file handle. Use this to get a handle to a file rather than eagerly load the data: ``` with read_handle(url) as handle: result = something.load(handle) result.do_something() ``` When program execution leaves this `with` block, the handle will be closed automatically. Args: url: a URL including scheme or a local path Returns: A file handle to the specified resource if it could be reached. The handle will be closed automatically once execution leaves this context. """ scheme = urlparse(url).scheme if cache == 'purge': _purge_cached(url) cache = None if _is_remote(scheme) and cache is None: cache = True log.debug("Cache not specified, enabling because resource is remote.") if cache: handle = _read_and_cache(url, mode=mode) else: if scheme in ("http", "https"): handle = _handle_web_url(url, mode=mode) elif scheme in ("gs"): handle = _handle_gfile(url, mode=mode) else: handle = open(url, mode=mode) yield handle handle.close()
python
def read_handle(url, cache=None, mode="rb"): """Read from any URL with a file handle. Use this to get a handle to a file rather than eagerly load the data: ``` with read_handle(url) as handle: result = something.load(handle) result.do_something() ``` When program execution leaves this `with` block, the handle will be closed automatically. Args: url: a URL including scheme or a local path Returns: A file handle to the specified resource if it could be reached. The handle will be closed automatically once execution leaves this context. """ scheme = urlparse(url).scheme if cache == 'purge': _purge_cached(url) cache = None if _is_remote(scheme) and cache is None: cache = True log.debug("Cache not specified, enabling because resource is remote.") if cache: handle = _read_and_cache(url, mode=mode) else: if scheme in ("http", "https"): handle = _handle_web_url(url, mode=mode) elif scheme in ("gs"): handle = _handle_gfile(url, mode=mode) else: handle = open(url, mode=mode) yield handle handle.close()
[ "def", "read_handle", "(", "url", ",", "cache", "=", "None", ",", "mode", "=", "\"rb\"", ")", ":", "scheme", "=", "urlparse", "(", "url", ")", ".", "scheme", "if", "cache", "==", "'purge'", ":", "_purge_cached", "(", "url", ")", "cache", "=", "None", "if", "_is_remote", "(", "scheme", ")", "and", "cache", "is", "None", ":", "cache", "=", "True", "log", ".", "debug", "(", "\"Cache not specified, enabling because resource is remote.\"", ")", "if", "cache", ":", "handle", "=", "_read_and_cache", "(", "url", ",", "mode", "=", "mode", ")", "else", ":", "if", "scheme", "in", "(", "\"http\"", ",", "\"https\"", ")", ":", "handle", "=", "_handle_web_url", "(", "url", ",", "mode", "=", "mode", ")", "elif", "scheme", "in", "(", "\"gs\"", ")", ":", "handle", "=", "_handle_gfile", "(", "url", ",", "mode", "=", "mode", ")", "else", ":", "handle", "=", "open", "(", "url", ",", "mode", "=", "mode", ")", "yield", "handle", "handle", ".", "close", "(", ")" ]
Read from any URL with a file handle. Use this to get a handle to a file rather than eagerly load the data: ``` with read_handle(url) as handle: result = something.load(handle) result.do_something() ``` When program execution leaves this `with` block, the handle will be closed automatically. Args: url: a URL including scheme or a local path Returns: A file handle to the specified resource if it could be reached. The handle will be closed automatically once execution leaves this context.
[ "Read", "from", "any", "URL", "with", "a", "file", "handle", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/reading.py#L75-L118
26,513
tensorflow/lucid
lucid/misc/io/reading.py
local_cache_path
def local_cache_path(remote_url): """Returns the path that remote_url would be cached at locally.""" local_name = RESERVED_PATH_CHARS.sub("_", remote_url) return os.path.join(gettempdir(), local_name)
python
def local_cache_path(remote_url): """Returns the path that remote_url would be cached at locally.""" local_name = RESERVED_PATH_CHARS.sub("_", remote_url) return os.path.join(gettempdir(), local_name)
[ "def", "local_cache_path", "(", "remote_url", ")", ":", "local_name", "=", "RESERVED_PATH_CHARS", ".", "sub", "(", "\"_\"", ",", "remote_url", ")", "return", "os", ".", "path", ".", "join", "(", "gettempdir", "(", ")", ",", "local_name", ")" ]
Returns the path that remote_url would be cached at locally.
[ "Returns", "the", "path", "that", "remote_url", "would", "be", "cached", "at", "locally", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/reading.py#L142-L145
26,514
tensorflow/lucid
lucid/optvis/param/cppn.py
cppn
def cppn( width, batch=1, num_output_channels=3, num_hidden_channels=24, num_layers=8, activation_func=_composite_activation, normalize=False, ): """Compositional Pattern Producing Network Args: width: width of resulting image, equals height batch: batch dimension of output, note that all params share the same weights! num_output_channels: num_hidden_channels: num_layers: activation_func: normalize: Returns: The collapsed shape, represented as a list. """ r = 3.0 ** 0.5 # std(coord_range) == 1.0 coord_range = tf.linspace(-r, r, width) y, x = tf.meshgrid(coord_range, coord_range, indexing="ij") net = tf.stack([tf.stack([x, y], -1)] * batch, 0) with slim.arg_scope( [slim.conv2d], kernel_size=[1, 1], activation_fn=None, weights_initializer=tf.initializers.variance_scaling(), biases_initializer=tf.initializers.random_normal(0.0, 0.1), ): for i in range(num_layers): x = slim.conv2d(net, num_hidden_channels) if normalize: x = slim.instance_norm(x) net = activation_func(x) rgb = slim.conv2d( net, num_output_channels, activation_fn=tf.nn.sigmoid, weights_initializer=tf.zeros_initializer(), ) return rgb
python
def cppn( width, batch=1, num_output_channels=3, num_hidden_channels=24, num_layers=8, activation_func=_composite_activation, normalize=False, ): """Compositional Pattern Producing Network Args: width: width of resulting image, equals height batch: batch dimension of output, note that all params share the same weights! num_output_channels: num_hidden_channels: num_layers: activation_func: normalize: Returns: The collapsed shape, represented as a list. """ r = 3.0 ** 0.5 # std(coord_range) == 1.0 coord_range = tf.linspace(-r, r, width) y, x = tf.meshgrid(coord_range, coord_range, indexing="ij") net = tf.stack([tf.stack([x, y], -1)] * batch, 0) with slim.arg_scope( [slim.conv2d], kernel_size=[1, 1], activation_fn=None, weights_initializer=tf.initializers.variance_scaling(), biases_initializer=tf.initializers.random_normal(0.0, 0.1), ): for i in range(num_layers): x = slim.conv2d(net, num_hidden_channels) if normalize: x = slim.instance_norm(x) net = activation_func(x) rgb = slim.conv2d( net, num_output_channels, activation_fn=tf.nn.sigmoid, weights_initializer=tf.zeros_initializer(), ) return rgb
[ "def", "cppn", "(", "width", ",", "batch", "=", "1", ",", "num_output_channels", "=", "3", ",", "num_hidden_channels", "=", "24", ",", "num_layers", "=", "8", ",", "activation_func", "=", "_composite_activation", ",", "normalize", "=", "False", ",", ")", ":", "r", "=", "3.0", "**", "0.5", "# std(coord_range) == 1.0", "coord_range", "=", "tf", ".", "linspace", "(", "-", "r", ",", "r", ",", "width", ")", "y", ",", "x", "=", "tf", ".", "meshgrid", "(", "coord_range", ",", "coord_range", ",", "indexing", "=", "\"ij\"", ")", "net", "=", "tf", ".", "stack", "(", "[", "tf", ".", "stack", "(", "[", "x", ",", "y", "]", ",", "-", "1", ")", "]", "*", "batch", ",", "0", ")", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", "]", ",", "kernel_size", "=", "[", "1", ",", "1", "]", ",", "activation_fn", "=", "None", ",", "weights_initializer", "=", "tf", ".", "initializers", ".", "variance_scaling", "(", ")", ",", "biases_initializer", "=", "tf", ".", "initializers", ".", "random_normal", "(", "0.0", ",", "0.1", ")", ",", ")", ":", "for", "i", "in", "range", "(", "num_layers", ")", ":", "x", "=", "slim", ".", "conv2d", "(", "net", ",", "num_hidden_channels", ")", "if", "normalize", ":", "x", "=", "slim", ".", "instance_norm", "(", "x", ")", "net", "=", "activation_func", "(", "x", ")", "rgb", "=", "slim", ".", "conv2d", "(", "net", ",", "num_output_channels", ",", "activation_fn", "=", "tf", ".", "nn", ".", "sigmoid", ",", "weights_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", ")", "return", "rgb" ]
Compositional Pattern Producing Network Args: width: width of resulting image, equals height batch: batch dimension of output, note that all params share the same weights! num_output_channels: num_hidden_channels: num_layers: activation_func: normalize: Returns: The collapsed shape, represented as a list.
[ "Compositional", "Pattern", "Producing", "Network" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/cppn.py#L54-L100
26,515
tensorflow/lucid
lucid/recipes/activation_atlas/main.py
activation_atlas
def activation_atlas( model, layer, grid_size=10, icon_size=96, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, icon_batch_size=32, verbose=False, ): """Renders an Activation Atlas of the given model's layer.""" activations = layer.activations[:number_activations, ...] layout, = aligned_umap(activations, verbose=verbose) directions, coordinates, _ = bin_laid_out_activations( layout, activations, grid_size ) icons = [] for directions_batch in chunked(directions, icon_batch_size): icon_batch, losses = render_icons( directions_batch, model, layer=layer.name, size=icon_size, num_attempts=1 ) icons += icon_batch canvas = make_canvas(icons, coordinates, grid_size) return canvas
python
def activation_atlas( model, layer, grid_size=10, icon_size=96, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, icon_batch_size=32, verbose=False, ): """Renders an Activation Atlas of the given model's layer.""" activations = layer.activations[:number_activations, ...] layout, = aligned_umap(activations, verbose=verbose) directions, coordinates, _ = bin_laid_out_activations( layout, activations, grid_size ) icons = [] for directions_batch in chunked(directions, icon_batch_size): icon_batch, losses = render_icons( directions_batch, model, layer=layer.name, size=icon_size, num_attempts=1 ) icons += icon_batch canvas = make_canvas(icons, coordinates, grid_size) return canvas
[ "def", "activation_atlas", "(", "model", ",", "layer", ",", "grid_size", "=", "10", ",", "icon_size", "=", "96", ",", "number_activations", "=", "NUMBER_OF_AVAILABLE_SAMPLES", ",", "icon_batch_size", "=", "32", ",", "verbose", "=", "False", ",", ")", ":", "activations", "=", "layer", ".", "activations", "[", ":", "number_activations", ",", "...", "]", "layout", ",", "=", "aligned_umap", "(", "activations", ",", "verbose", "=", "verbose", ")", "directions", ",", "coordinates", ",", "_", "=", "bin_laid_out_activations", "(", "layout", ",", "activations", ",", "grid_size", ")", "icons", "=", "[", "]", "for", "directions_batch", "in", "chunked", "(", "directions", ",", "icon_batch_size", ")", ":", "icon_batch", ",", "losses", "=", "render_icons", "(", "directions_batch", ",", "model", ",", "layer", "=", "layer", ".", "name", ",", "size", "=", "icon_size", ",", "num_attempts", "=", "1", ")", "icons", "+=", "icon_batch", "canvas", "=", "make_canvas", "(", "icons", ",", "coordinates", ",", "grid_size", ")", "return", "canvas" ]
Renders an Activation Atlas of the given model's layer.
[ "Renders", "an", "Activation", "Atlas", "of", "the", "given", "model", "s", "layer", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L30-L54
26,516
tensorflow/lucid
lucid/recipes/activation_atlas/main.py
aligned_activation_atlas
def aligned_activation_atlas( model1, layer1, model2, layer2, grid_size=10, icon_size=80, num_steps=1024, whiten_layers=True, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, icon_batch_size=32, verbose=False, ): """Renders two aligned Activation Atlases of the given models' layers. Returns a generator of the two atlasses, and a nested generator for intermediate atlasses while they're being rendered. """ combined_activations = _combine_activations( layer1, layer2, number_activations=number_activations ) layouts = aligned_umap(combined_activations, verbose=verbose) for model, layer, layout in zip((model1, model2), (layer1, layer2), layouts): directions, coordinates, densities = bin_laid_out_activations( layout, layer.activations[:number_activations, ...], grid_size, threshold=10 ) def _progressive_canvas_iterator(): icons = [] for directions_batch in chunked(directions, icon_batch_size): icon_batch, losses = render_icons( directions_batch, model, alpha=False, layer=layer.name, size=icon_size, n_steps=num_steps, S=layer_inverse_covariance(layer) if whiten_layers else None, ) icons += icon_batch yield make_canvas(icons, coordinates, grid_size) yield _progressive_canvas_iterator()
python
def aligned_activation_atlas( model1, layer1, model2, layer2, grid_size=10, icon_size=80, num_steps=1024, whiten_layers=True, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, icon_batch_size=32, verbose=False, ): """Renders two aligned Activation Atlases of the given models' layers. Returns a generator of the two atlasses, and a nested generator for intermediate atlasses while they're being rendered. """ combined_activations = _combine_activations( layer1, layer2, number_activations=number_activations ) layouts = aligned_umap(combined_activations, verbose=verbose) for model, layer, layout in zip((model1, model2), (layer1, layer2), layouts): directions, coordinates, densities = bin_laid_out_activations( layout, layer.activations[:number_activations, ...], grid_size, threshold=10 ) def _progressive_canvas_iterator(): icons = [] for directions_batch in chunked(directions, icon_batch_size): icon_batch, losses = render_icons( directions_batch, model, alpha=False, layer=layer.name, size=icon_size, n_steps=num_steps, S=layer_inverse_covariance(layer) if whiten_layers else None, ) icons += icon_batch yield make_canvas(icons, coordinates, grid_size) yield _progressive_canvas_iterator()
[ "def", "aligned_activation_atlas", "(", "model1", ",", "layer1", ",", "model2", ",", "layer2", ",", "grid_size", "=", "10", ",", "icon_size", "=", "80", ",", "num_steps", "=", "1024", ",", "whiten_layers", "=", "True", ",", "number_activations", "=", "NUMBER_OF_AVAILABLE_SAMPLES", ",", "icon_batch_size", "=", "32", ",", "verbose", "=", "False", ",", ")", ":", "combined_activations", "=", "_combine_activations", "(", "layer1", ",", "layer2", ",", "number_activations", "=", "number_activations", ")", "layouts", "=", "aligned_umap", "(", "combined_activations", ",", "verbose", "=", "verbose", ")", "for", "model", ",", "layer", ",", "layout", "in", "zip", "(", "(", "model1", ",", "model2", ")", ",", "(", "layer1", ",", "layer2", ")", ",", "layouts", ")", ":", "directions", ",", "coordinates", ",", "densities", "=", "bin_laid_out_activations", "(", "layout", ",", "layer", ".", "activations", "[", ":", "number_activations", ",", "...", "]", ",", "grid_size", ",", "threshold", "=", "10", ")", "def", "_progressive_canvas_iterator", "(", ")", ":", "icons", "=", "[", "]", "for", "directions_batch", "in", "chunked", "(", "directions", ",", "icon_batch_size", ")", ":", "icon_batch", ",", "losses", "=", "render_icons", "(", "directions_batch", ",", "model", ",", "alpha", "=", "False", ",", "layer", "=", "layer", ".", "name", ",", "size", "=", "icon_size", ",", "n_steps", "=", "num_steps", ",", "S", "=", "layer_inverse_covariance", "(", "layer", ")", "if", "whiten_layers", "else", "None", ",", ")", "icons", "+=", "icon_batch", "yield", "make_canvas", "(", "icons", ",", "coordinates", ",", "grid_size", ")", "yield", "_progressive_canvas_iterator", "(", ")" ]
Renders two aligned Activation Atlases of the given models' layers. Returns a generator of the two atlasses, and a nested generator for intermediate atlasses while they're being rendered.
[ "Renders", "two", "aligned", "Activation", "Atlases", "of", "the", "given", "models", "layers", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L57-L100
26,517
tensorflow/lucid
lucid/recipes/activation_atlas/main.py
_combine_activations
def _combine_activations( layer1, layer2, activations1=None, activations2=None, mode=ActivationTranslation.BIDIRECTIONAL, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, ): """Given two layers, combines their activations according to mode. ActivationTranslation.ONE_TO_TWO: Translate activations of layer1 into the space of layer2, and return a tuple of the translated activations and the original layer2 activations. ActivationTranslation.BIDIRECTIONAL: Translate activations of layer1 into the space of layer2, activations of layer2 into the space of layer 1, concatenate them along their channels, and returns a tuple of the concatenated activations for each layer. """ activations1 = activations1 or layer1.activations[:number_activations, ...] activations2 = activations2 or layer2.activations[:number_activations, ...] if mode is ActivationTranslation.ONE_TO_TWO: acts_1_to_2 = push_activations(activations1, layer1, layer2) return acts_1_to_2, activations2 elif mode is ActivationTranslation.BIDIRECTIONAL: acts_1_to_2 = push_activations(activations1, layer1, layer2) acts_2_to_1 = push_activations(activations2, layer2, layer1) activations_model1 = np.concatenate((activations1, acts_1_to_2), axis=1) activations_model2 = np.concatenate((acts_2_to_1, activations2), axis=1) return activations_model1, activations_model2
python
def _combine_activations( layer1, layer2, activations1=None, activations2=None, mode=ActivationTranslation.BIDIRECTIONAL, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, ): """Given two layers, combines their activations according to mode. ActivationTranslation.ONE_TO_TWO: Translate activations of layer1 into the space of layer2, and return a tuple of the translated activations and the original layer2 activations. ActivationTranslation.BIDIRECTIONAL: Translate activations of layer1 into the space of layer2, activations of layer2 into the space of layer 1, concatenate them along their channels, and returns a tuple of the concatenated activations for each layer. """ activations1 = activations1 or layer1.activations[:number_activations, ...] activations2 = activations2 or layer2.activations[:number_activations, ...] if mode is ActivationTranslation.ONE_TO_TWO: acts_1_to_2 = push_activations(activations1, layer1, layer2) return acts_1_to_2, activations2 elif mode is ActivationTranslation.BIDIRECTIONAL: acts_1_to_2 = push_activations(activations1, layer1, layer2) acts_2_to_1 = push_activations(activations2, layer2, layer1) activations_model1 = np.concatenate((activations1, acts_1_to_2), axis=1) activations_model2 = np.concatenate((acts_2_to_1, activations2), axis=1) return activations_model1, activations_model2
[ "def", "_combine_activations", "(", "layer1", ",", "layer2", ",", "activations1", "=", "None", ",", "activations2", "=", "None", ",", "mode", "=", "ActivationTranslation", ".", "BIDIRECTIONAL", ",", "number_activations", "=", "NUMBER_OF_AVAILABLE_SAMPLES", ",", ")", ":", "activations1", "=", "activations1", "or", "layer1", ".", "activations", "[", ":", "number_activations", ",", "...", "]", "activations2", "=", "activations2", "or", "layer2", ".", "activations", "[", ":", "number_activations", ",", "...", "]", "if", "mode", "is", "ActivationTranslation", ".", "ONE_TO_TWO", ":", "acts_1_to_2", "=", "push_activations", "(", "activations1", ",", "layer1", ",", "layer2", ")", "return", "acts_1_to_2", ",", "activations2", "elif", "mode", "is", "ActivationTranslation", ".", "BIDIRECTIONAL", ":", "acts_1_to_2", "=", "push_activations", "(", "activations1", ",", "layer1", ",", "layer2", ")", "acts_2_to_1", "=", "push_activations", "(", "activations2", ",", "layer2", ",", "layer1", ")", "activations_model1", "=", "np", ".", "concatenate", "(", "(", "activations1", ",", "acts_1_to_2", ")", ",", "axis", "=", "1", ")", "activations_model2", "=", "np", ".", "concatenate", "(", "(", "acts_2_to_1", ",", "activations2", ")", ",", "axis", "=", "1", ")", "return", "activations_model1", ",", "activations_model2" ]
Given two layers, combines their activations according to mode. ActivationTranslation.ONE_TO_TWO: Translate activations of layer1 into the space of layer2, and return a tuple of the translated activations and the original layer2 activations. ActivationTranslation.BIDIRECTIONAL: Translate activations of layer1 into the space of layer2, activations of layer2 into the space of layer 1, concatenate them along their channels, and returns a tuple of the concatenated activations for each layer.
[ "Given", "two", "layers", "combines", "their", "activations", "according", "to", "mode", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L111-L146
26,518
tensorflow/lucid
lucid/recipes/activation_atlas/main.py
bin_laid_out_activations
def bin_laid_out_activations(layout, activations, grid_size, threshold=5): """Given a layout and activations, overlays a grid on the layout and returns averaged activations for each grid cell. If a cell contains less than `threshold` activations it will be discarded, so the number of returned data is variable.""" assert layout.shape[0] == activations.shape[0] # calculate which grid cells each activation's layout position falls into # first bin stays empty because nothing should be < 0, so we add an extra bin bins = np.linspace(0, 1, num=grid_size + 1) bins[-1] = np.inf # last bin should include all higher values indices = np.digitize(layout, bins) - 1 # subtract 1 to account for empty first bin # because of thresholding we may need to return a variable number of means means, coordinates, counts = [], [], [] # iterate over all grid cell coordinates to compute their average directions grid_coordinates = np.indices((grid_size, grid_size)).transpose().reshape(-1, 2) for xy_coordinates in grid_coordinates: mask = np.equal(xy_coordinates, indices).all(axis=1) count = np.count_nonzero(mask) if count > threshold: counts.append(count) coordinates.append(xy_coordinates) mean = np.average(activations[mask], axis=0) means.append(mean) assert len(means) == len(coordinates) == len(counts) if len(coordinates) == 0: raise RuntimeError("Binning activations led to 0 cells containing activations!") return means, coordinates, counts
python
def bin_laid_out_activations(layout, activations, grid_size, threshold=5): """Given a layout and activations, overlays a grid on the layout and returns averaged activations for each grid cell. If a cell contains less than `threshold` activations it will be discarded, so the number of returned data is variable.""" assert layout.shape[0] == activations.shape[0] # calculate which grid cells each activation's layout position falls into # first bin stays empty because nothing should be < 0, so we add an extra bin bins = np.linspace(0, 1, num=grid_size + 1) bins[-1] = np.inf # last bin should include all higher values indices = np.digitize(layout, bins) - 1 # subtract 1 to account for empty first bin # because of thresholding we may need to return a variable number of means means, coordinates, counts = [], [], [] # iterate over all grid cell coordinates to compute their average directions grid_coordinates = np.indices((grid_size, grid_size)).transpose().reshape(-1, 2) for xy_coordinates in grid_coordinates: mask = np.equal(xy_coordinates, indices).all(axis=1) count = np.count_nonzero(mask) if count > threshold: counts.append(count) coordinates.append(xy_coordinates) mean = np.average(activations[mask], axis=0) means.append(mean) assert len(means) == len(coordinates) == len(counts) if len(coordinates) == 0: raise RuntimeError("Binning activations led to 0 cells containing activations!") return means, coordinates, counts
[ "def", "bin_laid_out_activations", "(", "layout", ",", "activations", ",", "grid_size", ",", "threshold", "=", "5", ")", ":", "assert", "layout", ".", "shape", "[", "0", "]", "==", "activations", ".", "shape", "[", "0", "]", "# calculate which grid cells each activation's layout position falls into", "# first bin stays empty because nothing should be < 0, so we add an extra bin", "bins", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "num", "=", "grid_size", "+", "1", ")", "bins", "[", "-", "1", "]", "=", "np", ".", "inf", "# last bin should include all higher values", "indices", "=", "np", ".", "digitize", "(", "layout", ",", "bins", ")", "-", "1", "# subtract 1 to account for empty first bin", "# because of thresholding we may need to return a variable number of means", "means", ",", "coordinates", ",", "counts", "=", "[", "]", ",", "[", "]", ",", "[", "]", "# iterate over all grid cell coordinates to compute their average directions", "grid_coordinates", "=", "np", ".", "indices", "(", "(", "grid_size", ",", "grid_size", ")", ")", ".", "transpose", "(", ")", ".", "reshape", "(", "-", "1", ",", "2", ")", "for", "xy_coordinates", "in", "grid_coordinates", ":", "mask", "=", "np", ".", "equal", "(", "xy_coordinates", ",", "indices", ")", ".", "all", "(", "axis", "=", "1", ")", "count", "=", "np", ".", "count_nonzero", "(", "mask", ")", "if", "count", ">", "threshold", ":", "counts", ".", "append", "(", "count", ")", "coordinates", ".", "append", "(", "xy_coordinates", ")", "mean", "=", "np", ".", "average", "(", "activations", "[", "mask", "]", ",", "axis", "=", "0", ")", "means", ".", "append", "(", "mean", ")", "assert", "len", "(", "means", ")", "==", "len", "(", "coordinates", ")", "==", "len", "(", "counts", ")", "if", "len", "(", "coordinates", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"Binning activations led to 0 cells containing activations!\"", ")", "return", "means", ",", "coordinates", ",", "counts" ]
Given a layout and activations, overlays a grid on the layout and returns averaged activations for each grid cell. If a cell contains less than `threshold` activations it will be discarded, so the number of returned data is variable.
[ "Given", "a", "layout", "and", "activations", "overlays", "a", "grid", "on", "the", "layout", "and", "returns", "averaged", "activations", "for", "each", "grid", "cell", ".", "If", "a", "cell", "contains", "less", "than", "threshold", "activations", "it", "will", "be", "discarded", "so", "the", "number", "of", "returned", "data", "is", "variable", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L149-L180
26,519
tensorflow/lucid
lucid/modelzoo/util.py
frozen_default_graph_def
def frozen_default_graph_def(input_node_names, output_node_names): """Return frozen and simplified graph_def of default graph.""" sess = tf.get_default_session() input_graph_def = tf.get_default_graph().as_graph_def() pruned_graph = tf.graph_util.remove_training_nodes( input_graph_def, protected_nodes=(output_node_names + input_node_names) ) pruned_graph = tf.graph_util.extract_sub_graph(pruned_graph, output_node_names) # remove explicit device assignments for node in pruned_graph.node: node.device = "" all_variable_names = [v.op.name for v in tf.global_variables()] output_graph_def = tf.graph_util.convert_variables_to_constants( sess=sess, input_graph_def=pruned_graph, output_node_names=output_node_names, variable_names_whitelist=all_variable_names, ) return output_graph_def
python
def frozen_default_graph_def(input_node_names, output_node_names): """Return frozen and simplified graph_def of default graph.""" sess = tf.get_default_session() input_graph_def = tf.get_default_graph().as_graph_def() pruned_graph = tf.graph_util.remove_training_nodes( input_graph_def, protected_nodes=(output_node_names + input_node_names) ) pruned_graph = tf.graph_util.extract_sub_graph(pruned_graph, output_node_names) # remove explicit device assignments for node in pruned_graph.node: node.device = "" all_variable_names = [v.op.name for v in tf.global_variables()] output_graph_def = tf.graph_util.convert_variables_to_constants( sess=sess, input_graph_def=pruned_graph, output_node_names=output_node_names, variable_names_whitelist=all_variable_names, ) return output_graph_def
[ "def", "frozen_default_graph_def", "(", "input_node_names", ",", "output_node_names", ")", ":", "sess", "=", "tf", ".", "get_default_session", "(", ")", "input_graph_def", "=", "tf", ".", "get_default_graph", "(", ")", ".", "as_graph_def", "(", ")", "pruned_graph", "=", "tf", ".", "graph_util", ".", "remove_training_nodes", "(", "input_graph_def", ",", "protected_nodes", "=", "(", "output_node_names", "+", "input_node_names", ")", ")", "pruned_graph", "=", "tf", ".", "graph_util", ".", "extract_sub_graph", "(", "pruned_graph", ",", "output_node_names", ")", "# remove explicit device assignments", "for", "node", "in", "pruned_graph", ".", "node", ":", "node", ".", "device", "=", "\"\"", "all_variable_names", "=", "[", "v", ".", "op", ".", "name", "for", "v", "in", "tf", ".", "global_variables", "(", ")", "]", "output_graph_def", "=", "tf", ".", "graph_util", ".", "convert_variables_to_constants", "(", "sess", "=", "sess", ",", "input_graph_def", "=", "pruned_graph", ",", "output_node_names", "=", "output_node_names", ",", "variable_names_whitelist", "=", "all_variable_names", ",", ")", "return", "output_graph_def" ]
Return frozen and simplified graph_def of default graph.
[ "Return", "frozen", "and", "simplified", "graph_def", "of", "default", "graph", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L61-L84
26,520
tensorflow/lucid
lucid/modelzoo/util.py
infuse_metadata
def infuse_metadata(graph_def, info): """Embed meta data as a string constant in a TF graph. This function takes info, converts it into json, and embeds it in graph_def as a constant op called `__lucid_metadata_json`. """ temp_graph = tf.Graph() with temp_graph.as_default(): tf.constant(json.dumps(info, cls=NumpyJSONEncoder), name=metadata_node_name) meta_node = temp_graph.as_graph_def().node[0] graph_def.node.extend([meta_node])
python
def infuse_metadata(graph_def, info): """Embed meta data as a string constant in a TF graph. This function takes info, converts it into json, and embeds it in graph_def as a constant op called `__lucid_metadata_json`. """ temp_graph = tf.Graph() with temp_graph.as_default(): tf.constant(json.dumps(info, cls=NumpyJSONEncoder), name=metadata_node_name) meta_node = temp_graph.as_graph_def().node[0] graph_def.node.extend([meta_node])
[ "def", "infuse_metadata", "(", "graph_def", ",", "info", ")", ":", "temp_graph", "=", "tf", ".", "Graph", "(", ")", "with", "temp_graph", ".", "as_default", "(", ")", ":", "tf", ".", "constant", "(", "json", ".", "dumps", "(", "info", ",", "cls", "=", "NumpyJSONEncoder", ")", ",", "name", "=", "metadata_node_name", ")", "meta_node", "=", "temp_graph", ".", "as_graph_def", "(", ")", ".", "node", "[", "0", "]", "graph_def", ".", "node", ".", "extend", "(", "[", "meta_node", "]", ")" ]
Embed meta data as a string constant in a TF graph. This function takes info, converts it into json, and embeds it in graph_def as a constant op called `__lucid_metadata_json`.
[ "Embed", "meta", "data", "as", "a", "string", "constant", "in", "a", "TF", "graph", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L89-L99
26,521
tensorflow/lucid
lucid/modelzoo/util.py
extract_metadata
def extract_metadata(graph_def): """Attempt to extract meta data hidden in graph_def. Looks for a `__lucid_metadata_json` constant string op. If present, extract it's content and convert it from json to python. If not, returns None. """ meta_matches = [n for n in graph_def.node if n.name==metadata_node_name] if meta_matches: assert len(meta_matches) == 1, "found more than 1 lucid metadata node!" meta_tensor = meta_matches[0].attr['value'].tensor return json.loads(meta_tensor.string_val[0]) else: return None
python
def extract_metadata(graph_def): """Attempt to extract meta data hidden in graph_def. Looks for a `__lucid_metadata_json` constant string op. If present, extract it's content and convert it from json to python. If not, returns None. """ meta_matches = [n for n in graph_def.node if n.name==metadata_node_name] if meta_matches: assert len(meta_matches) == 1, "found more than 1 lucid metadata node!" meta_tensor = meta_matches[0].attr['value'].tensor return json.loads(meta_tensor.string_val[0]) else: return None
[ "def", "extract_metadata", "(", "graph_def", ")", ":", "meta_matches", "=", "[", "n", "for", "n", "in", "graph_def", ".", "node", "if", "n", ".", "name", "==", "metadata_node_name", "]", "if", "meta_matches", ":", "assert", "len", "(", "meta_matches", ")", "==", "1", ",", "\"found more than 1 lucid metadata node!\"", "meta_tensor", "=", "meta_matches", "[", "0", "]", ".", "attr", "[", "'value'", "]", ".", "tensor", "return", "json", ".", "loads", "(", "meta_tensor", ".", "string_val", "[", "0", "]", ")", "else", ":", "return", "None" ]
Attempt to extract meta data hidden in graph_def. Looks for a `__lucid_metadata_json` constant string op. If present, extract it's content and convert it from json to python. If not, returns None.
[ "Attempt", "to", "extract", "meta", "data", "hidden", "in", "graph_def", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L102-L115
26,522
tensorflow/lucid
lucid/modelzoo/util.py
GraphDefHelper.neighborhood
def neighborhood(self, node, degree=4): """Am I really handcoding graph traversal please no""" assert self.by_name[node.name] == node already_visited = frontier = set([node.name]) for _ in range(degree): neighbor_names = set() for node_name in frontier: outgoing = set(n.name for n in self.by_input[node_name]) incoming = set(self.by_name[node_name].input) neighbor_names |= incoming | outgoing frontier = neighbor_names - already_visited already_visited |= neighbor_names return [self.by_name[name] for name in already_visited]
python
def neighborhood(self, node, degree=4): """Am I really handcoding graph traversal please no""" assert self.by_name[node.name] == node already_visited = frontier = set([node.name]) for _ in range(degree): neighbor_names = set() for node_name in frontier: outgoing = set(n.name for n in self.by_input[node_name]) incoming = set(self.by_name[node_name].input) neighbor_names |= incoming | outgoing frontier = neighbor_names - already_visited already_visited |= neighbor_names return [self.by_name[name] for name in already_visited]
[ "def", "neighborhood", "(", "self", ",", "node", ",", "degree", "=", "4", ")", ":", "assert", "self", ".", "by_name", "[", "node", ".", "name", "]", "==", "node", "already_visited", "=", "frontier", "=", "set", "(", "[", "node", ".", "name", "]", ")", "for", "_", "in", "range", "(", "degree", ")", ":", "neighbor_names", "=", "set", "(", ")", "for", "node_name", "in", "frontier", ":", "outgoing", "=", "set", "(", "n", ".", "name", "for", "n", "in", "self", ".", "by_input", "[", "node_name", "]", ")", "incoming", "=", "set", "(", "self", ".", "by_name", "[", "node_name", "]", ".", "input", ")", "neighbor_names", "|=", "incoming", "|", "outgoing", "frontier", "=", "neighbor_names", "-", "already_visited", "already_visited", "|=", "neighbor_names", "return", "[", "self", ".", "by_name", "[", "name", "]", "for", "name", "in", "already_visited", "]" ]
Am I really handcoding graph traversal please no
[ "Am", "I", "really", "handcoding", "graph", "traversal", "please", "no" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L135-L147
26,523
Rapptz/discord.py
discord/iterators.py
HistoryIterator._retrieve_messages_before_strategy
async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter.""" before = self.before.id if self.before else None data = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data
python
async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter.""" before = self.before.id if self.before else None data = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data
[ "async", "def", "_retrieve_messages_before_strategy", "(", "self", ",", "retrieve", ")", ":", "before", "=", "self", ".", "before", ".", "id", "if", "self", ".", "before", "else", "None", "data", "=", "await", "self", ".", "logs_from", "(", "self", ".", "channel", ".", "id", ",", "retrieve", ",", "before", "=", "before", ")", "if", "len", "(", "data", ")", ":", "if", "self", ".", "limit", "is", "not", "None", ":", "self", ".", "limit", "-=", "retrieve", "self", ".", "before", "=", "Object", "(", "id", "=", "int", "(", "data", "[", "-", "1", "]", "[", "'id'", "]", ")", ")", "return", "data" ]
Retrieve messages using before parameter.
[ "Retrieve", "messages", "using", "before", "parameter", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L325-L333
26,524
Rapptz/discord.py
discord/iterators.py
HistoryIterator._retrieve_messages_after_strategy
async def _retrieve_messages_after_strategy(self, retrieve): """Retrieve messages using after parameter.""" after = self.after.id if self.after else None data = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data
python
async def _retrieve_messages_after_strategy(self, retrieve): """Retrieve messages using after parameter.""" after = self.after.id if self.after else None data = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data
[ "async", "def", "_retrieve_messages_after_strategy", "(", "self", ",", "retrieve", ")", ":", "after", "=", "self", ".", "after", ".", "id", "if", "self", ".", "after", "else", "None", "data", "=", "await", "self", ".", "logs_from", "(", "self", ".", "channel", ".", "id", ",", "retrieve", ",", "after", "=", "after", ")", "if", "len", "(", "data", ")", ":", "if", "self", ".", "limit", "is", "not", "None", ":", "self", ".", "limit", "-=", "retrieve", "self", ".", "after", "=", "Object", "(", "id", "=", "int", "(", "data", "[", "0", "]", "[", "'id'", "]", ")", ")", "return", "data" ]
Retrieve messages using after parameter.
[ "Retrieve", "messages", "using", "after", "parameter", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L335-L343
26,525
Rapptz/discord.py
discord/iterators.py
HistoryIterator._retrieve_messages_around_strategy
async def _retrieve_messages_around_strategy(self, retrieve): """Retrieve messages using around parameter.""" if self.around: around = self.around.id if self.around else None data = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return []
python
async def _retrieve_messages_around_strategy(self, retrieve): """Retrieve messages using around parameter.""" if self.around: around = self.around.id if self.around else None data = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return []
[ "async", "def", "_retrieve_messages_around_strategy", "(", "self", ",", "retrieve", ")", ":", "if", "self", ".", "around", ":", "around", "=", "self", ".", "around", ".", "id", "if", "self", ".", "around", "else", "None", "data", "=", "await", "self", ".", "logs_from", "(", "self", ".", "channel", ".", "id", ",", "retrieve", ",", "around", "=", "around", ")", "self", ".", "around", "=", "None", "return", "data", "return", "[", "]" ]
Retrieve messages using around parameter.
[ "Retrieve", "messages", "using", "around", "parameter", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L345-L352
26,526
Rapptz/discord.py
discord/iterators.py
GuildIterator._retrieve_guilds_before_strategy
async def _retrieve_guilds_before_strategy(self, retrieve): """Retrieve guilds using before parameter.""" before = self.before.id if self.before else None data = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data
python
async def _retrieve_guilds_before_strategy(self, retrieve): """Retrieve guilds using before parameter.""" before = self.before.id if self.before else None data = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data
[ "async", "def", "_retrieve_guilds_before_strategy", "(", "self", ",", "retrieve", ")", ":", "before", "=", "self", ".", "before", ".", "id", "if", "self", ".", "before", "else", "None", "data", "=", "await", "self", ".", "get_guilds", "(", "retrieve", ",", "before", "=", "before", ")", "if", "len", "(", "data", ")", ":", "if", "self", ".", "limit", "is", "not", "None", ":", "self", ".", "limit", "-=", "retrieve", "self", ".", "before", "=", "Object", "(", "id", "=", "int", "(", "data", "[", "-", "1", "]", "[", "'id'", "]", ")", ")", "return", "data" ]
Retrieve guilds using before parameter.
[ "Retrieve", "guilds", "using", "before", "parameter", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L571-L579
26,527
Rapptz/discord.py
discord/iterators.py
GuildIterator._retrieve_guilds_after_strategy
async def _retrieve_guilds_after_strategy(self, retrieve): """Retrieve guilds using after parameter.""" after = self.after.id if self.after else None data = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data
python
async def _retrieve_guilds_after_strategy(self, retrieve): """Retrieve guilds using after parameter.""" after = self.after.id if self.after else None data = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data
[ "async", "def", "_retrieve_guilds_after_strategy", "(", "self", ",", "retrieve", ")", ":", "after", "=", "self", ".", "after", ".", "id", "if", "self", ".", "after", "else", "None", "data", "=", "await", "self", ".", "get_guilds", "(", "retrieve", ",", "after", "=", "after", ")", "if", "len", "(", "data", ")", ":", "if", "self", ".", "limit", "is", "not", "None", ":", "self", ".", "limit", "-=", "retrieve", "self", ".", "after", "=", "Object", "(", "id", "=", "int", "(", "data", "[", "0", "]", "[", "'id'", "]", ")", ")", "return", "data" ]
Retrieve guilds using after parameter.
[ "Retrieve", "guilds", "using", "after", "parameter", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L581-L589
26,528
Rapptz/discord.py
discord/ext/commands/cog.py
Cog.walk_commands
def walk_commands(self): """An iterator that recursively walks through this cog's commands and subcommands.""" from .core import GroupMixin for command in self.__cog_commands__: if command.parent is None: yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
python
def walk_commands(self): """An iterator that recursively walks through this cog's commands and subcommands.""" from .core import GroupMixin for command in self.__cog_commands__: if command.parent is None: yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
[ "def", "walk_commands", "(", "self", ")", ":", "from", ".", "core", "import", "GroupMixin", "for", "command", "in", "self", ".", "__cog_commands__", ":", "if", "command", ".", "parent", "is", "None", ":", "yield", "command", "if", "isinstance", "(", "command", ",", "GroupMixin", ")", ":", "yield", "from", "command", ".", "walk_commands", "(", ")" ]
An iterator that recursively walks through this cog's commands and subcommands.
[ "An", "iterator", "that", "recursively", "walks", "through", "this", "cog", "s", "commands", "and", "subcommands", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/cog.py#L214-L221
26,529
Rapptz/discord.py
discord/ext/commands/cog.py
Cog.listener
def listener(cls, name=None): """A decorator that marks a function as a listener. This is the cog equivalent of :meth:`.Bot.listen`. Parameters ------------ name: :class:`str` The name of the event being listened to. If not provided, it defaults to the function's name. Raises -------- TypeError The function is not a coroutine function or a string was not passed as the name. """ if name is not None and not isinstance(name, str): raise TypeError('Cog.listener expected str but received {0.__class__.__name__!r} instead.'.format(name)) def decorator(func): actual = func if isinstance(actual, staticmethod): actual = actual.__func__ if not inspect.iscoroutinefunction(actual): raise TypeError('Listener function must be a coroutine function.') actual.__cog_listener__ = True to_assign = name or actual.__name__ try: actual.__cog_listener_names__.append(to_assign) except AttributeError: actual.__cog_listener_names__ = [to_assign] # we have to return `func` instead of `actual` because # we need the type to be `staticmethod` for the metaclass # to pick it up but the metaclass unfurls the function and # thus the assignments need to be on the actual function return func return decorator
python
def listener(cls, name=None): """A decorator that marks a function as a listener. This is the cog equivalent of :meth:`.Bot.listen`. Parameters ------------ name: :class:`str` The name of the event being listened to. If not provided, it defaults to the function's name. Raises -------- TypeError The function is not a coroutine function or a string was not passed as the name. """ if name is not None and not isinstance(name, str): raise TypeError('Cog.listener expected str but received {0.__class__.__name__!r} instead.'.format(name)) def decorator(func): actual = func if isinstance(actual, staticmethod): actual = actual.__func__ if not inspect.iscoroutinefunction(actual): raise TypeError('Listener function must be a coroutine function.') actual.__cog_listener__ = True to_assign = name or actual.__name__ try: actual.__cog_listener_names__.append(to_assign) except AttributeError: actual.__cog_listener_names__ = [to_assign] # we have to return `func` instead of `actual` because # we need the type to be `staticmethod` for the metaclass # to pick it up but the metaclass unfurls the function and # thus the assignments need to be on the actual function return func return decorator
[ "def", "listener", "(", "cls", ",", "name", "=", "None", ")", ":", "if", "name", "is", "not", "None", "and", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "TypeError", "(", "'Cog.listener expected str but received {0.__class__.__name__!r} instead.'", ".", "format", "(", "name", ")", ")", "def", "decorator", "(", "func", ")", ":", "actual", "=", "func", "if", "isinstance", "(", "actual", ",", "staticmethod", ")", ":", "actual", "=", "actual", ".", "__func__", "if", "not", "inspect", ".", "iscoroutinefunction", "(", "actual", ")", ":", "raise", "TypeError", "(", "'Listener function must be a coroutine function.'", ")", "actual", ".", "__cog_listener__", "=", "True", "to_assign", "=", "name", "or", "actual", ".", "__name__", "try", ":", "actual", ".", "__cog_listener_names__", ".", "append", "(", "to_assign", ")", "except", "AttributeError", ":", "actual", ".", "__cog_listener_names__", "=", "[", "to_assign", "]", "# we have to return `func` instead of `actual` because", "# we need the type to be `staticmethod` for the metaclass", "# to pick it up but the metaclass unfurls the function and", "# thus the assignments need to be on the actual function", "return", "func", "return", "decorator" ]
A decorator that marks a function as a listener. This is the cog equivalent of :meth:`.Bot.listen`. Parameters ------------ name: :class:`str` The name of the event being listened to. If not provided, it defaults to the function's name. Raises -------- TypeError The function is not a coroutine function or a string was not passed as the name.
[ "A", "decorator", "that", "marks", "a", "function", "as", "a", "listener", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/cog.py#L233-L271
26,530
Rapptz/discord.py
discord/embeds.py
Embed.set_footer
def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed): """Sets the footer for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- text: :class:`str` The footer text. icon_url: :class:`str` The URL of the footer icon. Only HTTP(S) is supported. """ self._footer = {} if text is not EmptyEmbed: self._footer['text'] = str(text) if icon_url is not EmptyEmbed: self._footer['icon_url'] = str(icon_url) return self
python
def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed): """Sets the footer for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- text: :class:`str` The footer text. icon_url: :class:`str` The URL of the footer icon. Only HTTP(S) is supported. """ self._footer = {} if text is not EmptyEmbed: self._footer['text'] = str(text) if icon_url is not EmptyEmbed: self._footer['icon_url'] = str(icon_url) return self
[ "def", "set_footer", "(", "self", ",", "*", ",", "text", "=", "EmptyEmbed", ",", "icon_url", "=", "EmptyEmbed", ")", ":", "self", ".", "_footer", "=", "{", "}", "if", "text", "is", "not", "EmptyEmbed", ":", "self", ".", "_footer", "[", "'text'", "]", "=", "str", "(", "text", ")", "if", "icon_url", "is", "not", "EmptyEmbed", ":", "self", ".", "_footer", "[", "'icon_url'", "]", "=", "str", "(", "icon_url", ")", "return", "self" ]
Sets the footer for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- text: :class:`str` The footer text. icon_url: :class:`str` The URL of the footer icon. Only HTTP(S) is supported.
[ "Sets", "the", "footer", "for", "the", "embed", "content", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L233-L254
26,531
Rapptz/discord.py
discord/embeds.py
Embed.set_author
def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed): """Sets the author for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the author. url: :class:`str` The URL for the author. icon_url: :class:`str` The URL of the author icon. Only HTTP(S) is supported. """ self._author = { 'name': str(name) } if url is not EmptyEmbed: self._author['url'] = str(url) if icon_url is not EmptyEmbed: self._author['icon_url'] = str(icon_url) return self
python
def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed): """Sets the author for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the author. url: :class:`str` The URL for the author. icon_url: :class:`str` The URL of the author icon. Only HTTP(S) is supported. """ self._author = { 'name': str(name) } if url is not EmptyEmbed: self._author['url'] = str(url) if icon_url is not EmptyEmbed: self._author['icon_url'] = str(icon_url) return self
[ "def", "set_author", "(", "self", ",", "*", ",", "name", ",", "url", "=", "EmptyEmbed", ",", "icon_url", "=", "EmptyEmbed", ")", ":", "self", ".", "_author", "=", "{", "'name'", ":", "str", "(", "name", ")", "}", "if", "url", "is", "not", "EmptyEmbed", ":", "self", ".", "_author", "[", "'url'", "]", "=", "str", "(", "url", ")", "if", "icon_url", "is", "not", "EmptyEmbed", ":", "self", ".", "_author", "[", "'icon_url'", "]", "=", "str", "(", "icon_url", ")", "return", "self" ]
Sets the author for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the author. url: :class:`str` The URL for the author. icon_url: :class:`str` The URL of the author icon. Only HTTP(S) is supported.
[ "Sets", "the", "author", "for", "the", "embed", "content", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L356-L382
26,532
Rapptz/discord.py
discord/embeds.py
Embed.add_field
def add_field(self, *, name, value, inline=True): """Adds a field to the embed object. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. """ field = { 'inline': inline, 'name': str(name), 'value': str(value) } try: self._fields.append(field) except AttributeError: self._fields = [field] return self
python
def add_field(self, *, name, value, inline=True): """Adds a field to the embed object. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. """ field = { 'inline': inline, 'name': str(name), 'value': str(value) } try: self._fields.append(field) except AttributeError: self._fields = [field] return self
[ "def", "add_field", "(", "self", ",", "*", ",", "name", ",", "value", ",", "inline", "=", "True", ")", ":", "field", "=", "{", "'inline'", ":", "inline", ",", "'name'", ":", "str", "(", "name", ")", ",", "'value'", ":", "str", "(", "value", ")", "}", "try", ":", "self", ".", "_fields", ".", "append", "(", "field", ")", "except", "AttributeError", ":", "self", ".", "_fields", "=", "[", "field", "]", "return", "self" ]
Adds a field to the embed object. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline.
[ "Adds", "a", "field", "to", "the", "embed", "object", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L394-L421
26,533
Rapptz/discord.py
discord/embeds.py
Embed.set_field_at
def set_field_at(self, index, *, name, value, inline=True): """Modifies a field to the embed object. The index must point to a valid pre-existing field. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- index: :class:`int` The index of the field to modify. name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. Raises ------- IndexError An invalid index was provided. """ try: field = self._fields[index] except (TypeError, IndexError, AttributeError): raise IndexError('field index out of range') field['name'] = str(name) field['value'] = str(value) field['inline'] = inline return self
python
def set_field_at(self, index, *, name, value, inline=True): """Modifies a field to the embed object. The index must point to a valid pre-existing field. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- index: :class:`int` The index of the field to modify. name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. Raises ------- IndexError An invalid index was provided. """ try: field = self._fields[index] except (TypeError, IndexError, AttributeError): raise IndexError('field index out of range') field['name'] = str(name) field['value'] = str(value) field['inline'] = inline return self
[ "def", "set_field_at", "(", "self", ",", "index", ",", "*", ",", "name", ",", "value", ",", "inline", "=", "True", ")", ":", "try", ":", "field", "=", "self", ".", "_fields", "[", "index", "]", "except", "(", "TypeError", ",", "IndexError", ",", "AttributeError", ")", ":", "raise", "IndexError", "(", "'field index out of range'", ")", "field", "[", "'name'", "]", "=", "str", "(", "name", ")", "field", "[", "'value'", "]", "=", "str", "(", "value", ")", "field", "[", "'inline'", "]", "=", "inline", "return", "self" ]
Modifies a field to the embed object. The index must point to a valid pre-existing field. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- index: :class:`int` The index of the field to modify. name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. Raises ------- IndexError An invalid index was provided.
[ "Modifies", "a", "field", "to", "the", "embed", "object", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L451-L484
26,534
Rapptz/discord.py
discord/user.py
BaseUser.avatar_url_as
def avatar_url_as(self, *, format=None, static_format='webp', size=1024): """Returns a friendly URL version of the avatar the user has. If the user does not have a traditional avatar, their default avatar URL is returned instead. The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 1024. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is automatically detected into either 'gif' or static_format depending on the avatar being animated or not. static_format: Optional[:class:`str`] Format to attempt to convert only non-animated avatars to. Defaults to 'webp' size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or ``static_format``, or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_avatar(self._state, self, format=format, static_format=static_format, size=size)
python
def avatar_url_as(self, *, format=None, static_format='webp', size=1024): """Returns a friendly URL version of the avatar the user has. If the user does not have a traditional avatar, their default avatar URL is returned instead. The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 1024. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is automatically detected into either 'gif' or static_format depending on the avatar being animated or not. static_format: Optional[:class:`str`] Format to attempt to convert only non-animated avatars to. Defaults to 'webp' size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or ``static_format``, or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_avatar(self._state, self, format=format, static_format=static_format, size=size)
[ "def", "avatar_url_as", "(", "self", ",", "*", ",", "format", "=", "None", ",", "static_format", "=", "'webp'", ",", "size", "=", "1024", ")", ":", "return", "Asset", ".", "_from_avatar", "(", "self", ".", "_state", ",", "self", ",", "format", "=", "format", ",", "static_format", "=", "static_format", ",", "size", "=", "size", ")" ]
Returns a friendly URL version of the avatar the user has. If the user does not have a traditional avatar, their default avatar URL is returned instead. The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 1024. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is automatically detected into either 'gif' or static_format depending on the avatar being animated or not. static_format: Optional[:class:`str`] Format to attempt to convert only non-animated avatars to. Defaults to 'webp' size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or ``static_format``, or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset.
[ "Returns", "a", "friendly", "URL", "version", "of", "the", "avatar", "the", "user", "has", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L131-L165
26,535
Rapptz/discord.py
discord/user.py
BaseUser.mentioned_in
def mentioned_in(self, message): """Checks if the user is mentioned in the specified message. Parameters ----------- message: :class:`Message` The message to check if you're mentioned in. """ if message.mention_everyone: return True for user in message.mentions: if user.id == self.id: return True return False
python
def mentioned_in(self, message): """Checks if the user is mentioned in the specified message. Parameters ----------- message: :class:`Message` The message to check if you're mentioned in. """ if message.mention_everyone: return True for user in message.mentions: if user.id == self.id: return True return False
[ "def", "mentioned_in", "(", "self", ",", "message", ")", ":", "if", "message", ".", "mention_everyone", ":", "return", "True", "for", "user", "in", "message", ".", "mentions", ":", "if", "user", ".", "id", "==", "self", ".", "id", ":", "return", "True", "return", "False" ]
Checks if the user is mentioned in the specified message. Parameters ----------- message: :class:`Message` The message to check if you're mentioned in.
[ "Checks", "if", "the", "user", "is", "mentioned", "in", "the", "specified", "message", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L226-L242
26,536
Rapptz/discord.py
discord/utils.py
time_snowflake
def time_snowflake(datetime_obj, high=False): """Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive Parameters ----------- datetime_obj A timezone-naive datetime object representing UTC time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low. """ unix_seconds = (datetime_obj - type(datetime_obj)(1970, 1, 1)).total_seconds() discord_millis = int(unix_seconds * 1000 - DISCORD_EPOCH) return (discord_millis << 22) + (2**22-1 if high else 0)
python
def time_snowflake(datetime_obj, high=False): """Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive Parameters ----------- datetime_obj A timezone-naive datetime object representing UTC time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low. """ unix_seconds = (datetime_obj - type(datetime_obj)(1970, 1, 1)).total_seconds() discord_millis = int(unix_seconds * 1000 - DISCORD_EPOCH) return (discord_millis << 22) + (2**22-1 if high else 0)
[ "def", "time_snowflake", "(", "datetime_obj", ",", "high", "=", "False", ")", ":", "unix_seconds", "=", "(", "datetime_obj", "-", "type", "(", "datetime_obj", ")", "(", "1970", ",", "1", ",", "1", ")", ")", ".", "total_seconds", "(", ")", "discord_millis", "=", "int", "(", "unix_seconds", "*", "1000", "-", "DISCORD_EPOCH", ")", "return", "(", "discord_millis", "<<", "22", ")", "+", "(", "2", "**", "22", "-", "1", "if", "high", "else", "0", ")" ]
Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive Parameters ----------- datetime_obj A timezone-naive datetime object representing UTC time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low.
[ "Returns", "a", "numeric", "snowflake", "pretending", "to", "be", "created", "at", "the", "given", "date", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L160-L176
26,537
Rapptz/discord.py
discord/utils.py
_string_width
def _string_width(string, *, _IS_ASCII=_IS_ASCII): """Returns string's width.""" match = _IS_ASCII.match(string) if match: return match.endpos UNICODE_WIDE_CHAR_TYPE = 'WFA' width = 0 func = unicodedata.east_asian_width for char in string: width += 2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 return width
python
def _string_width(string, *, _IS_ASCII=_IS_ASCII): """Returns string's width.""" match = _IS_ASCII.match(string) if match: return match.endpos UNICODE_WIDE_CHAR_TYPE = 'WFA' width = 0 func = unicodedata.east_asian_width for char in string: width += 2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 return width
[ "def", "_string_width", "(", "string", ",", "*", ",", "_IS_ASCII", "=", "_IS_ASCII", ")", ":", "match", "=", "_IS_ASCII", ".", "match", "(", "string", ")", "if", "match", ":", "return", "match", ".", "endpos", "UNICODE_WIDE_CHAR_TYPE", "=", "'WFA'", "width", "=", "0", "func", "=", "unicodedata", ".", "east_asian_width", "for", "char", "in", "string", ":", "width", "+=", "2", "if", "func", "(", "char", ")", "in", "UNICODE_WIDE_CHAR_TYPE", "else", "1", "return", "width" ]
Returns string's width.
[ "Returns", "string", "s", "width", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L359-L370
26,538
Rapptz/discord.py
discord/utils.py
escape_markdown
def escape_markdown(text, *, as_needed=False, ignore_links=True): r"""A helper function that escapes Discord's markdown. Parameters ----------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters escaped with a slash. """ if not as_needed: url_regex = r'(?P<url>(?:https?|steam)://(?:-\.)?(?:[^\s/?\.#-]+\.?)+(?:/[^\s]*)?)' def replacement(match): groupdict = match.groupdict() is_url = groupdict.get('url') if is_url: return is_url return '\\' + groupdict['markdown'] regex = r'(?P<markdown>[_\\~|\*`])' if ignore_links: regex = '(?:%s|%s)' % (url_regex, regex) return re.sub(regex, replacement, text) else: text = re.sub(r'\\', r'\\\\', text) return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)
python
def escape_markdown(text, *, as_needed=False, ignore_links=True): r"""A helper function that escapes Discord's markdown. Parameters ----------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters escaped with a slash. """ if not as_needed: url_regex = r'(?P<url>(?:https?|steam)://(?:-\.)?(?:[^\s/?\.#-]+\.?)+(?:/[^\s]*)?)' def replacement(match): groupdict = match.groupdict() is_url = groupdict.get('url') if is_url: return is_url return '\\' + groupdict['markdown'] regex = r'(?P<markdown>[_\\~|\*`])' if ignore_links: regex = '(?:%s|%s)' % (url_regex, regex) return re.sub(regex, replacement, text) else: text = re.sub(r'\\', r'\\\\', text) return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)
[ "def", "escape_markdown", "(", "text", ",", "*", ",", "as_needed", "=", "False", ",", "ignore_links", "=", "True", ")", ":", "if", "not", "as_needed", ":", "url_regex", "=", "r'(?P<url>(?:https?|steam)://(?:-\\.)?(?:[^\\s/?\\.#-]+\\.?)+(?:/[^\\s]*)?)'", "def", "replacement", "(", "match", ")", ":", "groupdict", "=", "match", ".", "groupdict", "(", ")", "is_url", "=", "groupdict", ".", "get", "(", "'url'", ")", "if", "is_url", ":", "return", "is_url", "return", "'\\\\'", "+", "groupdict", "[", "'markdown'", "]", "regex", "=", "r'(?P<markdown>[_\\\\~|\\*`])'", "if", "ignore_links", ":", "regex", "=", "'(?:%s|%s)'", "%", "(", "url_regex", ",", "regex", ")", "return", "re", ".", "sub", "(", "regex", ",", "replacement", ",", "text", ")", "else", ":", "text", "=", "re", ".", "sub", "(", "r'\\\\'", ",", "r'\\\\\\\\'", ",", "text", ")", "return", "_MARKDOWN_ESCAPE_REGEX", ".", "sub", "(", "r'\\\\\\1'", ",", "text", ")" ]
r"""A helper function that escapes Discord's markdown. Parameters ----------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters escaped with a slash.
[ "r", "A", "helper", "function", "that", "escapes", "Discord", "s", "markdown", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L401-L441
26,539
Rapptz/discord.py
examples/basic_bot.py
add
async def add(ctx, left: int, right: int): """Adds two numbers together.""" await ctx.send(left + right)
python
async def add(ctx, left: int, right: int): """Adds two numbers together.""" await ctx.send(left + right)
[ "async", "def", "add", "(", "ctx", ",", "left", ":", "int", ",", "right", ":", "int", ")", ":", "await", "ctx", ".", "send", "(", "left", "+", "right", ")" ]
Adds two numbers together.
[ "Adds", "two", "numbers", "together", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_bot.py#L19-L21
26,540
Rapptz/discord.py
examples/basic_bot.py
roll
async def roll(ctx, dice: str): """Rolls a dice in NdN format.""" try: rolls, limit = map(int, dice.split('d')) except Exception: await ctx.send('Format has to be in NdN!') return result = ', '.join(str(random.randint(1, limit)) for r in range(rolls)) await ctx.send(result)
python
async def roll(ctx, dice: str): """Rolls a dice in NdN format.""" try: rolls, limit = map(int, dice.split('d')) except Exception: await ctx.send('Format has to be in NdN!') return result = ', '.join(str(random.randint(1, limit)) for r in range(rolls)) await ctx.send(result)
[ "async", "def", "roll", "(", "ctx", ",", "dice", ":", "str", ")", ":", "try", ":", "rolls", ",", "limit", "=", "map", "(", "int", ",", "dice", ".", "split", "(", "'d'", ")", ")", "except", "Exception", ":", "await", "ctx", ".", "send", "(", "'Format has to be in NdN!'", ")", "return", "result", "=", "', '", ".", "join", "(", "str", "(", "random", ".", "randint", "(", "1", ",", "limit", ")", ")", "for", "r", "in", "range", "(", "rolls", ")", ")", "await", "ctx", ".", "send", "(", "result", ")" ]
Rolls a dice in NdN format.
[ "Rolls", "a", "dice", "in", "NdN", "format", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_bot.py#L24-L33
26,541
Rapptz/discord.py
examples/basic_bot.py
repeat
async def repeat(ctx, times: int, content='repeating...'): """Repeats a message multiple times.""" for i in range(times): await ctx.send(content)
python
async def repeat(ctx, times: int, content='repeating...'): """Repeats a message multiple times.""" for i in range(times): await ctx.send(content)
[ "async", "def", "repeat", "(", "ctx", ",", "times", ":", "int", ",", "content", "=", "'repeating...'", ")", ":", "for", "i", "in", "range", "(", "times", ")", ":", "await", "ctx", ".", "send", "(", "content", ")" ]
Repeats a message multiple times.
[ "Repeats", "a", "message", "multiple", "times", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_bot.py#L41-L44
26,542
Rapptz/discord.py
examples/basic_voice.py
Music.join
async def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel""" if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect()
python
async def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel""" if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect()
[ "async", "def", "join", "(", "self", ",", "ctx", ",", "*", ",", "channel", ":", "discord", ".", "VoiceChannel", ")", ":", "if", "ctx", ".", "voice_client", "is", "not", "None", ":", "return", "await", "ctx", ".", "voice_client", ".", "move_to", "(", "channel", ")", "await", "channel", ".", "connect", "(", ")" ]
Joins a voice channel
[ "Joins", "a", "voice", "channel" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_voice.py#L60-L66
26,543
Rapptz/discord.py
examples/basic_voice.py
Music.play
async def play(self, ctx, *, query): """Plays a file from the local filesystem""" source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query)) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send('Now playing: {}'.format(query))
python
async def play(self, ctx, *, query): """Plays a file from the local filesystem""" source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query)) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send('Now playing: {}'.format(query))
[ "async", "def", "play", "(", "self", ",", "ctx", ",", "*", ",", "query", ")", ":", "source", "=", "discord", ".", "PCMVolumeTransformer", "(", "discord", ".", "FFmpegPCMAudio", "(", "query", ")", ")", "ctx", ".", "voice_client", ".", "play", "(", "source", ",", "after", "=", "lambda", "e", ":", "print", "(", "'Player error: %s'", "%", "e", ")", "if", "e", "else", "None", ")", "await", "ctx", ".", "send", "(", "'Now playing: {}'", ".", "format", "(", "query", ")", ")" ]
Plays a file from the local filesystem
[ "Plays", "a", "file", "from", "the", "local", "filesystem" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_voice.py#L69-L75
26,544
Rapptz/discord.py
examples/basic_voice.py
Music.volume
async def volume(self, ctx, volume: int): """Changes the player's volume""" if ctx.voice_client is None: return await ctx.send("Not connected to a voice channel.") ctx.voice_client.source.volume = volume / 100 await ctx.send("Changed volume to {}%".format(volume))
python
async def volume(self, ctx, volume: int): """Changes the player's volume""" if ctx.voice_client is None: return await ctx.send("Not connected to a voice channel.") ctx.voice_client.source.volume = volume / 100 await ctx.send("Changed volume to {}%".format(volume))
[ "async", "def", "volume", "(", "self", ",", "ctx", ",", "volume", ":", "int", ")", ":", "if", "ctx", ".", "voice_client", "is", "None", ":", "return", "await", "ctx", ".", "send", "(", "\"Not connected to a voice channel.\"", ")", "ctx", ".", "voice_client", ".", "source", ".", "volume", "=", "volume", "/", "100", "await", "ctx", ".", "send", "(", "\"Changed volume to {}%\"", ".", "format", "(", "volume", ")", ")" ]
Changes the player's volume
[ "Changes", "the", "player", "s", "volume" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_voice.py#L98-L105
26,545
Rapptz/discord.py
discord/calls.py
CallMessage.duration
def duration(self): """Queries the duration of the call. If the call has not ended then the current duration will be returned. Returns --------- datetime.timedelta The timedelta object representing the duration. """ if self.ended_timestamp is None: return datetime.datetime.utcnow() - self.message.created_at else: return self.ended_timestamp - self.message.created_at
python
def duration(self): """Queries the duration of the call. If the call has not ended then the current duration will be returned. Returns --------- datetime.timedelta The timedelta object representing the duration. """ if self.ended_timestamp is None: return datetime.datetime.utcnow() - self.message.created_at else: return self.ended_timestamp - self.message.created_at
[ "def", "duration", "(", "self", ")", ":", "if", "self", ".", "ended_timestamp", "is", "None", ":", "return", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "self", ".", "message", ".", "created_at", "else", ":", "return", "self", ".", "ended_timestamp", "-", "self", ".", "message", ".", "created_at" ]
Queries the duration of the call. If the call has not ended then the current duration will be returned. Returns --------- datetime.timedelta The timedelta object representing the duration.
[ "Queries", "the", "duration", "of", "the", "call", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/calls.py#L65-L79
26,546
Rapptz/discord.py
discord/webhook.py
Webhook.avatar_url_as
def avatar_url_as(self, *, format=None, size=1024): """Returns a friendly URL version of the avatar the webhook has. If the webhook does not have a traditional avatar, their default avatar URL is returned instead. The format must be one of 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 1024. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is equivalent to png. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ if self.avatar is None: # Default is always blurple apparently return Asset(self._state, 'https://cdn.discordapp.com/embed/avatars/0.png') if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 1024") format = format or 'png' if format not in ('png', 'jpg', 'jpeg'): raise InvalidArgument("format must be one of 'png', 'jpg', or 'jpeg'.") url = 'https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.{1}?size={2}'.format(self, format, size) return Asset(self._state, url)
python
def avatar_url_as(self, *, format=None, size=1024): """Returns a friendly URL version of the avatar the webhook has. If the webhook does not have a traditional avatar, their default avatar URL is returned instead. The format must be one of 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 1024. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is equivalent to png. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ if self.avatar is None: # Default is always blurple apparently return Asset(self._state, 'https://cdn.discordapp.com/embed/avatars/0.png') if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 1024") format = format or 'png' if format not in ('png', 'jpg', 'jpeg'): raise InvalidArgument("format must be one of 'png', 'jpg', or 'jpeg'.") url = 'https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.{1}?size={2}'.format(self, format, size) return Asset(self._state, url)
[ "def", "avatar_url_as", "(", "self", ",", "*", ",", "format", "=", "None", ",", "size", "=", "1024", ")", ":", "if", "self", ".", "avatar", "is", "None", ":", "# Default is always blurple apparently", "return", "Asset", "(", "self", ".", "_state", ",", "'https://cdn.discordapp.com/embed/avatars/0.png'", ")", "if", "not", "utils", ".", "valid_icon_size", "(", "size", ")", ":", "raise", "InvalidArgument", "(", "\"size must be a power of 2 between 16 and 1024\"", ")", "format", "=", "format", "or", "'png'", "if", "format", "not", "in", "(", "'png'", ",", "'jpg'", ",", "'jpeg'", ")", ":", "raise", "InvalidArgument", "(", "\"format must be one of 'png', 'jpg', or 'jpeg'.\"", ")", "url", "=", "'https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.{1}?size={2}'", ".", "format", "(", "self", ",", "format", ",", "size", ")", "return", "Asset", "(", "self", ".", "_state", ",", "url", ")" ]
Returns a friendly URL version of the avatar the webhook has. If the webhook does not have a traditional avatar, their default avatar URL is returned instead. The format must be one of 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 1024. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is equivalent to png. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset.
[ "Returns", "a", "friendly", "URL", "version", "of", "the", "avatar", "the", "webhook", "has", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/webhook.py#L536-L576
26,547
Rapptz/discord.py
discord/abc.py
GuildChannel.overwrites_for
def overwrites_for(self, obj): """Returns the channel-specific overwrites for a member or a role. Parameters ----------- obj The :class:`Role` or :class:`abc.User` denoting whose overwrite to get. Returns --------- :class:`PermissionOverwrite` The permission overwrites for this object. """ if isinstance(obj, User): predicate = lambda p: p.type == 'member' elif isinstance(obj, Role): predicate = lambda p: p.type == 'role' else: predicate = lambda p: True for overwrite in filter(predicate, self._overwrites): if overwrite.id == obj.id: allow = Permissions(overwrite.allow) deny = Permissions(overwrite.deny) return PermissionOverwrite.from_pair(allow, deny) return PermissionOverwrite()
python
def overwrites_for(self, obj): """Returns the channel-specific overwrites for a member or a role. Parameters ----------- obj The :class:`Role` or :class:`abc.User` denoting whose overwrite to get. Returns --------- :class:`PermissionOverwrite` The permission overwrites for this object. """ if isinstance(obj, User): predicate = lambda p: p.type == 'member' elif isinstance(obj, Role): predicate = lambda p: p.type == 'role' else: predicate = lambda p: True for overwrite in filter(predicate, self._overwrites): if overwrite.id == obj.id: allow = Permissions(overwrite.allow) deny = Permissions(overwrite.deny) return PermissionOverwrite.from_pair(allow, deny) return PermissionOverwrite()
[ "def", "overwrites_for", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "User", ")", ":", "predicate", "=", "lambda", "p", ":", "p", ".", "type", "==", "'member'", "elif", "isinstance", "(", "obj", ",", "Role", ")", ":", "predicate", "=", "lambda", "p", ":", "p", ".", "type", "==", "'role'", "else", ":", "predicate", "=", "lambda", "p", ":", "True", "for", "overwrite", "in", "filter", "(", "predicate", ",", "self", ".", "_overwrites", ")", ":", "if", "overwrite", ".", "id", "==", "obj", ".", "id", ":", "allow", "=", "Permissions", "(", "overwrite", ".", "allow", ")", "deny", "=", "Permissions", "(", "overwrite", ".", "deny", ")", "return", "PermissionOverwrite", ".", "from_pair", "(", "allow", ",", "deny", ")", "return", "PermissionOverwrite", "(", ")" ]
Returns the channel-specific overwrites for a member or a role. Parameters ----------- obj The :class:`Role` or :class:`abc.User` denoting whose overwrite to get. Returns --------- :class:`PermissionOverwrite` The permission overwrites for this object.
[ "Returns", "the", "channel", "-", "specific", "overwrites", "for", "a", "member", "or", "a", "role", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L315-L343
26,548
Rapptz/discord.py
discord/abc.py
GuildChannel.overwrites
def overwrites(self): """Returns all of the channel's overwrites. This is returned as a dictionary where the key contains the target which can be either a :class:`Role` or a :class:`Member` and the key is the overwrite as a :class:`PermissionOverwrite`. Returns -------- Mapping[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]: The channel's permission overwrites. """ ret = {} for ow in self._overwrites: allow = Permissions(ow.allow) deny = Permissions(ow.deny) overwrite = PermissionOverwrite.from_pair(allow, deny) if ow.type == 'role': target = self.guild.get_role(ow.id) elif ow.type == 'member': target = self.guild.get_member(ow.id) # TODO: There is potential data loss here in the non-chunked # case, i.e. target is None because get_member returned nothing. # This can be fixed with a slight breaking change to the return type, # i.e. adding discord.Object to the list of it # However, for now this is an acceptable compromise. if target is not None: ret[target] = overwrite return ret
python
def overwrites(self): """Returns all of the channel's overwrites. This is returned as a dictionary where the key contains the target which can be either a :class:`Role` or a :class:`Member` and the key is the overwrite as a :class:`PermissionOverwrite`. Returns -------- Mapping[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]: The channel's permission overwrites. """ ret = {} for ow in self._overwrites: allow = Permissions(ow.allow) deny = Permissions(ow.deny) overwrite = PermissionOverwrite.from_pair(allow, deny) if ow.type == 'role': target = self.guild.get_role(ow.id) elif ow.type == 'member': target = self.guild.get_member(ow.id) # TODO: There is potential data loss here in the non-chunked # case, i.e. target is None because get_member returned nothing. # This can be fixed with a slight breaking change to the return type, # i.e. adding discord.Object to the list of it # However, for now this is an acceptable compromise. if target is not None: ret[target] = overwrite return ret
[ "def", "overwrites", "(", "self", ")", ":", "ret", "=", "{", "}", "for", "ow", "in", "self", ".", "_overwrites", ":", "allow", "=", "Permissions", "(", "ow", ".", "allow", ")", "deny", "=", "Permissions", "(", "ow", ".", "deny", ")", "overwrite", "=", "PermissionOverwrite", ".", "from_pair", "(", "allow", ",", "deny", ")", "if", "ow", ".", "type", "==", "'role'", ":", "target", "=", "self", ".", "guild", ".", "get_role", "(", "ow", ".", "id", ")", "elif", "ow", ".", "type", "==", "'member'", ":", "target", "=", "self", ".", "guild", ".", "get_member", "(", "ow", ".", "id", ")", "# TODO: There is potential data loss here in the non-chunked", "# case, i.e. target is None because get_member returned nothing.", "# This can be fixed with a slight breaking change to the return type,", "# i.e. adding discord.Object to the list of it", "# However, for now this is an acceptable compromise.", "if", "target", "is", "not", "None", ":", "ret", "[", "target", "]", "=", "overwrite", "return", "ret" ]
Returns all of the channel's overwrites. This is returned as a dictionary where the key contains the target which can be either a :class:`Role` or a :class:`Member` and the key is the overwrite as a :class:`PermissionOverwrite`. Returns -------- Mapping[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]: The channel's permission overwrites.
[ "Returns", "all", "of", "the", "channel", "s", "overwrites", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L346-L376
26,549
Rapptz/discord.py
discord/ext/tasks/__init__.py
loop
def loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None): """A decorator that schedules a task in the background for you with optional reconnect logic. Parameters ------------ seconds: :class:`float` The number of seconds between every iteration. minutes: :class:`float` The number of minutes between every iteration. hours: :class:`float` The number of hours between every iteration. count: Optional[:class:`int`] The number of loops to do, ``None`` if it should be an infinite loop. reconnect: :class:`bool` Whether to handle errors and restart the task using an exponential back-off algorithm similar to the one used in :meth:`discord.Client.connect`. loop: :class:`asyncio.AbstractEventLoop` The loop to use to register the task, if not given defaults to :func:`asyncio.get_event_loop`. Raises -------- ValueError An invalid value was given. TypeError The function was not a coroutine. Returns --------- :class:`Loop` The loop helper that handles the background task. """ def decorator(func): return Loop(func, seconds=seconds, minutes=minutes, hours=hours, count=count, reconnect=reconnect, loop=loop) return decorator
python
def loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None): """A decorator that schedules a task in the background for you with optional reconnect logic. Parameters ------------ seconds: :class:`float` The number of seconds between every iteration. minutes: :class:`float` The number of minutes between every iteration. hours: :class:`float` The number of hours between every iteration. count: Optional[:class:`int`] The number of loops to do, ``None`` if it should be an infinite loop. reconnect: :class:`bool` Whether to handle errors and restart the task using an exponential back-off algorithm similar to the one used in :meth:`discord.Client.connect`. loop: :class:`asyncio.AbstractEventLoop` The loop to use to register the task, if not given defaults to :func:`asyncio.get_event_loop`. Raises -------- ValueError An invalid value was given. TypeError The function was not a coroutine. Returns --------- :class:`Loop` The loop helper that handles the background task. """ def decorator(func): return Loop(func, seconds=seconds, minutes=minutes, hours=hours, count=count, reconnect=reconnect, loop=loop) return decorator
[ "def", "loop", "(", "*", ",", "seconds", "=", "0", ",", "minutes", "=", "0", ",", "hours", "=", "0", ",", "count", "=", "None", ",", "reconnect", "=", "True", ",", "loop", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "return", "Loop", "(", "func", ",", "seconds", "=", "seconds", ",", "minutes", "=", "minutes", ",", "hours", "=", "hours", ",", "count", "=", "count", ",", "reconnect", "=", "reconnect", ",", "loop", "=", "loop", ")", "return", "decorator" ]
A decorator that schedules a task in the background for you with optional reconnect logic. Parameters ------------ seconds: :class:`float` The number of seconds between every iteration. minutes: :class:`float` The number of minutes between every iteration. hours: :class:`float` The number of hours between every iteration. count: Optional[:class:`int`] The number of loops to do, ``None`` if it should be an infinite loop. reconnect: :class:`bool` Whether to handle errors and restart the task using an exponential back-off algorithm similar to the one used in :meth:`discord.Client.connect`. loop: :class:`asyncio.AbstractEventLoop` The loop to use to register the task, if not given defaults to :func:`asyncio.get_event_loop`. Raises -------- ValueError An invalid value was given. TypeError The function was not a coroutine. Returns --------- :class:`Loop` The loop helper that handles the background task.
[ "A", "decorator", "that", "schedules", "a", "task", "in", "the", "background", "for", "you", "with", "optional", "reconnect", "logic", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L238-L276
26,550
Rapptz/discord.py
discord/ext/tasks/__init__.py
Loop.remove_exception_type
def remove_exception_type(self, exc): """Removes an exception type from being handled during the reconnect logic. Parameters ------------ exc: Type[:class:`BaseException`] The exception class to handle. Returns --------- :class:`bool` Whether it was successfully removed. """ old_length = len(self._valid_exception) self._valid_exception = tuple(x for x in self._valid_exception if x is not exc) return len(self._valid_exception) != old_length
python
def remove_exception_type(self, exc): """Removes an exception type from being handled during the reconnect logic. Parameters ------------ exc: Type[:class:`BaseException`] The exception class to handle. Returns --------- :class:`bool` Whether it was successfully removed. """ old_length = len(self._valid_exception) self._valid_exception = tuple(x for x in self._valid_exception if x is not exc) return len(self._valid_exception) != old_length
[ "def", "remove_exception_type", "(", "self", ",", "exc", ")", ":", "old_length", "=", "len", "(", "self", ".", "_valid_exception", ")", "self", ".", "_valid_exception", "=", "tuple", "(", "x", "for", "x", "in", "self", ".", "_valid_exception", "if", "x", "is", "not", "exc", ")", "return", "len", "(", "self", ".", "_valid_exception", ")", "!=", "old_length" ]
Removes an exception type from being handled during the reconnect logic. Parameters ------------ exc: Type[:class:`BaseException`] The exception class to handle. Returns --------- :class:`bool` Whether it was successfully removed.
[ "Removes", "an", "exception", "type", "from", "being", "handled", "during", "the", "reconnect", "logic", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L174-L189
26,551
Rapptz/discord.py
discord/ext/tasks/__init__.py
Loop.after_loop
def after_loop(self, coro): """A function that also acts as a decorator to register a coroutine to be called after the loop finished running. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register after the loop finishes. Raises ------- TypeError The function was not a coroutine. """ if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)): raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro))) self._after_loop = coro
python
def after_loop(self, coro): """A function that also acts as a decorator to register a coroutine to be called after the loop finished running. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register after the loop finishes. Raises ------- TypeError The function was not a coroutine. """ if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)): raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro))) self._after_loop = coro
[ "def", "after_loop", "(", "self", ",", "coro", ")", ":", "if", "not", "(", "inspect", ".", "iscoroutinefunction", "(", "coro", ")", "or", "inspect", ".", "isawaitable", "(", "coro", ")", ")", ":", "raise", "TypeError", "(", "'Expected coroutine or awaitable, received {0.__name__!r}.'", ".", "format", "(", "type", "(", "coro", ")", ")", ")", "self", ".", "_after_loop", "=", "coro" ]
A function that also acts as a decorator to register a coroutine to be called after the loop finished running. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register after the loop finishes. Raises ------- TypeError The function was not a coroutine.
[ "A", "function", "that", "also", "acts", "as", "a", "decorator", "to", "register", "a", "coroutine", "to", "be", "called", "after", "the", "loop", "finished", "running", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L218-L236
26,552
Rapptz/discord.py
discord/backoff.py
ExponentialBackoff.delay
def delay(self): """Compute the next delay Returns the next delay to wait according to the exponential backoff algorithm. This is a value between 0 and base * 2^exp where exponent starts off at 1 and is incremented at every invocation of this method up to a maximum of 10. If a period of more than base * 2^11 has passed since the last retry, the exponent is reset to 1. """ invocation = time.monotonic() interval = invocation - self._last_invocation self._last_invocation = invocation if interval > self._reset_time: self._exp = 0 self._exp = min(self._exp + 1, self._max) return self._randfunc(0, self._base * 2 ** self._exp)
python
def delay(self): """Compute the next delay Returns the next delay to wait according to the exponential backoff algorithm. This is a value between 0 and base * 2^exp where exponent starts off at 1 and is incremented at every invocation of this method up to a maximum of 10. If a period of more than base * 2^11 has passed since the last retry, the exponent is reset to 1. """ invocation = time.monotonic() interval = invocation - self._last_invocation self._last_invocation = invocation if interval > self._reset_time: self._exp = 0 self._exp = min(self._exp + 1, self._max) return self._randfunc(0, self._base * 2 ** self._exp)
[ "def", "delay", "(", "self", ")", ":", "invocation", "=", "time", ".", "monotonic", "(", ")", "interval", "=", "invocation", "-", "self", ".", "_last_invocation", "self", ".", "_last_invocation", "=", "invocation", "if", "interval", ">", "self", ".", "_reset_time", ":", "self", ".", "_exp", "=", "0", "self", ".", "_exp", "=", "min", "(", "self", ".", "_exp", "+", "1", ",", "self", ".", "_max", ")", "return", "self", ".", "_randfunc", "(", "0", ",", "self", ".", "_base", "*", "2", "**", "self", ".", "_exp", ")" ]
Compute the next delay Returns the next delay to wait according to the exponential backoff algorithm. This is a value between 0 and base * 2^exp where exponent starts off at 1 and is incremented at every invocation of this method up to a maximum of 10. If a period of more than base * 2^11 has passed since the last retry, the exponent is reset to 1.
[ "Compute", "the", "next", "delay" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/backoff.py#L66-L85
26,553
Rapptz/discord.py
discord/permissions.py
Permissions.is_subset
def is_subset(self, other): """Returns True if self has the same or fewer permissions as other.""" if isinstance(other, Permissions): return (self.value & other.value) == self.value else: raise TypeError("cannot compare {} with {}".format(self.__class__.__name__, other.__class__.__name__))
python
def is_subset(self, other): """Returns True if self has the same or fewer permissions as other.""" if isinstance(other, Permissions): return (self.value & other.value) == self.value else: raise TypeError("cannot compare {} with {}".format(self.__class__.__name__, other.__class__.__name__))
[ "def", "is_subset", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Permissions", ")", ":", "return", "(", "self", ".", "value", "&", "other", ".", "value", ")", "==", "self", ".", "value", "else", ":", "raise", "TypeError", "(", "\"cannot compare {} with {}\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "other", ".", "__class__", ".", "__name__", ")", ")" ]
Returns True if self has the same or fewer permissions as other.
[ "Returns", "True", "if", "self", "has", "the", "same", "or", "fewer", "permissions", "as", "other", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/permissions.py#L99-L104
26,554
Rapptz/discord.py
discord/permissions.py
Permissions.update
def update(self, **kwargs): r"""Bulk updates this permission object. Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored. Parameters ------------ \*\*kwargs A list of key/value pairs to bulk update permissions with. """ for key, value in kwargs.items(): try: is_property = isinstance(getattr(self.__class__, key), property) except AttributeError: continue if is_property: setattr(self, key, value)
python
def update(self, **kwargs): r"""Bulk updates this permission object. Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored. Parameters ------------ \*\*kwargs A list of key/value pairs to bulk update permissions with. """ for key, value in kwargs.items(): try: is_property = isinstance(getattr(self.__class__, key), property) except AttributeError: continue if is_property: setattr(self, key, value)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "try", ":", "is_property", "=", "isinstance", "(", "getattr", "(", "self", ".", "__class__", ",", "key", ")", ",", "property", ")", "except", "AttributeError", ":", "continue", "if", "is_property", ":", "setattr", "(", "self", ",", "key", ",", "value", ")" ]
r"""Bulk updates this permission object. Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored. Parameters ------------ \*\*kwargs A list of key/value pairs to bulk update permissions with.
[ "r", "Bulk", "updates", "this", "permission", "object", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/permissions.py#L171-L190
26,555
Rapptz/discord.py
discord/ext/commands/core.py
Command.clean_params
def clean_params(self): """Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature. """ result = self.params.copy() if self.cog is not None: # first parameter is self result.popitem(last=False) try: # first/second parameter is context result.popitem(last=False) except Exception: raise ValueError('Missing context parameter') from None return result
python
def clean_params(self): """Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature. """ result = self.params.copy() if self.cog is not None: # first parameter is self result.popitem(last=False) try: # first/second parameter is context result.popitem(last=False) except Exception: raise ValueError('Missing context parameter') from None return result
[ "def", "clean_params", "(", "self", ")", ":", "result", "=", "self", ".", "params", ".", "copy", "(", ")", "if", "self", ".", "cog", "is", "not", "None", ":", "# first parameter is self", "result", ".", "popitem", "(", "last", "=", "False", ")", "try", ":", "# first/second parameter is context", "result", ".", "popitem", "(", "last", "=", "False", ")", "except", "Exception", ":", "raise", "ValueError", "(", "'Missing context parameter'", ")", "from", "None", "return", "result" ]
Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature.
[ "Retrieves", "the", "parameter", "OrderedDict", "without", "the", "context", "or", "self", "parameters", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L488-L504
26,556
Rapptz/discord.py
discord/ext/commands/core.py
Command.full_parent_name
def full_parent_name(self): """Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self while command.parent is not None: command = command.parent entries.append(command.name) return ' '.join(reversed(entries))
python
def full_parent_name(self): """Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self while command.parent is not None: command = command.parent entries.append(command.name) return ' '.join(reversed(entries))
[ "def", "full_parent_name", "(", "self", ")", ":", "entries", "=", "[", "]", "command", "=", "self", "while", "command", ".", "parent", "is", "not", "None", ":", "command", "=", "command", ".", "parent", "entries", ".", "append", "(", "command", ".", "name", ")", "return", "' '", ".", "join", "(", "reversed", "(", "entries", ")", ")" ]
Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``.
[ "Retrieves", "the", "fully", "qualified", "parent", "command", "name", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L507-L519
26,557
Rapptz/discord.py
discord/ext/commands/core.py
Command.parents
def parents(self): """Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1.0 """ entries = [] command = self while command.parent is not None: command = command.parent entries.append(command) return entries
python
def parents(self): """Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1.0 """ entries = [] command = self while command.parent is not None: command = command.parent entries.append(command) return entries
[ "def", "parents", "(", "self", ")", ":", "entries", "=", "[", "]", "command", "=", "self", "while", "command", ".", "parent", "is", "not", "None", ":", "command", "=", "command", ".", "parent", "entries", ".", "append", "(", "command", ")", "return", "entries" ]
Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1.0
[ "Retrieves", "the", "parents", "of", "this", "command", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L522-L537
26,558
Rapptz/discord.py
discord/ext/commands/core.py
Command.qualified_name
def qualified_name(self): """Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two three`` the qualified name would be ``one two three``. """ parent = self.full_parent_name if parent: return parent + ' ' + self.name else: return self.name
python
def qualified_name(self): """Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two three`` the qualified name would be ``one two three``. """ parent = self.full_parent_name if parent: return parent + ' ' + self.name else: return self.name
[ "def", "qualified_name", "(", "self", ")", ":", "parent", "=", "self", ".", "full_parent_name", "if", "parent", ":", "return", "parent", "+", "' '", "+", "self", ".", "name", "else", ":", "return", "self", ".", "name" ]
Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two three`` the qualified name would be ``one two three``.
[ "Retrieves", "the", "fully", "qualified", "command", "name", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L552-L564
26,559
Rapptz/discord.py
discord/ext/commands/core.py
Command.is_on_cooldown
def is_on_cooldown(self, ctx): """Checks whether the command is currently on cooldown. Parameters ----------- ctx: :class:`.Context.` The invocation context to use when checking the commands cooldown status. Returns -------- :class:`bool` A boolean indicating if the command is on cooldown. """ if not self._buckets.valid: return False bucket = self._buckets.get_bucket(ctx.message) return bucket.get_tokens() == 0
python
def is_on_cooldown(self, ctx): """Checks whether the command is currently on cooldown. Parameters ----------- ctx: :class:`.Context.` The invocation context to use when checking the commands cooldown status. Returns -------- :class:`bool` A boolean indicating if the command is on cooldown. """ if not self._buckets.valid: return False bucket = self._buckets.get_bucket(ctx.message) return bucket.get_tokens() == 0
[ "def", "is_on_cooldown", "(", "self", ",", "ctx", ")", ":", "if", "not", "self", ".", "_buckets", ".", "valid", ":", "return", "False", "bucket", "=", "self", ".", "_buckets", ".", "get_bucket", "(", "ctx", ".", "message", ")", "return", "bucket", ".", "get_tokens", "(", ")", "==", "0" ]
Checks whether the command is currently on cooldown. Parameters ----------- ctx: :class:`.Context.` The invocation context to use when checking the commands cooldown status. Returns -------- :class:`bool` A boolean indicating if the command is on cooldown.
[ "Checks", "whether", "the", "command", "is", "currently", "on", "cooldown", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L686-L703
26,560
Rapptz/discord.py
discord/ext/commands/core.py
Command.reset_cooldown
def reset_cooldown(self, ctx): """Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) bucket.reset()
python
def reset_cooldown(self, ctx): """Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) bucket.reset()
[ "def", "reset_cooldown", "(", "self", ",", "ctx", ")", ":", "if", "self", ".", "_buckets", ".", "valid", ":", "bucket", "=", "self", ".", "_buckets", ".", "get_bucket", "(", "ctx", ".", "message", ")", "bucket", ".", "reset", "(", ")" ]
Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under.
[ "Resets", "the", "cooldown", "on", "this", "command", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L705-L715
26,561
Rapptz/discord.py
discord/ext/commands/core.py
Command.error
def error(self, coro): """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error = coro return coro
python
def error(self, coro): """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error = coro return coro
[ "def", "error", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'The error handler must be a coroutine.'", ")", "self", ".", "on_error", "=", "coro", "return", "coro" ]
A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine.
[ "A", "decorator", "that", "registers", "a", "coroutine", "as", "a", "local", "error", "handler", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L744-L766
26,562
Rapptz/discord.py
discord/ext/commands/core.py
Command.before_invoke
def before_invoke(self, coro): """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.before_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro
python
def before_invoke(self, coro): """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.before_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro
[ "def", "before_invoke", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'The pre-invoke hook must be a coroutine.'", ")", "self", ".", "_before_invoke", "=", "coro", "return", "coro" ]
A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.before_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine.
[ "A", "decorator", "that", "registers", "a", "coroutine", "as", "a", "pre", "-", "invoke", "hook", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L768-L793
26,563
Rapptz/discord.py
discord/ext/commands/core.py
Command.after_invoke
def after_invoke(self, coro): """A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.after_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the post-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro
python
def after_invoke(self, coro): """A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.after_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the post-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro
[ "def", "after_invoke", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'The post-invoke hook must be a coroutine.'", ")", "self", ".", "_after_invoke", "=", "coro", "return", "coro" ]
A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.after_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the post-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine.
[ "A", "decorator", "that", "registers", "a", "coroutine", "as", "a", "post", "-", "invoke", "hook", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L795-L820
26,564
Rapptz/discord.py
discord/ext/commands/core.py
Command.short_doc
def short_doc(self): """Gets the "short" documentation of a command. By default, this is the :attr:`brief` attribute. If that lookup leads to an empty string then the first line of the :attr:`help` attribute is used instead. """ if self.brief is not None: return self.brief if self.help is not None: return self.help.split('\n', 1)[0] return ''
python
def short_doc(self): """Gets the "short" documentation of a command. By default, this is the :attr:`brief` attribute. If that lookup leads to an empty string then the first line of the :attr:`help` attribute is used instead. """ if self.brief is not None: return self.brief if self.help is not None: return self.help.split('\n', 1)[0] return ''
[ "def", "short_doc", "(", "self", ")", ":", "if", "self", ".", "brief", "is", "not", "None", ":", "return", "self", ".", "brief", "if", "self", ".", "help", "is", "not", "None", ":", "return", "self", ".", "help", ".", "split", "(", "'\\n'", ",", "1", ")", "[", "0", "]", "return", "''" ]
Gets the "short" documentation of a command. By default, this is the :attr:`brief` attribute. If that lookup leads to an empty string then the first line of the :attr:`help` attribute is used instead.
[ "Gets", "the", "short", "documentation", "of", "a", "command", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L828-L839
26,565
Rapptz/discord.py
discord/ext/commands/core.py
Command.signature
def signature(self): """Returns a POSIX-like signature useful for help command output.""" if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): greedy = isinstance(param.annotation, converters._Greedy) if param.default is not param.empty: # We don't want None or '' to trigger the [name=value] case and instead it should # do [name] since [name=None] or [name=] are not exactly useful for the user. should_print = param.default if isinstance(param.default, str) else param.default is not None if should_print: result.append('[%s=%s]' % (name, param.default) if not greedy else '[%s=%s]...' % (name, param.default)) continue else: result.append('[%s]' % name) elif param.kind == param.VAR_POSITIONAL: result.append('[%s...]' % name) elif greedy: result.append('[%s]...' % name) elif self._is_typing_optional(param.annotation): result.append('[%s]' % name) else: result.append('<%s>' % name) return ' '.join(result)
python
def signature(self): """Returns a POSIX-like signature useful for help command output.""" if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): greedy = isinstance(param.annotation, converters._Greedy) if param.default is not param.empty: # We don't want None or '' to trigger the [name=value] case and instead it should # do [name] since [name=None] or [name=] are not exactly useful for the user. should_print = param.default if isinstance(param.default, str) else param.default is not None if should_print: result.append('[%s=%s]' % (name, param.default) if not greedy else '[%s=%s]...' % (name, param.default)) continue else: result.append('[%s]' % name) elif param.kind == param.VAR_POSITIONAL: result.append('[%s...]' % name) elif greedy: result.append('[%s]...' % name) elif self._is_typing_optional(param.annotation): result.append('[%s]' % name) else: result.append('<%s>' % name) return ' '.join(result)
[ "def", "signature", "(", "self", ")", ":", "if", "self", ".", "usage", "is", "not", "None", ":", "return", "self", ".", "usage", "params", "=", "self", ".", "clean_params", "if", "not", "params", ":", "return", "''", "result", "=", "[", "]", "for", "name", ",", "param", "in", "params", ".", "items", "(", ")", ":", "greedy", "=", "isinstance", "(", "param", ".", "annotation", ",", "converters", ".", "_Greedy", ")", "if", "param", ".", "default", "is", "not", "param", ".", "empty", ":", "# We don't want None or '' to trigger the [name=value] case and instead it should", "# do [name] since [name=None] or [name=] are not exactly useful for the user.", "should_print", "=", "param", ".", "default", "if", "isinstance", "(", "param", ".", "default", ",", "str", ")", "else", "param", ".", "default", "is", "not", "None", "if", "should_print", ":", "result", ".", "append", "(", "'[%s=%s]'", "%", "(", "name", ",", "param", ".", "default", ")", "if", "not", "greedy", "else", "'[%s=%s]...'", "%", "(", "name", ",", "param", ".", "default", ")", ")", "continue", "else", ":", "result", ".", "append", "(", "'[%s]'", "%", "name", ")", "elif", "param", ".", "kind", "==", "param", ".", "VAR_POSITIONAL", ":", "result", ".", "append", "(", "'[%s...]'", "%", "name", ")", "elif", "greedy", ":", "result", ".", "append", "(", "'[%s]...'", "%", "name", ")", "elif", "self", ".", "_is_typing_optional", "(", "param", ".", "annotation", ")", ":", "result", ".", "append", "(", "'[%s]'", "%", "name", ")", "else", ":", "result", ".", "append", "(", "'<%s>'", "%", "name", ")", "return", "' '", ".", "join", "(", "result", ")" ]
Returns a POSIX-like signature useful for help command output.
[ "Returns", "a", "POSIX", "-", "like", "signature", "useful", "for", "help", "command", "output", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L853-L887
26,566
Rapptz/discord.py
discord/ext/commands/core.py
GroupMixin.walk_commands
def walk_commands(self): """An iterator that recursively walks through all commands and subcommands.""" for command in tuple(self.all_commands.values()): yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
python
def walk_commands(self): """An iterator that recursively walks through all commands and subcommands.""" for command in tuple(self.all_commands.values()): yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
[ "def", "walk_commands", "(", "self", ")", ":", "for", "command", "in", "tuple", "(", "self", ".", "all_commands", ".", "values", "(", ")", ")", ":", "yield", "command", "if", "isinstance", "(", "command", ",", "GroupMixin", ")", ":", "yield", "from", "command", ".", "walk_commands", "(", ")" ]
An iterator that recursively walks through all commands and subcommands.
[ "An", "iterator", "that", "recursively", "walks", "through", "all", "commands", "and", "subcommands", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1032-L1037
26,567
Rapptz/discord.py
discord/gateway.py
DiscordWebSocket.wait_for
def wait_for(self, event, predicate, result=None): """Waits for a DISPATCH'd event that meets the predicate. Parameters ----------- event: :class:`str` The event name in all upper case to wait for. predicate A function that takes a data parameter to check for event properties. The data parameter is the 'd' key in the JSON message. result A function that takes the same data parameter and executes to send the result to the future. If None, returns the data. Returns -------- asyncio.Future A future to wait for. """ future = self.loop.create_future() entry = EventListener(event=event, predicate=predicate, result=result, future=future) self._dispatch_listeners.append(entry) return future
python
def wait_for(self, event, predicate, result=None): """Waits for a DISPATCH'd event that meets the predicate. Parameters ----------- event: :class:`str` The event name in all upper case to wait for. predicate A function that takes a data parameter to check for event properties. The data parameter is the 'd' key in the JSON message. result A function that takes the same data parameter and executes to send the result to the future. If None, returns the data. Returns -------- asyncio.Future A future to wait for. """ future = self.loop.create_future() entry = EventListener(event=event, predicate=predicate, result=result, future=future) self._dispatch_listeners.append(entry) return future
[ "def", "wait_for", "(", "self", ",", "event", ",", "predicate", ",", "result", "=", "None", ")", ":", "future", "=", "self", ".", "loop", ".", "create_future", "(", ")", "entry", "=", "EventListener", "(", "event", "=", "event", ",", "predicate", "=", "predicate", ",", "result", "=", "result", ",", "future", "=", "future", ")", "self", ".", "_dispatch_listeners", ".", "append", "(", "entry", ")", "return", "future" ]
Waits for a DISPATCH'd event that meets the predicate. Parameters ----------- event: :class:`str` The event name in all upper case to wait for. predicate A function that takes a data parameter to check for event properties. The data parameter is the 'd' key in the JSON message. result A function that takes the same data parameter and executes to send the result to the future. If None, returns the data. Returns -------- asyncio.Future A future to wait for.
[ "Waits", "for", "a", "DISPATCH", "d", "event", "that", "meets", "the", "predicate", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L259-L282
26,568
Rapptz/discord.py
discord/gateway.py
DiscordWebSocket.identify
async def identify(self): """Sends the IDENTIFY packet.""" payload = { 'op': self.IDENTIFY, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', '$device': 'discord.py', '$referrer': '', '$referring_domain': '' }, 'compress': True, 'large_threshold': 250, 'v': 3 } } if not self._connection.is_bot: payload['d']['synced_guilds'] = [] if self.shard_id is not None and self.shard_count is not None: payload['d']['shard'] = [self.shard_id, self.shard_count] state = self._connection if state._activity is not None or state._status is not None: payload['d']['presence'] = { 'status': state._status, 'game': state._activity, 'since': 0, 'afk': False } await self.send_as_json(payload) log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
python
async def identify(self): """Sends the IDENTIFY packet.""" payload = { 'op': self.IDENTIFY, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', '$device': 'discord.py', '$referrer': '', '$referring_domain': '' }, 'compress': True, 'large_threshold': 250, 'v': 3 } } if not self._connection.is_bot: payload['d']['synced_guilds'] = [] if self.shard_id is not None and self.shard_count is not None: payload['d']['shard'] = [self.shard_id, self.shard_count] state = self._connection if state._activity is not None or state._status is not None: payload['d']['presence'] = { 'status': state._status, 'game': state._activity, 'since': 0, 'afk': False } await self.send_as_json(payload) log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
[ "async", "def", "identify", "(", "self", ")", ":", "payload", "=", "{", "'op'", ":", "self", ".", "IDENTIFY", ",", "'d'", ":", "{", "'token'", ":", "self", ".", "token", ",", "'properties'", ":", "{", "'$os'", ":", "sys", ".", "platform", ",", "'$browser'", ":", "'discord.py'", ",", "'$device'", ":", "'discord.py'", ",", "'$referrer'", ":", "''", ",", "'$referring_domain'", ":", "''", "}", ",", "'compress'", ":", "True", ",", "'large_threshold'", ":", "250", ",", "'v'", ":", "3", "}", "}", "if", "not", "self", ".", "_connection", ".", "is_bot", ":", "payload", "[", "'d'", "]", "[", "'synced_guilds'", "]", "=", "[", "]", "if", "self", ".", "shard_id", "is", "not", "None", "and", "self", ".", "shard_count", "is", "not", "None", ":", "payload", "[", "'d'", "]", "[", "'shard'", "]", "=", "[", "self", ".", "shard_id", ",", "self", ".", "shard_count", "]", "state", "=", "self", ".", "_connection", "if", "state", ".", "_activity", "is", "not", "None", "or", "state", ".", "_status", "is", "not", "None", ":", "payload", "[", "'d'", "]", "[", "'presence'", "]", "=", "{", "'status'", ":", "state", ".", "_status", ",", "'game'", ":", "state", ".", "_activity", ",", "'since'", ":", "0", ",", "'afk'", ":", "False", "}", "await", "self", ".", "send_as_json", "(", "payload", ")", "log", ".", "info", "(", "'Shard ID %s has sent the IDENTIFY payload.'", ",", "self", ".", "shard_id", ")" ]
Sends the IDENTIFY packet.
[ "Sends", "the", "IDENTIFY", "packet", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L284-L319
26,569
Rapptz/discord.py
discord/gateway.py
DiscordWebSocket.resume
async def resume(self): """Sends the RESUME packet.""" payload = { 'op': self.RESUME, 'd': { 'seq': self.sequence, 'session_id': self.session_id, 'token': self.token } } await self.send_as_json(payload) log.info('Shard ID %s has sent the RESUME payload.', self.shard_id)
python
async def resume(self): """Sends the RESUME packet.""" payload = { 'op': self.RESUME, 'd': { 'seq': self.sequence, 'session_id': self.session_id, 'token': self.token } } await self.send_as_json(payload) log.info('Shard ID %s has sent the RESUME payload.', self.shard_id)
[ "async", "def", "resume", "(", "self", ")", ":", "payload", "=", "{", "'op'", ":", "self", ".", "RESUME", ",", "'d'", ":", "{", "'seq'", ":", "self", ".", "sequence", ",", "'session_id'", ":", "self", ".", "session_id", ",", "'token'", ":", "self", ".", "token", "}", "}", "await", "self", ".", "send_as_json", "(", "payload", ")", "log", ".", "info", "(", "'Shard ID %s has sent the RESUME payload.'", ",", "self", ".", "shard_id", ")" ]
Sends the RESUME packet.
[ "Sends", "the", "RESUME", "packet", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L321-L333
26,570
Rapptz/discord.py
discord/gateway.py
DiscordWebSocket.poll_event
async def poll_event(self): """Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was terminated for unhandled reasons. """ try: msg = await self.recv() await self.received_message(msg) except websockets.exceptions.ConnectionClosed as exc: if self._can_handle_close(exc.code): log.info('Websocket closed with %s (%s), attempting a reconnect.', exc.code, exc.reason) raise ResumeWebSocket(self.shard_id) from exc else: log.info('Websocket closed with %s (%s), cannot reconnect.', exc.code, exc.reason) raise ConnectionClosed(exc, shard_id=self.shard_id) from exc
python
async def poll_event(self): """Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was terminated for unhandled reasons. """ try: msg = await self.recv() await self.received_message(msg) except websockets.exceptions.ConnectionClosed as exc: if self._can_handle_close(exc.code): log.info('Websocket closed with %s (%s), attempting a reconnect.', exc.code, exc.reason) raise ResumeWebSocket(self.shard_id) from exc else: log.info('Websocket closed with %s (%s), cannot reconnect.', exc.code, exc.reason) raise ConnectionClosed(exc, shard_id=self.shard_id) from exc
[ "async", "def", "poll_event", "(", "self", ")", ":", "try", ":", "msg", "=", "await", "self", ".", "recv", "(", ")", "await", "self", ".", "received_message", "(", "msg", ")", "except", "websockets", ".", "exceptions", ".", "ConnectionClosed", "as", "exc", ":", "if", "self", ".", "_can_handle_close", "(", "exc", ".", "code", ")", ":", "log", ".", "info", "(", "'Websocket closed with %s (%s), attempting a reconnect.'", ",", "exc", ".", "code", ",", "exc", ".", "reason", ")", "raise", "ResumeWebSocket", "(", "self", ".", "shard_id", ")", "from", "exc", "else", ":", "log", ".", "info", "(", "'Websocket closed with %s (%s), cannot reconnect.'", ",", "exc", ".", "code", ",", "exc", ".", "reason", ")", "raise", "ConnectionClosed", "(", "exc", ",", "shard_id", "=", "self", ".", "shard_id", ")", "from", "exc" ]
Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was terminated for unhandled reasons.
[ "Polls", "for", "a", "DISPATCH", "event", "and", "handles", "the", "general", "gateway", "loop", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L460-L477
26,571
Rapptz/discord.py
discord/ext/commands/help.py
Paginator.clear
def clear(self): """Clears the paginator to have no pages.""" if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: self._current_page = [] self._count = 0 self._pages = []
python
def clear(self): """Clears the paginator to have no pages.""" if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: self._current_page = [] self._count = 0 self._pages = []
[ "def", "clear", "(", "self", ")", ":", "if", "self", ".", "prefix", "is", "not", "None", ":", "self", ".", "_current_page", "=", "[", "self", ".", "prefix", "]", "self", ".", "_count", "=", "len", "(", "self", ".", "prefix", ")", "+", "1", "# prefix + newline", "else", ":", "self", ".", "_current_page", "=", "[", "]", "self", ".", "_count", "=", "0", "self", ".", "_pages", "=", "[", "]" ]
Clears the paginator to have no pages.
[ "Clears", "the", "paginator", "to", "have", "no", "pages", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L89-L97
26,572
Rapptz/discord.py
discord/ext/commands/help.py
Paginator.add_line
def add_line(self, line='', *, empty=False): """Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicates if another empty line should be added. Raises ------ RuntimeError The line was too big for the current :attr:`max_size`. """ max_page_size = self.max_size - self._prefix_len - 2 if len(line) > max_page_size: raise RuntimeError('Line exceeds maximum page size %s' % (max_page_size)) if self._count + len(line) + 1 > self.max_size: self.close_page() self._count += len(line) + 1 self._current_page.append(line) if empty: self._current_page.append('') self._count += 1
python
def add_line(self, line='', *, empty=False): """Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicates if another empty line should be added. Raises ------ RuntimeError The line was too big for the current :attr:`max_size`. """ max_page_size = self.max_size - self._prefix_len - 2 if len(line) > max_page_size: raise RuntimeError('Line exceeds maximum page size %s' % (max_page_size)) if self._count + len(line) + 1 > self.max_size: self.close_page() self._count += len(line) + 1 self._current_page.append(line) if empty: self._current_page.append('') self._count += 1
[ "def", "add_line", "(", "self", ",", "line", "=", "''", ",", "*", ",", "empty", "=", "False", ")", ":", "max_page_size", "=", "self", ".", "max_size", "-", "self", ".", "_prefix_len", "-", "2", "if", "len", "(", "line", ")", ">", "max_page_size", ":", "raise", "RuntimeError", "(", "'Line exceeds maximum page size %s'", "%", "(", "max_page_size", ")", ")", "if", "self", ".", "_count", "+", "len", "(", "line", ")", "+", "1", ">", "self", ".", "max_size", ":", "self", ".", "close_page", "(", ")", "self", ".", "_count", "+=", "len", "(", "line", ")", "+", "1", "self", ".", "_current_page", ".", "append", "(", "line", ")", "if", "empty", ":", "self", ".", "_current_page", ".", "append", "(", "''", ")", "self", ".", "_count", "+=", "1" ]
Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicates if another empty line should be added. Raises ------ RuntimeError The line was too big for the current :attr:`max_size`.
[ "Adds", "a", "line", "to", "the", "current", "page", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L103-L133
26,573
Rapptz/discord.py
discord/ext/commands/help.py
Paginator.close_page
def close_page(self): """Prematurely terminate a page.""" if self.suffix is not None: self._current_page.append(self.suffix) self._pages.append('\n'.join(self._current_page)) if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: self._current_page = [] self._count = 0
python
def close_page(self): """Prematurely terminate a page.""" if self.suffix is not None: self._current_page.append(self.suffix) self._pages.append('\n'.join(self._current_page)) if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: self._current_page = [] self._count = 0
[ "def", "close_page", "(", "self", ")", ":", "if", "self", ".", "suffix", "is", "not", "None", ":", "self", ".", "_current_page", ".", "append", "(", "self", ".", "suffix", ")", "self", ".", "_pages", ".", "append", "(", "'\\n'", ".", "join", "(", "self", ".", "_current_page", ")", ")", "if", "self", ".", "prefix", "is", "not", "None", ":", "self", ".", "_current_page", "=", "[", "self", ".", "prefix", "]", "self", ".", "_count", "=", "len", "(", "self", ".", "prefix", ")", "+", "1", "# prefix + newline", "else", ":", "self", ".", "_current_page", "=", "[", "]", "self", ".", "_count", "=", "0" ]
Prematurely terminate a page.
[ "Prematurely", "terminate", "a", "page", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L135-L146
26,574
Rapptz/discord.py
discord/ext/commands/help.py
HelpCommand.clean_prefix
def clean_prefix(self): """The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.""" user = self.context.guild.me if self.context.guild else self.context.bot.user # this breaks if the prefix mention is not the bot itself but I # consider this to be an *incredibly* strange use case. I'd rather go # for this common use case rather than waste performance for the # odd one. return self.context.prefix.replace(user.mention, '@' + user.display_name)
python
def clean_prefix(self): """The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.""" user = self.context.guild.me if self.context.guild else self.context.bot.user # this breaks if the prefix mention is not the bot itself but I # consider this to be an *incredibly* strange use case. I'd rather go # for this common use case rather than waste performance for the # odd one. return self.context.prefix.replace(user.mention, '@' + user.display_name)
[ "def", "clean_prefix", "(", "self", ")", ":", "user", "=", "self", ".", "context", ".", "guild", ".", "me", "if", "self", ".", "context", ".", "guild", "else", "self", ".", "context", ".", "bot", ".", "user", "# this breaks if the prefix mention is not the bot itself but I", "# consider this to be an *incredibly* strange use case. I'd rather go", "# for this common use case rather than waste performance for the", "# odd one.", "return", "self", ".", "context", ".", "prefix", ".", "replace", "(", "user", ".", "mention", ",", "'@'", "+", "user", ".", "display_name", ")" ]
The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
[ "The", "cleaned", "up", "invoke", "prefix", ".", "i", ".", "e", ".", "mentions", "are" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L336-L343
26,575
Rapptz/discord.py
discord/ext/commands/help.py
HelpCommand.get_command_signature
def get_command_signature(self, command): """Retrieves the signature portion of the help page. Parameters ------------ command: :class:`Command` The command to get the signature of. Returns -------- :class:`str` The signature for the command. """ parent = command.full_parent_name if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = '[%s|%s]' % (command.name, aliases) if parent: fmt = parent + ' ' + fmt alias = fmt else: alias = command.name if not parent else parent + ' ' + command.name return '%s%s %s' % (self.clean_prefix, alias, command.signature)
python
def get_command_signature(self, command): """Retrieves the signature portion of the help page. Parameters ------------ command: :class:`Command` The command to get the signature of. Returns -------- :class:`str` The signature for the command. """ parent = command.full_parent_name if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = '[%s|%s]' % (command.name, aliases) if parent: fmt = parent + ' ' + fmt alias = fmt else: alias = command.name if not parent else parent + ' ' + command.name return '%s%s %s' % (self.clean_prefix, alias, command.signature)
[ "def", "get_command_signature", "(", "self", ",", "command", ")", ":", "parent", "=", "command", ".", "full_parent_name", "if", "len", "(", "command", ".", "aliases", ")", ">", "0", ":", "aliases", "=", "'|'", ".", "join", "(", "command", ".", "aliases", ")", "fmt", "=", "'[%s|%s]'", "%", "(", "command", ".", "name", ",", "aliases", ")", "if", "parent", ":", "fmt", "=", "parent", "+", "' '", "+", "fmt", "alias", "=", "fmt", "else", ":", "alias", "=", "command", ".", "name", "if", "not", "parent", "else", "parent", "+", "' '", "+", "command", ".", "name", "return", "'%s%s %s'", "%", "(", "self", ".", "clean_prefix", ",", "alias", ",", "command", ".", "signature", ")" ]
Retrieves the signature portion of the help page. Parameters ------------ command: :class:`Command` The command to get the signature of. Returns -------- :class:`str` The signature for the command.
[ "Retrieves", "the", "signature", "portion", "of", "the", "help", "page", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L366-L390
26,576
Rapptz/discord.py
discord/ext/commands/help.py
HelpCommand.remove_mentions
def remove_mentions(self, string): """Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mentions. """ def replace(obj, *, transforms=self.MENTION_TRANSFORMS): return transforms.get(obj.group(0), '@invalid') return self.MENTION_PATTERN.sub(replace, string)
python
def remove_mentions(self, string): """Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mentions. """ def replace(obj, *, transforms=self.MENTION_TRANSFORMS): return transforms.get(obj.group(0), '@invalid') return self.MENTION_PATTERN.sub(replace, string)
[ "def", "remove_mentions", "(", "self", ",", "string", ")", ":", "def", "replace", "(", "obj", ",", "*", ",", "transforms", "=", "self", ".", "MENTION_TRANSFORMS", ")", ":", "return", "transforms", ".", "get", "(", "obj", ".", "group", "(", "0", ")", ",", "'@invalid'", ")", "return", "self", ".", "MENTION_PATTERN", ".", "sub", "(", "replace", ",", "string", ")" ]
Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mentions.
[ "Removes", "mentions", "from", "the", "string", "to", "prevent", "abuse", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L392-L401
26,577
Rapptz/discord.py
discord/ext/commands/help.py
HelpCommand.get_max_size
def get_max_size(self, commands): """Returns the largest name length of the specified command list. Parameters ------------ commands: Sequence[:class:`Command`] A sequence of commands to check for the largest size. Returns -------- :class:`int` The maximum width of the commands. """ as_lengths = ( discord.utils._string_width(c.name) for c in commands ) return max(as_lengths, default=0)
python
def get_max_size(self, commands): """Returns the largest name length of the specified command list. Parameters ------------ commands: Sequence[:class:`Command`] A sequence of commands to check for the largest size. Returns -------- :class:`int` The maximum width of the commands. """ as_lengths = ( discord.utils._string_width(c.name) for c in commands ) return max(as_lengths, default=0)
[ "def", "get_max_size", "(", "self", ",", "commands", ")", ":", "as_lengths", "=", "(", "discord", ".", "utils", ".", "_string_width", "(", "c", ".", "name", ")", "for", "c", "in", "commands", ")", "return", "max", "(", "as_lengths", ",", "default", "=", "0", ")" ]
Returns the largest name length of the specified command list. Parameters ------------ commands: Sequence[:class:`Command`] A sequence of commands to check for the largest size. Returns -------- :class:`int` The maximum width of the commands.
[ "Returns", "the", "largest", "name", "length", "of", "the", "specified", "command", "list", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L532-L550
26,578
Rapptz/discord.py
discord/ext/commands/help.py
DefaultHelpCommand.add_indented_commands
def add_indented_commands(self, commands, *, heading, max_size=None): """Indents a list of commands after the specified heading. The formatting is added to the :attr:`paginator`. The default implementation is the command name indented by :attr:`indent` spaces, padded to ``max_size`` followed by the command's :attr:`Command.short_doc` and then shortened to fit into the :attr:`width`. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands to indent for output. heading: :class:`str` The heading to add to the output. This is only added if the list of commands is greater than 0. max_size: Optional[:class:`int`] The max size to use for the gap between indents. If unspecified, calls :meth:`get_max_size` on the commands parameter. """ if not commands: return self.paginator.add_line(heading) max_size = max_size or self.get_max_size(commands) get_width = discord.utils._string_width for command in commands: name = command.name width = max_size - (get_width(name) - len(name)) entry = '{0}{1:<{width}} {2}'.format(self.indent * ' ', name, command.short_doc, width=width) self.paginator.add_line(self.shorten_text(entry))
python
def add_indented_commands(self, commands, *, heading, max_size=None): """Indents a list of commands after the specified heading. The formatting is added to the :attr:`paginator`. The default implementation is the command name indented by :attr:`indent` spaces, padded to ``max_size`` followed by the command's :attr:`Command.short_doc` and then shortened to fit into the :attr:`width`. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands to indent for output. heading: :class:`str` The heading to add to the output. This is only added if the list of commands is greater than 0. max_size: Optional[:class:`int`] The max size to use for the gap between indents. If unspecified, calls :meth:`get_max_size` on the commands parameter. """ if not commands: return self.paginator.add_line(heading) max_size = max_size or self.get_max_size(commands) get_width = discord.utils._string_width for command in commands: name = command.name width = max_size - (get_width(name) - len(name)) entry = '{0}{1:<{width}} {2}'.format(self.indent * ' ', name, command.short_doc, width=width) self.paginator.add_line(self.shorten_text(entry))
[ "def", "add_indented_commands", "(", "self", ",", "commands", ",", "*", ",", "heading", ",", "max_size", "=", "None", ")", ":", "if", "not", "commands", ":", "return", "self", ".", "paginator", ".", "add_line", "(", "heading", ")", "max_size", "=", "max_size", "or", "self", ".", "get_max_size", "(", "commands", ")", "get_width", "=", "discord", ".", "utils", ".", "_string_width", "for", "command", "in", "commands", ":", "name", "=", "command", ".", "name", "width", "=", "max_size", "-", "(", "get_width", "(", "name", ")", "-", "len", "(", "name", ")", ")", "entry", "=", "'{0}{1:<{width}} {2}'", ".", "format", "(", "self", ".", "indent", "*", "' '", ",", "name", ",", "command", ".", "short_doc", ",", "width", "=", "width", ")", "self", ".", "paginator", ".", "add_line", "(", "self", ".", "shorten_text", "(", "entry", ")", ")" ]
Indents a list of commands after the specified heading. The formatting is added to the :attr:`paginator`. The default implementation is the command name indented by :attr:`indent` spaces, padded to ``max_size`` followed by the command's :attr:`Command.short_doc` and then shortened to fit into the :attr:`width`. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands to indent for output. heading: :class:`str` The heading to add to the output. This is only added if the list of commands is greater than 0. max_size: Optional[:class:`int`] The max size to use for the gap between indents. If unspecified, calls :meth:`get_max_size` on the commands parameter.
[ "Indents", "a", "list", "of", "commands", "after", "the", "specified", "heading", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L877-L911
26,579
Rapptz/discord.py
discord/ext/commands/help.py
MinimalHelpCommand.add_bot_commands_formatting
def add_bot_commands_formatting(self, commands, heading): """Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line. """ if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line('__**%s**__' % heading) self.paginator.add_line(joined)
python
def add_bot_commands_formatting(self, commands, heading): """Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line. """ if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line('__**%s**__' % heading) self.paginator.add_line(joined)
[ "def", "add_bot_commands_formatting", "(", "self", ",", "commands", ",", "heading", ")", ":", "if", "commands", ":", "# U+2002 Middle Dot", "joined", "=", "'\\u2002'", ".", "join", "(", "c", ".", "name", "for", "c", "in", "commands", ")", "self", ".", "paginator", ".", "add_line", "(", "'__**%s**__'", "%", "heading", ")", "self", ".", "paginator", ".", "add_line", "(", "joined", ")" ]
Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line.
[ "Adds", "the", "minified", "bot", "heading", "with", "commands", "to", "the", "output", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1092-L1111
26,580
Rapptz/discord.py
discord/ext/commands/help.py
MinimalHelpCommand.add_subcommand_formatting
def add_subcommand_formatting(self, command): """Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of. """ fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.clean_prefix, command.qualified_name, command.short_doc))
python
def add_subcommand_formatting(self, command): """Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of. """ fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.clean_prefix, command.qualified_name, command.short_doc))
[ "def", "add_subcommand_formatting", "(", "self", ",", "command", ")", ":", "fmt", "=", "'{0}{1} \\N{EN DASH} {2}'", "if", "command", ".", "short_doc", "else", "'{0}{1}'", "self", ".", "paginator", ".", "add_line", "(", "fmt", ".", "format", "(", "self", ".", "clean_prefix", ",", "command", ".", "qualified_name", ",", "command", ".", "short_doc", ")", ")" ]
Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of.
[ "Adds", "formatting", "information", "on", "a", "subcommand", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1113-L1127
26,581
Rapptz/discord.py
discord/ext/commands/help.py
MinimalHelpCommand.add_aliases_formatting
def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format. """ self.paginator.add_line('**%s** %s' % (self.aliases_heading, ', '.join(aliases)), empty=True)
python
def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format. """ self.paginator.add_line('**%s** %s' % (self.aliases_heading, ', '.join(aliases)), empty=True)
[ "def", "add_aliases_formatting", "(", "self", ",", "aliases", ")", ":", "self", ".", "paginator", ".", "add_line", "(", "'**%s** %s'", "%", "(", "self", ".", "aliases_heading", ",", "', '", ".", "join", "(", "aliases", ")", ")", ",", "empty", "=", "True", ")" ]
Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format.
[ "Adds", "the", "formatting", "information", "on", "a", "command", "s", "aliases", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1129-L1144
26,582
Rapptz/discord.py
discord/ext/commands/help.py
MinimalHelpCommand.add_command_formatting
def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(signature) self.add_aliases_formatting(command.aliases) else: self.paginator.add_line(signature, empty=True) if command.help: try: self.paginator.add_line(command.help, empty=True) except RuntimeError: for line in command.help.splitlines(): self.paginator.add_line(line) self.paginator.add_line()
python
def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(signature) self.add_aliases_formatting(command.aliases) else: self.paginator.add_line(signature, empty=True) if command.help: try: self.paginator.add_line(command.help, empty=True) except RuntimeError: for line in command.help.splitlines(): self.paginator.add_line(line) self.paginator.add_line()
[ "def", "add_command_formatting", "(", "self", ",", "command", ")", ":", "if", "command", ".", "description", ":", "self", ".", "paginator", ".", "add_line", "(", "command", ".", "description", ",", "empty", "=", "True", ")", "signature", "=", "self", ".", "get_command_signature", "(", "command", ")", "if", "command", ".", "aliases", ":", "self", ".", "paginator", ".", "add_line", "(", "signature", ")", "self", ".", "add_aliases_formatting", "(", "command", ".", "aliases", ")", "else", ":", "self", ".", "paginator", ".", "add_line", "(", "signature", ",", "empty", "=", "True", ")", "if", "command", ".", "help", ":", "try", ":", "self", ".", "paginator", ".", "add_line", "(", "command", ".", "help", ",", "empty", "=", "True", ")", "except", "RuntimeError", ":", "for", "line", "in", "command", ".", "help", ".", "splitlines", "(", ")", ":", "self", ".", "paginator", ".", "add_line", "(", "line", ")", "self", ".", "paginator", ".", "add_line", "(", ")" ]
A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format.
[ "A", "utility", "function", "to", "format", "commands", "and", "groups", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1146-L1171
26,583
Rapptz/discord.py
discord/voice_client.py
VoiceClient.send_audio_packet
def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed. """ self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_ip, self.voice_port)) except BlockingIOError: log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) self.checked_add('timestamp', self.encoder.SAMPLES_PER_FRAME, 4294967295)
python
def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed. """ self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_ip, self.voice_port)) except BlockingIOError: log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) self.checked_add('timestamp', self.encoder.SAMPLES_PER_FRAME, 4294967295)
[ "def", "send_audio_packet", "(", "self", ",", "data", ",", "*", ",", "encode", "=", "True", ")", ":", "self", ".", "checked_add", "(", "'sequence'", ",", "1", ",", "65535", ")", "if", "encode", ":", "encoded_data", "=", "self", ".", "encoder", ".", "encode", "(", "data", ",", "self", ".", "encoder", ".", "SAMPLES_PER_FRAME", ")", "else", ":", "encoded_data", "=", "data", "packet", "=", "self", ".", "_get_voice_packet", "(", "encoded_data", ")", "try", ":", "self", ".", "socket", ".", "sendto", "(", "packet", ",", "(", "self", ".", "endpoint_ip", ",", "self", ".", "voice_port", ")", ")", "except", "BlockingIOError", ":", "log", ".", "warning", "(", "'A packet has been dropped (seq: %s, timestamp: %s)'", ",", "self", ".", "sequence", ",", "self", ".", "timestamp", ")", "self", ".", "checked_add", "(", "'timestamp'", ",", "self", ".", "encoder", ".", "SAMPLES_PER_FRAME", ",", "4294967295", ")" ]
Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed.
[ "Sends", "an", "audio", "packet", "composed", "of", "the", "data", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L415-L446
26,584
Rapptz/discord.py
discord/client.py
Client.clear
def clear(self): """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
python
def clear(self): """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_closed", "=", "False", "self", ".", "_ready", ".", "clear", "(", ")", "self", ".", "_connection", ".", "clear", "(", ")", "self", ".", "http", ".", "recreate", "(", ")" ]
Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared.
[ "Clears", "the", "internal", "state", "of", "the", "bot", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L490-L500
26,585
Rapptz/discord.py
discord/client.py
Client.run
def run(self, *args, **kwargs): """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: self.loop.run_until_complete(runner()) except KeyboardInterrupt: log.info('Received signal to terminate bot and event loop.') finally: log.info('Cleaning up tasks.') _cleanup_loop(self.loop)
python
def run(self, *args, **kwargs): """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: self.loop.run_until_complete(runner()) except KeyboardInterrupt: log.info('Received signal to terminate bot and event loop.') finally: log.info('Cleaning up tasks.') _cleanup_loop(self.loop)
[ "def", "run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "async", "def", "runner", "(", ")", ":", "try", ":", "await", "self", ".", "start", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "await", "self", ".", "close", "(", ")", "try", ":", "self", ".", "loop", ".", "run_until_complete", "(", "runner", "(", ")", ")", "except", "KeyboardInterrupt", ":", "log", ".", "info", "(", "'Received signal to terminate bot and event loop.'", ")", "finally", ":", "log", ".", "info", "(", "'Cleaning up tasks.'", ")", "_cleanup_loop", "(", "self", ".", "loop", ")" ]
A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
[ "A", "blocking", "call", "that", "abstracts", "away", "the", "event", "loop", "initialisation", "from", "you", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L513-L549
26,586
Rapptz/discord.py
discord/client.py
Client.event
def event(self, coro): """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', coro.__name__) return coro
python
def event(self, coro): """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', coro.__name__) return coro
[ "def", "event", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'event registered must be a coroutine function'", ")", "setattr", "(", "self", ",", "coro", ".", "__name__", ",", "coro", ")", "log", ".", "debug", "(", "'%s has successfully been registered as an event'", ",", "coro", ".", "__name__", ")", "return", "coro" ]
A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine.
[ "A", "decorator", "that", "registers", "an", "event", "to", "listen", "to", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L740-L767
26,587
Rapptz/discord.py
discord/message.py
Message.raw_role_mentions
def raw_role_mentions(self): """A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content. """ return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
python
def raw_role_mentions(self): """A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content. """ return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
[ "def", "raw_role_mentions", "(", "self", ")", ":", "return", "[", "int", "(", "x", ")", "for", "x", "in", "re", ".", "findall", "(", "r'<@&([0-9]+)>'", ",", "self", ".", "content", ")", "]" ]
A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.
[ "A", "property", "that", "returns", "an", "array", "of", "role", "IDs", "matched", "with", "the", "syntax", "of", "<" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L387-L391
26,588
Rapptz/discord.py
discord/ext/commands/bot.py
when_mentioned_or
def when_mentioned_or(*prefixes): """A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example -------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also ---------- :func:`.when_mentioned` """ def inner(bot, msg): r = list(prefixes) r = when_mentioned(bot, msg) + r return r return inner
python
def when_mentioned_or(*prefixes): """A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example -------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also ---------- :func:`.when_mentioned` """ def inner(bot, msg): r = list(prefixes) r = when_mentioned(bot, msg) + r return r return inner
[ "def", "when_mentioned_or", "(", "*", "prefixes", ")", ":", "def", "inner", "(", "bot", ",", "msg", ")", ":", "r", "=", "list", "(", "prefixes", ")", "r", "=", "when_mentioned", "(", "bot", ",", "msg", ")", "+", "r", "return", "r", "return", "inner" ]
A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example -------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also ---------- :func:`.when_mentioned`
[ "A", "callable", "that", "implements", "when", "mentioned", "or", "other", "prefixes", "provided", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L52-L86
26,589
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.add_check
def add_check(self, func, *, call_once=False): """Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------- func The function that was used as a global check. call_once: :class:`bool` If the function should only be called once per :meth:`.Command.invoke` call. """ if call_once: self._check_once.append(func) else: self._checks.append(func)
python
def add_check(self, func, *, call_once=False): """Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------- func The function that was used as a global check. call_once: :class:`bool` If the function should only be called once per :meth:`.Command.invoke` call. """ if call_once: self._check_once.append(func) else: self._checks.append(func)
[ "def", "add_check", "(", "self", ",", "func", ",", "*", ",", "call_once", "=", "False", ")", ":", "if", "call_once", ":", "self", ".", "_check_once", ".", "append", "(", "func", ")", "else", ":", "self", ".", "_checks", ".", "append", "(", "func", ")" ]
Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------- func The function that was used as a global check. call_once: :class:`bool` If the function should only be called once per :meth:`.Command.invoke` call.
[ "Adds", "a", "global", "check", "to", "the", "bot", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L200-L218
26,590
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.remove_check
def remove_check(self, func, *, call_once=False): """Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks. Parameters ----------- func The function to remove from the global checks. call_once: :class:`bool` If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. """ l = self._check_once if call_once else self._checks try: l.remove(func) except ValueError: pass
python
def remove_check(self, func, *, call_once=False): """Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks. Parameters ----------- func The function to remove from the global checks. call_once: :class:`bool` If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. """ l = self._check_once if call_once else self._checks try: l.remove(func) except ValueError: pass
[ "def", "remove_check", "(", "self", ",", "func", ",", "*", ",", "call_once", "=", "False", ")", ":", "l", "=", "self", ".", "_check_once", "if", "call_once", "else", "self", ".", "_checks", "try", ":", "l", ".", "remove", "(", "func", ")", "except", "ValueError", ":", "pass" ]
Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks. Parameters ----------- func The function to remove from the global checks. call_once: :class:`bool` If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`.
[ "Removes", "a", "global", "check", "from", "the", "bot", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L220-L239
26,591
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.remove_listener
def remove_listener(self, func, name=None): """Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ``func.__name__``. """ name = func.__name__ if name is None else name if name in self.extra_events: try: self.extra_events[name].remove(func) except ValueError: pass
python
def remove_listener(self, func, name=None): """Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ``func.__name__``. """ name = func.__name__ if name is None else name if name in self.extra_events: try: self.extra_events[name].remove(func) except ValueError: pass
[ "def", "remove_listener", "(", "self", ",", "func", ",", "name", "=", "None", ")", ":", "name", "=", "func", ".", "__name__", "if", "name", "is", "None", "else", "name", "if", "name", "in", "self", ".", "extra_events", ":", "try", ":", "self", ".", "extra_events", "[", "name", "]", ".", "remove", "(", "func", ")", "except", "ValueError", ":", "pass" ]
Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ``func.__name__``.
[ "Removes", "a", "listener", "from", "the", "pool", "of", "listeners", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L399-L417
26,592
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.add_cog
def add_cog(self, cog): """Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. Parameters ----------- cog: :class:`.Cog` The cog to register to the bot. Raises ------- TypeError The cog does not inherit from :class:`.Cog`. CommandError An error happened during loading. """ if not isinstance(cog, Cog): raise TypeError('cogs must derive from Cog') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog
python
def add_cog(self, cog): """Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. Parameters ----------- cog: :class:`.Cog` The cog to register to the bot. Raises ------- TypeError The cog does not inherit from :class:`.Cog`. CommandError An error happened during loading. """ if not isinstance(cog, Cog): raise TypeError('cogs must derive from Cog') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog
[ "def", "add_cog", "(", "self", ",", "cog", ")", ":", "if", "not", "isinstance", "(", "cog", ",", "Cog", ")", ":", "raise", "TypeError", "(", "'cogs must derive from Cog'", ")", "cog", "=", "cog", ".", "_inject", "(", "self", ")", "self", ".", "__cogs", "[", "cog", ".", "__cog_name__", "]", "=", "cog" ]
Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. Parameters ----------- cog: :class:`.Cog` The cog to register to the bot. Raises ------- TypeError The cog does not inherit from :class:`.Cog`. CommandError An error happened during loading.
[ "Adds", "a", "cog", "to", "the", "bot", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L457-L479
26,593
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.remove_cog
def remove_cog(self, name): """Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect. Parameters ----------- name: :class:`str` The name of the cog to remove. """ cog = self.__cogs.pop(name, None) if cog is None: return help_command = self._help_command if help_command and help_command.cog is cog: help_command.cog = None cog._eject(self)
python
def remove_cog(self, name): """Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect. Parameters ----------- name: :class:`str` The name of the cog to remove. """ cog = self.__cogs.pop(name, None) if cog is None: return help_command = self._help_command if help_command and help_command.cog is cog: help_command.cog = None cog._eject(self)
[ "def", "remove_cog", "(", "self", ",", "name", ")", ":", "cog", "=", "self", ".", "__cogs", ".", "pop", "(", "name", ",", "None", ")", "if", "cog", "is", "None", ":", "return", "help_command", "=", "self", ".", "_help_command", "if", "help_command", "and", "help_command", ".", "cog", "is", "cog", ":", "help_command", ".", "cog", "=", "None", "cog", ".", "_eject", "(", "self", ")" ]
Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect. Parameters ----------- name: :class:`str` The name of the cog to remove.
[ "Removes", "a", "cog", "from", "the", "bot", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L495-L516
26,594
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.load_extension
def load_extension(self, name): """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ------------ name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises -------- ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The extension is already loaded. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ if name in self.__extensions: raise errors.ExtensionAlreadyLoaded(name) try: lib = importlib.import_module(name) except ImportError as e: raise errors.ExtensionNotFound(name, e) from e else: self._load_from_module_spec(lib, name)
python
def load_extension(self, name): """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ------------ name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises -------- ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The extension is already loaded. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ if name in self.__extensions: raise errors.ExtensionAlreadyLoaded(name) try: lib = importlib.import_module(name) except ImportError as e: raise errors.ExtensionNotFound(name, e) from e else: self._load_from_module_spec(lib, name)
[ "def", "load_extension", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "__extensions", ":", "raise", "errors", ".", "ExtensionAlreadyLoaded", "(", "name", ")", "try", ":", "lib", "=", "importlib", ".", "import_module", "(", "name", ")", "except", "ImportError", "as", "e", ":", "raise", "errors", ".", "ExtensionNotFound", "(", "name", ",", "e", ")", "from", "e", "else", ":", "self", ".", "_load_from_module_spec", "(", "lib", ",", "name", ")" ]
Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ------------ name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises -------- ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The extension is already loaded. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error.
[ "Loads", "an", "extension", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L584-L621
26,595
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.unload_extension
def unload_extension(self, name): """Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up if necessary. This function takes a single parameter, the ``bot``, similar to ``setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name)
python
def unload_extension(self, name): """Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up if necessary. This function takes a single parameter, the ``bot``, similar to ``setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name)
[ "def", "unload_extension", "(", "self", ",", "name", ")", ":", "lib", "=", "self", ".", "__extensions", ".", "get", "(", "name", ")", "if", "lib", "is", "None", ":", "raise", "errors", ".", "ExtensionNotLoaded", "(", "name", ")", "self", ".", "_remove_module_references", "(", "lib", ".", "__name__", ")", "self", ".", "_call_module_finalizers", "(", "lib", ",", "name", ")" ]
Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up if necessary. This function takes a single parameter, the ``bot``, similar to ``setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded.
[ "Unloads", "an", "extension", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L623-L652
26,596
Rapptz/discord.py
discord/ext/commands/bot.py
BotBase.reload_extension
def reload_extension(self, name): """Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state. Parameters ------------ name: :class:`str` The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could not be imported. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) # get the previous module states from sys modules modules = { name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception as e: # if the load failed, the remnants should have been # cleaned from the load_extension function call # so let's load it from our old compiled library. self._load_from_module_spec(lib, name) # revert sys.modules back to normal and raise back to caller sys.modules.update(modules) raise
python
def reload_extension(self, name): """Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state. Parameters ------------ name: :class:`str` The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could not be imported. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) # get the previous module states from sys modules modules = { name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception as e: # if the load failed, the remnants should have been # cleaned from the load_extension function call # so let's load it from our old compiled library. self._load_from_module_spec(lib, name) # revert sys.modules back to normal and raise back to caller sys.modules.update(modules) raise
[ "def", "reload_extension", "(", "self", ",", "name", ")", ":", "lib", "=", "self", ".", "__extensions", ".", "get", "(", "name", ")", "if", "lib", "is", "None", ":", "raise", "errors", ".", "ExtensionNotLoaded", "(", "name", ")", "# get the previous module states from sys modules", "modules", "=", "{", "name", ":", "module", "for", "name", ",", "module", "in", "sys", ".", "modules", ".", "items", "(", ")", "if", "_is_submodule", "(", "lib", ".", "__name__", ",", "name", ")", "}", "try", ":", "# Unload and then load the module...", "self", ".", "_remove_module_references", "(", "lib", ".", "__name__", ")", "self", ".", "_call_module_finalizers", "(", "lib", ",", "name", ")", "self", ".", "load_extension", "(", "name", ")", "except", "Exception", "as", "e", ":", "# if the load failed, the remnants should have been", "# cleaned from the load_extension function call", "# so let's load it from our old compiled library.", "self", ".", "_load_from_module_spec", "(", "lib", ",", "name", ")", "# revert sys.modules back to normal and raise back to caller", "sys", ".", "modules", ".", "update", "(", "modules", ")", "raise" ]
Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state. Parameters ------------ name: :class:`str` The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could not be imported. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error.
[ "Atomically", "reloads", "an", "extension", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L654-L705
26,597
Rapptz/discord.py
discord/guild.py
Guild.chunked
def chunked(self): """Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members stored in the internal :attr:`members` cache. If this value returns ``False``, then you should request for offline members. """ count = getattr(self, '_member_count', None) if count is None: return False return count == len(self._members)
python
def chunked(self): """Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members stored in the internal :attr:`members` cache. If this value returns ``False``, then you should request for offline members. """ count = getattr(self, '_member_count', None) if count is None: return False return count == len(self._members)
[ "def", "chunked", "(", "self", ")", ":", "count", "=", "getattr", "(", "self", ",", "'_member_count'", ",", "None", ")", "if", "count", "is", "None", ":", "return", "False", "return", "count", "==", "len", "(", "self", ".", "_members", ")" ]
Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members stored in the internal :attr:`members` cache. If this value returns ``False``, then you should request for offline members.
[ "Returns", "a", "boolean", "indicating", "if", "the", "guild", "is", "chunked", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L515-L527
26,598
Rapptz/discord.py
discord/guild.py
Guild.shard_id
def shard_id(self): """Returns the shard ID for this guild if applicable.""" count = self._state.shard_count if count is None: return None return (self.id >> 22) % count
python
def shard_id(self): """Returns the shard ID for this guild if applicable.""" count = self._state.shard_count if count is None: return None return (self.id >> 22) % count
[ "def", "shard_id", "(", "self", ")", ":", "count", "=", "self", ".", "_state", ".", "shard_count", "if", "count", "is", "None", ":", "return", "None", "return", "(", "self", ".", "id", ">>", "22", ")", "%", "count" ]
Returns the shard ID for this guild if applicable.
[ "Returns", "the", "shard", "ID", "for", "this", "guild", "if", "applicable", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L530-L535
26,599
Rapptz/discord.py
discord/guild.py
Guild.get_member_named
def get_member_named(self, name): """Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work. If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique. If no member is found, ``None`` is returned. Parameters ----------- name: :class:`str` The name of the member to lookup with an optional discriminator. Returns -------- :class:`Member` The member in this guild with the associated name. If not found then ``None`` is returned. """ result = None members = self.members if len(name) > 5 and name[-5] == '#': # The 5 length is checking to see if #0000 is in the string, # as a#0000 has a length of 6, the minimum for a potential # discriminator lookup. potential_discriminator = name[-4:] # do the actual lookup and return if found # if it isn't found then we'll do a full name lookup below. result = utils.get(members, name=name[:-5], discriminator=potential_discriminator) if result is not None: return result def pred(m): return m.nick == name or m.name == name return utils.find(pred, members)
python
def get_member_named(self, name): """Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work. If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique. If no member is found, ``None`` is returned. Parameters ----------- name: :class:`str` The name of the member to lookup with an optional discriminator. Returns -------- :class:`Member` The member in this guild with the associated name. If not found then ``None`` is returned. """ result = None members = self.members if len(name) > 5 and name[-5] == '#': # The 5 length is checking to see if #0000 is in the string, # as a#0000 has a length of 6, the minimum for a potential # discriminator lookup. potential_discriminator = name[-4:] # do the actual lookup and return if found # if it isn't found then we'll do a full name lookup below. result = utils.get(members, name=name[:-5], discriminator=potential_discriminator) if result is not None: return result def pred(m): return m.nick == name or m.name == name return utils.find(pred, members)
[ "def", "get_member_named", "(", "self", ",", "name", ")", ":", "result", "=", "None", "members", "=", "self", ".", "members", "if", "len", "(", "name", ")", ">", "5", "and", "name", "[", "-", "5", "]", "==", "'#'", ":", "# The 5 length is checking to see if #0000 is in the string,", "# as a#0000 has a length of 6, the minimum for a potential", "# discriminator lookup.", "potential_discriminator", "=", "name", "[", "-", "4", ":", "]", "# do the actual lookup and return if found", "# if it isn't found then we'll do a full name lookup below.", "result", "=", "utils", ".", "get", "(", "members", ",", "name", "=", "name", "[", ":", "-", "5", "]", ",", "discriminator", "=", "potential_discriminator", ")", "if", "result", "is", "not", "None", ":", "return", "result", "def", "pred", "(", "m", ")", ":", "return", "m", ".", "nick", "==", "name", "or", "m", ".", "name", "==", "name", "return", "utils", ".", "find", "(", "pred", ",", "members", ")" ]
Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work. If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique. If no member is found, ``None`` is returned. Parameters ----------- name: :class:`str` The name of the member to lookup with an optional discriminator. Returns -------- :class:`Member` The member in this guild with the associated name. If not found then ``None`` is returned.
[ "Returns", "the", "first", "member", "found", "that", "matches", "the", "name", "provided", "." ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L542-L586