repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
edx/pa11ycrawler
pa11ycrawler/spiders/edx.py
EdxSpider.after_initial_login
def after_initial_login(self, response): """ This method is called *only* if the crawler is started with an email and password combination. It verifies that the login request was successful, and then generates requests from `self.start_urls`. """ if LOGIN_FAILURE_...
python
def after_initial_login(self, response): """ This method is called *only* if the crawler is started with an email and password combination. It verifies that the login request was successful, and then generates requests from `self.start_urls`. """ if LOGIN_FAILURE_...
[ "def", "after_initial_login", "(", "self", ",", "response", ")", ":", "if", "LOGIN_FAILURE_MSG", "in", "response", ".", "text", ":", "self", ".", "logger", ".", "error", "(", "\"Credentials failed. Either add/update the current credentials \"", "\"or remove them to enable...
This method is called *only* if the crawler is started with an email and password combination. It verifies that the login request was successful, and then generates requests from `self.start_urls`.
[ "This", "method", "is", "called", "*", "only", "*", "if", "the", "crawler", "is", "started", "with", "an", "email", "and", "password", "combination", ".", "It", "verifies", "that", "the", "login", "request", "was", "successful", "and", "then", "generates", ...
train
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L260-L288
edx/pa11ycrawler
pa11ycrawler/spiders/edx.py
EdxSpider.after_auto_auth
def after_auto_auth(self, response): """ This method is called *only* if the crawler is started without an email and password combination. It parses the response from the "auto auth" feature, and saves the email and password combination. Then it generates requests from `self.star...
python
def after_auto_auth(self, response): """ This method is called *only* if the crawler is started without an email and password combination. It parses the response from the "auto auth" feature, and saves the email and password combination. Then it generates requests from `self.star...
[ "def", "after_auto_auth", "(", "self", ",", "response", ")", ":", "result", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "self", ".", "login_email", "=", "result", "[", "\"email\"", "]", "self", ".", "login_password", "=", "result", "[",...
This method is called *only* if the crawler is started without an email and password combination. It parses the response from the "auto auth" feature, and saves the email and password combination. Then it generates requests from `self.start_urls`.
[ "This", "method", "is", "called", "*", "only", "*", "if", "the", "crawler", "is", "started", "without", "an", "email", "and", "password", "combination", ".", "It", "parses", "the", "response", "from", "the", "auto", "auth", "feature", "and", "saves", "the"...
train
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L290-L317
edx/pa11ycrawler
pa11ycrawler/spiders/edx.py
EdxSpider.analyze_url_list
def analyze_url_list(self, response): """ Parse JSON response for the beginning url(s) for the crawler. """ response = json.loads(response.text) for _, block in response['blocks'].items(): for attribute in block: parsed = urlparse(block[attribu...
python
def analyze_url_list(self, response): """ Parse JSON response for the beginning url(s) for the crawler. """ response = json.loads(response.text) for _, block in response['blocks'].items(): for attribute in block: parsed = urlparse(block[attribu...
[ "def", "analyze_url_list", "(", "self", ",", "response", ")", ":", "response", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "for", "_", ",", "block", "in", "response", "[", "'blocks'", "]", ".", "items", "(", ")", ":", "for", "attrib...
Parse JSON response for the beginning url(s) for the crawler.
[ "Parse", "JSON", "response", "for", "the", "beginning", "url", "(", "s", ")", "for", "the", "crawler", "." ]
train
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L319-L330
edx/pa11ycrawler
pa11ycrawler/spiders/edx.py
EdxSpider.parse_item
def parse_item(self, response): """ Get basic information about a page, so that it can be passed to the `pa11y` tool for further testing. @url https://www.google.com/ @returns items 1 1 @returns requests 0 0 @scrapes url request_headers accessed_at page_title ...
python
def parse_item(self, response): """ Get basic information about a page, so that it can be passed to the `pa11y` tool for further testing. @url https://www.google.com/ @returns items 1 1 @returns requests 0 0 @scrapes url request_headers accessed_at page_title ...
[ "def", "parse_item", "(", "self", ",", "response", ")", ":", "# if we got redirected to a login page, then login", "if", "URLObject", "(", "response", ".", "url", ")", ".", "path", "==", "LOGIN_HTML_PATH", ":", "reqs", "=", "self", ".", "handle_unexpected_redirect_t...
Get basic information about a page, so that it can be passed to the `pa11y` tool for further testing. @url https://www.google.com/ @returns items 1 1 @returns requests 0 0 @scrapes url request_headers accessed_at page_title
[ "Get", "basic", "information", "about", "a", "page", "so", "that", "it", "can", "be", "passed", "to", "the", "pa11y", "tool", "for", "further", "testing", "." ]
train
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L332-L371
edx/pa11ycrawler
pa11ycrawler/spiders/edx.py
EdxSpider.handle_unexpected_redirect_to_login_page
def handle_unexpected_redirect_to_login_page(self, response): """ This method is called if the crawler has been unexpectedly logged out. If that happens, and the crawler requests a page that requires a logged-in user, the crawler will be redirected to a login page, with the origi...
python
def handle_unexpected_redirect_to_login_page(self, response): """ This method is called if the crawler has been unexpectedly logged out. If that happens, and the crawler requests a page that requires a logged-in user, the crawler will be redirected to a login page, with the origi...
[ "def", "handle_unexpected_redirect_to_login_page", "(", "self", ",", "response", ")", ":", "next_url", "=", "URLObject", "(", "response", ".", "url", ")", ".", "query_dict", ".", "get", "(", "\"next\"", ")", "login_url", "=", "(", "URLObject", "(", "\"http://\...
This method is called if the crawler has been unexpectedly logged out. If that happens, and the crawler requests a page that requires a logged-in user, the crawler will be redirected to a login page, with the originally-requested URL as the `next` query parameter. This method simply cau...
[ "This", "method", "is", "called", "if", "the", "crawler", "has", "been", "unexpectedly", "logged", "out", ".", "If", "that", "happens", "and", "the", "crawler", "requests", "a", "page", "that", "requires", "a", "logged", "-", "in", "user", "the", "crawler"...
train
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L373-L413
jessemiller/HamlPy
hamlpy/elements.py
Element._escape_attribute_quotes
def _escape_attribute_quotes(self, v): ''' Escapes quotes with a backslash, except those inside a Django tag ''' escaped = [] inside_tag = False for i, _ in enumerate(v): if v[i:i + 2] == '{%': inside_tag = True elif v[i:i + 2] == '...
python
def _escape_attribute_quotes(self, v): ''' Escapes quotes with a backslash, except those inside a Django tag ''' escaped = [] inside_tag = False for i, _ in enumerate(v): if v[i:i + 2] == '{%': inside_tag = True elif v[i:i + 2] == '...
[ "def", "_escape_attribute_quotes", "(", "self", ",", "v", ")", ":", "escaped", "=", "[", "]", "inside_tag", "=", "False", "for", "i", ",", "_", "in", "enumerate", "(", "v", ")", ":", "if", "v", "[", "i", ":", "i", "+", "2", "]", "==", "'{%'", "...
Escapes quotes with a backslash, except those inside a Django tag
[ "Escapes", "quotes", "with", "a", "backslash", "except", "those", "inside", "a", "Django", "tag" ]
train
https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/elements.py#L93-L110
jessemiller/HamlPy
hamlpy/nodes.py
RootNode.add_child
def add_child(self, child): '''Add child node, and copy all options to it''' super(RootNode, self).add_child(child) child.attr_wrapper = self.attr_wrapper
python
def add_child(self, child): '''Add child node, and copy all options to it''' super(RootNode, self).add_child(child) child.attr_wrapper = self.attr_wrapper
[ "def", "add_child", "(", "self", ",", "child", ")", ":", "super", "(", "RootNode", ",", "self", ")", ".", "add_child", "(", "child", ")", "child", ".", "attr_wrapper", "=", "self", ".", "attr_wrapper" ]
Add child node, and copy all options to it
[ "Add", "child", "node", "and", "copy", "all", "options", "to", "it" ]
train
https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/nodes.py#L152-L155
jessemiller/HamlPy
hamlpy/nodes.py
ElementNode._render_before
def _render_before(self, element): '''Render opening tag and inline content''' start = ["%s<%s" % (self.spaces, element.tag)] if element.id: start.append(" id=%s" % self.element.attr_wrap(self.replace_inline_variables(element.id))) if element.classes: start.append...
python
def _render_before(self, element): '''Render opening tag and inline content''' start = ["%s<%s" % (self.spaces, element.tag)] if element.id: start.append(" id=%s" % self.element.attr_wrap(self.replace_inline_variables(element.id))) if element.classes: start.append...
[ "def", "_render_before", "(", "self", ",", "element", ")", ":", "start", "=", "[", "\"%s<%s\"", "%", "(", "self", ".", "spaces", ",", "element", ".", "tag", ")", "]", "if", "element", ".", "id", ":", "start", ".", "append", "(", "\" id=%s\"", "%", ...
Render opening tag and inline content
[ "Render", "opening", "tag", "and", "inline", "content" ]
train
https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/nodes.py#L270-L293
jessemiller/HamlPy
hamlpy/nodes.py
ElementNode._render_after
def _render_after(self, element): '''Render closing tag''' if element.inline_content: return "</%s>%s" % (element.tag, self.render_newlines()) elif element.self_close: return self.render_newlines() elif self.children: return "%s</%s>\n" % (self.spaces,...
python
def _render_after(self, element): '''Render closing tag''' if element.inline_content: return "</%s>%s" % (element.tag, self.render_newlines()) elif element.self_close: return self.render_newlines() elif self.children: return "%s</%s>\n" % (self.spaces,...
[ "def", "_render_after", "(", "self", ",", "element", ")", ":", "if", "element", ".", "inline_content", ":", "return", "\"</%s>%s\"", "%", "(", "element", ".", "tag", ",", "self", ".", "render_newlines", "(", ")", ")", "elif", "element", ".", "self_close", ...
Render closing tag
[ "Render", "closing", "tag" ]
train
https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/nodes.py#L295-L304
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.authenticate
def authenticate(self, user, password): """ Method to get simplenote auth token Arguments: - user (string): simplenote email address - password (string): simplenote password Returns: Simplenote API token as string """ reques...
python
def authenticate(self, user, password): """ Method to get simplenote auth token Arguments: - user (string): simplenote email address - password (string): simplenote password Returns: Simplenote API token as string """ reques...
[ "def", "authenticate", "(", "self", ",", "user", ",", "password", ")", ":", "request", "=", "Request", "(", "AUTH_URL", ")", "request", ".", "add_header", "(", "'X-Simperium-API-Key'", ",", "API_KEY", ")", "if", "sys", ".", "version_info", "<", "(", "3", ...
Method to get simplenote auth token Arguments: - user (string): simplenote email address - password (string): simplenote password Returns: Simplenote API token as string
[ "Method", "to", "get", "simplenote", "auth", "token" ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L63-L88
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.get_token
def get_token(self): """ Method to retrieve an auth token. The cached global token is looked up and returned if it exists. If it is `None` a new one is requested and returned. Returns: Simplenote API token as string """ if self.token == None: se...
python
def get_token(self): """ Method to retrieve an auth token. The cached global token is looked up and returned if it exists. If it is `None` a new one is requested and returned. Returns: Simplenote API token as string """ if self.token == None: se...
[ "def", "get_token", "(", "self", ")", ":", "if", "self", ".", "token", "==", "None", ":", "self", ".", "token", "=", "self", ".", "authenticate", "(", "self", ".", "username", ",", "self", ".", "password", ")", "try", ":", "return", "str", "(", "se...
Method to retrieve an auth token. The cached global token is looked up and returned if it exists. If it is `None` a new one is requested and returned. Returns: Simplenote API token as string
[ "Method", "to", "retrieve", "an", "auth", "token", "." ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L90-L105
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.get_note
def get_note(self, noteid, version=None): """ Method to get a specific note Arguments: - noteid (string): ID of the note to get - version (int): optional version of the note to get Returns: A tuple `(note, status)` - note (dict): note object ...
python
def get_note(self, noteid, version=None): """ Method to get a specific note Arguments: - noteid (string): ID of the note to get - version (int): optional version of the note to get Returns: A tuple `(note, status)` - note (dict): note object ...
[ "def", "get_note", "(", "self", ",", "noteid", ",", "version", "=", "None", ")", ":", "# request note", "params_version", "=", "\"\"", "if", "version", "is", "not", "None", ":", "params_version", "=", "'/v/'", "+", "str", "(", "version", ")", "params", "...
Method to get a specific note Arguments: - noteid (string): ID of the note to get - version (int): optional version of the note to get Returns: A tuple `(note, status)` - note (dict): note object - status (int): 0 on success and -1 otherwise
[ "Method", "to", "get", "a", "specific", "note" ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L107-L145
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.update_note
def update_note(self, note): """ Method to update a specific note object, if the note object does not have a "key" field, a new note is created Arguments - note (dict): note object to update Returns: A tuple `(note, status)` - note (dict): note objec...
python
def update_note(self, note): """ Method to update a specific note object, if the note object does not have a "key" field, a new note is created Arguments - note (dict): note object to update Returns: A tuple `(note, status)` - note (dict): note objec...
[ "def", "update_note", "(", "self", ",", "note", ")", ":", "# determine whether to create a new note or update an existing one", "# Also need to add/remove key field to keep simplenote.py consistency", "if", "\"key\"", "in", "note", ":", "# Then already have a noteid we need to remove b...
Method to update a specific note object, if the note object does not have a "key" field, a new note is created Arguments - note (dict): note object to update Returns: A tuple `(note, status)` - note (dict): note object - status (int): 0 on succes...
[ "Method", "to", "update", "a", "specific", "note", "object", "if", "the", "note", "object", "does", "not", "have", "a", "key", "field", "a", "new", "note", "is", "created" ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L147-L196
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.add_note
def add_note(self, note): """ Wrapper method to add a note The method can be passed the note as a dict with the `content` property set, which is then directly send to the web service for creation. Alternatively, only the body as string can also be passed. In this case the parame...
python
def add_note(self, note): """ Wrapper method to add a note The method can be passed the note as a dict with the `content` property set, which is then directly send to the web service for creation. Alternatively, only the body as string can also be passed. In this case the parame...
[ "def", "add_note", "(", "self", ",", "note", ")", ":", "if", "type", "(", "note", ")", "==", "str", ":", "return", "self", ".", "update_note", "(", "{", "\"content\"", ":", "note", "}", ")", "elif", "(", "type", "(", "note", ")", "==", "dict", ")...
Wrapper method to add a note The method can be passed the note as a dict with the `content` property set, which is then directly send to the web service for creation. Alternatively, only the body as string can also be passed. In this case the parameter is used as `content` for the new n...
[ "Wrapper", "method", "to", "add", "a", "note" ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L198-L222
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.get_note_list
def get_note_list(self, data=True, since=None, tags=[]): """ Method to get the note list The method can be passed optional arguments to limit the list to notes containing a certain tag, or only updated since a certain Simperium cursor. If omitted a list of all notes is returned. ...
python
def get_note_list(self, data=True, since=None, tags=[]): """ Method to get the note list The method can be passed optional arguments to limit the list to notes containing a certain tag, or only updated since a certain Simperium cursor. If omitted a list of all notes is returned. ...
[ "def", "get_note_list", "(", "self", ",", "data", "=", "True", ",", "since", "=", "None", ",", "tags", "=", "[", "]", ")", ":", "# initialize data", "status", "=", "0", "ret", "=", "[", "]", "response_notes", "=", "{", "}", "notes", "=", "{", "\"in...
Method to get the note list The method can be passed optional arguments to limit the list to notes containing a certain tag, or only updated since a certain Simperium cursor. If omitted a list of all notes is returned. By default data objects are returned. If data is set to false only ...
[ "Method", "to", "get", "the", "note", "list" ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L224-L319
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.trash_note
def trash_note(self, note_id): """ Method to move a note to the trash Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): the newly created note or an error message - status (int): 0 on succes...
python
def trash_note(self, note_id): """ Method to move a note to the trash Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): the newly created note or an error message - status (int): 0 on succes...
[ "def", "trash_note", "(", "self", ",", "note_id", ")", ":", "# get note", "note", ",", "status", "=", "self", ".", "get_note", "(", "note_id", ")", "if", "(", "status", "==", "-", "1", ")", ":", "return", "note", ",", "status", "# set deleted property, b...
Method to move a note to the trash Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): the newly created note or an error message - status (int): 0 on success and -1 otherwise
[ "Method", "to", "move", "a", "note", "to", "the", "trash" ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L321-L347
mrtazz/simplenote.py
simplenote/simplenote.py
Simplenote.delete_note
def delete_note(self, note_id): """ Method to permanently delete a note Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): an empty dict or an error message - status (int): 0 on success and -...
python
def delete_note(self, note_id): """ Method to permanently delete a note Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): an empty dict or an error message - status (int): 0 on success and -...
[ "def", "delete_note", "(", "self", ",", "note_id", ")", ":", "# notes have to be trashed before deletion", "note", ",", "status", "=", "self", ".", "trash_note", "(", "note_id", ")", "if", "(", "status", "==", "-", "1", ")", ":", "return", "note", ",", "st...
Method to permanently delete a note Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): an empty dict or an error message - status (int): 0 on success and -1 otherwise
[ "Method", "to", "permanently", "delete", "a", "note" ]
train
https://github.com/mrtazz/simplenote.py/blob/19a8c6e5de8db2e5ff9f0a82e86b8a6fb35eac82/simplenote/simplenote.py#L349-L379
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/bearer/authentication.py
BearerAuthentication.authenticate_credentials
def authenticate_credentials(self, token): """ Validate the bearer token against the OAuth provider. Arguments: token (str): Access token to validate Returns: (tuple): tuple containing: user (User): User associated with the access token ...
python
def authenticate_credentials(self, token): """ Validate the bearer token against the OAuth provider. Arguments: token (str): Access token to validate Returns: (tuple): tuple containing: user (User): User associated with the access token ...
[ "def", "authenticate_credentials", "(", "self", ",", "token", ")", ":", "try", ":", "user_info", "=", "self", ".", "get_user_info", "(", "token", ")", "except", "UserInfoRetrievalFailed", ":", "msg", "=", "'Failed to retrieve user info. Unable to authenticate.'", "log...
Validate the bearer token against the OAuth provider. Arguments: token (str): Access token to validate Returns: (tuple): tuple containing: user (User): User associated with the access token access_token (str): Access token Raises: ...
[ "Validate", "the", "bearer", "token", "against", "the", "OAuth", "provider", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/bearer/authentication.py#L54-L83
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/bearer/authentication.py
BearerAuthentication.get_user_info
def get_user_info(self, token): """ Retrieves the user info from the OAuth provider. Arguments: token (str): OAuth2 access token. Returns: dict Raises: UserInfoRetrievalFailed: Retrieval of user info from the remote server failed. ""...
python
def get_user_info(self, token): """ Retrieves the user info from the OAuth provider. Arguments: token (str): OAuth2 access token. Returns: dict Raises: UserInfoRetrievalFailed: Retrieval of user info from the remote server failed. ""...
[ "def", "get_user_info", "(", "self", ",", "token", ")", ":", "url", "=", "self", ".", "get_user_info_url", "(", ")", "try", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "token", ")", "}", "response", "=", "requests...
Retrieves the user info from the OAuth provider. Arguments: token (str): OAuth2 access token. Returns: dict Raises: UserInfoRetrievalFailed: Retrieval of user info from the remote server failed.
[ "Retrieves", "the", "user", "info", "from", "the", "OAuth", "provider", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/bearer/authentication.py#L85-L115
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/bearer/authentication.py
BearerAuthentication.process_user_info_response
def process_user_info_response(self, response): """ Process the user info response data. By default, this simply maps the edX user info key-values (example below) to Django-friendly names. If your provider returns different fields, you should sub-class this class and override this metho...
python
def process_user_info_response(self, response): """ Process the user info response data. By default, this simply maps the edX user info key-values (example below) to Django-friendly names. If your provider returns different fields, you should sub-class this class and override this metho...
[ "def", "process_user_info_response", "(", "self", ",", "response", ")", ":", "mapping", "=", "(", "(", "'username'", ",", "'preferred_username'", ")", ",", "(", "'email'", ",", "'email'", ")", ",", "(", "'last_name'", ",", "'family_name'", ")", ",", "(", "...
Process the user info response data. By default, this simply maps the edX user info key-values (example below) to Django-friendly names. If your provider returns different fields, you should sub-class this class and override this method. .. code-block:: python { "u...
[ "Process", "the", "user", "info", "response", "data", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/bearer/authentication.py#L117-L146
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/authentication.py
JwtAuthentication.authenticate_credentials
def authenticate_credentials(self, payload): """Get or create an active user with the username contained in the payload.""" username = payload.get('preferred_username') or payload.get('username') if username is None: raise exceptions.AuthenticationFailed('JWT must include a preferre...
python
def authenticate_credentials(self, payload): """Get or create an active user with the username contained in the payload.""" username = payload.get('preferred_username') or payload.get('username') if username is None: raise exceptions.AuthenticationFailed('JWT must include a preferre...
[ "def", "authenticate_credentials", "(", "self", ",", "payload", ")", ":", "username", "=", "payload", ".", "get", "(", "'preferred_username'", ")", "or", "payload", ".", "get", "(", "'username'", ")", "if", "username", "is", "None", ":", "raise", "exceptions...
Get or create an active user with the username contained in the payload.
[ "Get", "or", "create", "an", "active", "user", "with", "the", "username", "contained", "in", "the", "payload", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/authentication.py#L51-L75
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/middleware.py
EnsureJWTAuthSettingsMiddleware._includes_base_class
def _includes_base_class(self, iter_classes, base_class): """ Returns whether any class in iter_class is a subclass of the given base_class. """ return any( issubclass(auth_class, base_class) for auth_class in iter_classes, )
python
def _includes_base_class(self, iter_classes, base_class): """ Returns whether any class in iter_class is a subclass of the given base_class. """ return any( issubclass(auth_class, base_class) for auth_class in iter_classes, )
[ "def", "_includes_base_class", "(", "self", ",", "iter_classes", ",", "base_class", ")", ":", "return", "any", "(", "issubclass", "(", "auth_class", ",", "base_class", ")", "for", "auth_class", "in", "iter_classes", ",", ")" ]
Returns whether any class in iter_class is a subclass of the given base_class.
[ "Returns", "whether", "any", "class", "in", "iter_class", "is", "a", "subclass", "of", "the", "given", "base_class", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/middleware.py#L28-L34
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/middleware.py
EnsureJWTAuthSettingsMiddleware._add_missing_jwt_permission_classes
def _add_missing_jwt_permission_classes(self, view_class): """ Adds permissions classes that should exist for Jwt based authentication, if needed. """ view_permissions = list(getattr(view_class, 'permission_classes', [])) # Not all permissions are classes, some will be C...
python
def _add_missing_jwt_permission_classes(self, view_class): """ Adds permissions classes that should exist for Jwt based authentication, if needed. """ view_permissions = list(getattr(view_class, 'permission_classes', [])) # Not all permissions are classes, some will be C...
[ "def", "_add_missing_jwt_permission_classes", "(", "self", ",", "view_class", ")", ":", "view_permissions", "=", "list", "(", "getattr", "(", "view_class", ",", "'permission_classes'", ",", "[", "]", ")", ")", "# Not all permissions are classes, some will be ConditionalPe...
Adds permissions classes that should exist for Jwt based authentication, if needed.
[ "Adds", "permissions", "classes", "that", "should", "exist", "for", "Jwt", "based", "authentication", "if", "needed", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/middleware.py#L36-L67
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/middleware.py
JwtAuthCookieMiddleware._get_missing_cookie_message_and_metric
def _get_missing_cookie_message_and_metric(self, cookie_name): """ Returns tuple with missing cookie (log_message, metric_value) """ cookie_missing_message = '{} cookie is missing. JWT auth cookies will not be reconstituted.'.format( cookie_name ) request_jwt_cookie = 'mi...
python
def _get_missing_cookie_message_and_metric(self, cookie_name): """ Returns tuple with missing cookie (log_message, metric_value) """ cookie_missing_message = '{} cookie is missing. JWT auth cookies will not be reconstituted.'.format( cookie_name ) request_jwt_cookie = 'mi...
[ "def", "_get_missing_cookie_message_and_metric", "(", "self", ",", "cookie_name", ")", ":", "cookie_missing_message", "=", "'{} cookie is missing. JWT auth cookies will not be reconstituted.'", ".", "format", "(", "cookie_name", ")", "request_jwt_cookie", "=", "'missing-{}'", "...
Returns tuple with missing cookie (log_message, metric_value)
[ "Returns", "tuple", "with", "missing", "cookie", "(", "log_message", "metric_value", ")" ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/middleware.py#L112-L118
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/middleware.py
JwtAuthCookieMiddleware.process_request
def process_request(self, request): """ Reconstitute the full JWT and add a new cookie on the request object. """ use_jwt_cookie_requested = request.META.get(USE_JWT_COOKIE_HEADER) header_payload_cookie = request.COOKIES.get(jwt_cookie_header_payload_name()) signature_coo...
python
def process_request(self, request): """ Reconstitute the full JWT and add a new cookie on the request object. """ use_jwt_cookie_requested = request.META.get(USE_JWT_COOKIE_HEADER) header_payload_cookie = request.COOKIES.get(jwt_cookie_header_payload_name()) signature_coo...
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "use_jwt_cookie_requested", "=", "request", ".", "META", ".", "get", "(", "USE_JWT_COOKIE_HEADER", ")", "header_payload_cookie", "=", "request", ".", "COOKIES", ".", "get", "(", "jwt_cookie_header_pa...
Reconstitute the full JWT and add a new cookie on the request object.
[ "Reconstitute", "the", "full", "JWT", "and", "add", "a", "new", "cookie", "on", "the", "request", "object", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/middleware.py#L120-L153
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/decoder.py
jwt_decode_handler
def jwt_decode_handler(token): """ Decodes a JSON Web Token (JWT). Notes: * Requires "exp" and "iat" claims to be present in the token's payload. * Aids debugging by logging InvalidTokenError log entries when decoding fails. Examples: Use with `djangorestframework-jwt <https://...
python
def jwt_decode_handler(token): """ Decodes a JSON Web Token (JWT). Notes: * Requires "exp" and "iat" claims to be present in the token's payload. * Aids debugging by logging InvalidTokenError log entries when decoding fails. Examples: Use with `djangorestframework-jwt <https://...
[ "def", "jwt_decode_handler", "(", "token", ")", ":", "jwt_issuer", "=", "get_first_jwt_issuer", "(", ")", "_verify_jwt_signature", "(", "token", ",", "jwt_issuer", ")", "decoded_token", "=", "_decode_and_verify_token", "(", "token", ",", "jwt_issuer", ")", "return",...
Decodes a JSON Web Token (JWT). Notes: * Requires "exp" and "iat" claims to be present in the token's payload. * Aids debugging by logging InvalidTokenError log entries when decoding fails. Examples: Use with `djangorestframework-jwt <https://getblimp.github.io/django-rest-framework-jw...
[ "Decodes", "a", "JSON", "Web", "Token", "(", "JWT", ")", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/decoder.py#L24-L59
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/decoder.py
_set_token_defaults
def _set_token_defaults(token): """ Returns an updated token that includes default values for fields that were introduced since the token was created by checking its version number. """ def _verify_version(jwt_version): supported_version = Version( settings.JWT_AUTH.get('JWT_...
python
def _set_token_defaults(token): """ Returns an updated token that includes default values for fields that were introduced since the token was created by checking its version number. """ def _verify_version(jwt_version): supported_version = Version( settings.JWT_AUTH.get('JWT_...
[ "def", "_set_token_defaults", "(", "token", ")", ":", "def", "_verify_version", "(", "jwt_version", ")", ":", "supported_version", "=", "Version", "(", "settings", ".", "JWT_AUTH", ".", "get", "(", "'JWT_SUPPORTED_VERSION'", ",", "JwtTokenVersion", ".", "default_l...
Returns an updated token that includes default values for fields that were introduced since the token was created by checking its version number.
[ "Returns", "an", "updated", "token", "that", "includes", "default", "values", "for", "fields", "that", "were", "introduced", "since", "the", "token", "was", "created", "by", "checking", "its", "version", "number", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/decoder.py#L84-L133
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/decoder.py
_get_signing_jwk_key_set
def _get_signing_jwk_key_set(jwt_issuer): """ Returns a JWK Keyset containing all active keys that are configured for verifying signatures. """ key_set = KEYS() # asymmetric keys signing_jwk_set = settings.JWT_AUTH.get('JWT_PUBLIC_SIGNING_JWK_SET') if signing_jwk_set: key_set.lo...
python
def _get_signing_jwk_key_set(jwt_issuer): """ Returns a JWK Keyset containing all active keys that are configured for verifying signatures. """ key_set = KEYS() # asymmetric keys signing_jwk_set = settings.JWT_AUTH.get('JWT_PUBLIC_SIGNING_JWK_SET') if signing_jwk_set: key_set.lo...
[ "def", "_get_signing_jwk_key_set", "(", "jwt_issuer", ")", ":", "key_set", "=", "KEYS", "(", ")", "# asymmetric keys", "signing_jwk_set", "=", "settings", ".", "JWT_AUTH", ".", "get", "(", "'JWT_PUBLIC_SIGNING_JWK_SET'", ")", "if", "signing_jwk_set", ":", "key_set",...
Returns a JWK Keyset containing all active keys that are configured for verifying signatures.
[ "Returns", "a", "JWK", "Keyset", "containing", "all", "active", "keys", "that", "are", "configured", "for", "verifying", "signatures", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/decoder.py#L179-L194
edx/edx-drf-extensions
edx_rest_framework_extensions/paginators.py
paginate_search_results
def paginate_search_results(object_class, search_results, page_size, page): """ Takes edx-search results and returns a Page object populated with db objects for that page. :param object_class: Model class to use when querying the db for objects. :param search_results: edX-search results. :param...
python
def paginate_search_results(object_class, search_results, page_size, page): """ Takes edx-search results and returns a Page object populated with db objects for that page. :param object_class: Model class to use when querying the db for objects. :param search_results: edX-search results. :param...
[ "def", "paginate_search_results", "(", "object_class", ",", "search_results", ",", "page_size", ",", "page", ")", ":", "paginator", "=", "Paginator", "(", "search_results", "[", "'results'", "]", ",", "page_size", ")", "# This code is taken from within the GenericAPIVie...
Takes edx-search results and returns a Page object populated with db objects for that page. :param object_class: Model class to use when querying the db for objects. :param search_results: edX-search results. :param page_size: Number of results per page. :param page: Page number. :return: Pagin...
[ "Takes", "edx", "-", "search", "results", "and", "returns", "a", "Page", "object", "populated", "with", "db", "objects", "for", "that", "page", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/paginators.py#L79-L125
edx/edx-drf-extensions
edx_rest_framework_extensions/paginators.py
DefaultPagination.get_paginated_response
def get_paginated_response(self, data): """ Annotate the response with pagination information. """ return Response({ 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'num_pages': self.p...
python
def get_paginated_response(self, data): """ Annotate the response with pagination information. """ return Response({ 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'num_pages': self.p...
[ "def", "get_paginated_response", "(", "self", ",", "data", ")", ":", "return", "Response", "(", "{", "'next'", ":", "self", ".", "get_next_link", "(", ")", ",", "'previous'", ":", "self", ".", "get_previous_link", "(", ")", ",", "'count'", ":", "self", "...
Annotate the response with pagination information.
[ "Annotate", "the", "response", "with", "pagination", "information", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/paginators.py#L20-L32
edx/edx-drf-extensions
edx_rest_framework_extensions/paginators.py
NamespacedPageNumberPagination.get_paginated_response
def get_paginated_response(self, data): """ Annotate the response with pagination information """ metadata = { 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.get_result_count(), 'num_pages': self.get_num_p...
python
def get_paginated_response(self, data): """ Annotate the response with pagination information """ metadata = { 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.get_result_count(), 'num_pages': self.get_num_p...
[ "def", "get_paginated_response", "(", "self", ",", "data", ")", ":", "metadata", "=", "{", "'next'", ":", "self", ".", "get_next_link", "(", ")", ",", "'previous'", ":", "self", ".", "get_previous_link", "(", ")", ",", "'count'", ":", "self", ".", "get_r...
Annotate the response with pagination information
[ "Annotate", "the", "response", "with", "pagination", "information" ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/paginators.py#L57-L76
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/jwt/cookies.py
get_decoded_jwt
def get_decoded_jwt(request): """ Grab jwt from jwt cookie in request if possible. Returns a decoded jwt dict if it can be found. Returns None if the jwt is not found. """ jwt_cookie = request.COOKIES.get(jwt_cookie_name(), None) if not jwt_cookie: return None return jwt_decode...
python
def get_decoded_jwt(request): """ Grab jwt from jwt cookie in request if possible. Returns a decoded jwt dict if it can be found. Returns None if the jwt is not found. """ jwt_cookie = request.COOKIES.get(jwt_cookie_name(), None) if not jwt_cookie: return None return jwt_decode...
[ "def", "get_decoded_jwt", "(", "request", ")", ":", "jwt_cookie", "=", "request", ".", "COOKIES", ".", "get", "(", "jwt_cookie_name", "(", ")", ",", "None", ")", "if", "not", "jwt_cookie", ":", "return", "None", "return", "jwt_decode_handler", "(", "jwt_cook...
Grab jwt from jwt cookie in request if possible. Returns a decoded jwt dict if it can be found. Returns None if the jwt is not found.
[ "Grab", "jwt", "from", "jwt", "cookie", "in", "request", "if", "possible", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/cookies.py#L25-L36
edx/edx-drf-extensions
edx_rest_framework_extensions/auth/session/authentication.py
SessionAuthenticationAllowInactiveUser.authenticate
def authenticate(self, request): """Authenticate the user, requiring a logged-in account and CSRF. This is exactly the same as the `SessionAuthentication` implementation, with the `user.is_active` check removed. Args: request (HttpRequest) Returns: Tupl...
python
def authenticate(self, request): """Authenticate the user, requiring a logged-in account and CSRF. This is exactly the same as the `SessionAuthentication` implementation, with the `user.is_active` check removed. Args: request (HttpRequest) Returns: Tupl...
[ "def", "authenticate", "(", "self", ",", "request", ")", ":", "# Get the underlying HttpRequest object", "request", "=", "request", ".", "_request", "# pylint: disable=protected-access", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "# Una...
Authenticate the user, requiring a logged-in account and CSRF. This is exactly the same as the `SessionAuthentication` implementation, with the `user.is_active` check removed. Args: request (HttpRequest) Returns: Tuple of `(user, token)` Raises: ...
[ "Authenticate", "the", "user", "requiring", "a", "logged", "-", "in", "account", "and", "CSRF", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/session/authentication.py#L20-L50
edx/edx-drf-extensions
edx_rest_framework_extensions/permissions.py
JwtHasContentOrgFilterForRequestedCourse.has_permission
def has_permission(self, request, view): """ Ensure that the course_id kwarg provided to the view contains one of the organizations specified in the content provider filters in the JWT used to authenticate. """ course_key = CourseKey.from_string(view.kwargs.get('course_id...
python
def has_permission(self, request, view): """ Ensure that the course_id kwarg provided to the view contains one of the organizations specified in the content provider filters in the JWT used to authenticate. """ course_key = CourseKey.from_string(view.kwargs.get('course_id...
[ "def", "has_permission", "(", "self", ",", "request", ",", "view", ")", ":", "course_key", "=", "CourseKey", ".", "from_string", "(", "view", ".", "kwargs", ".", "get", "(", "'course_id'", ")", ")", "jwt_filters", "=", "decode_jwt_filters", "(", "request", ...
Ensure that the course_id kwarg provided to the view contains one of the organizations specified in the content provider filters in the JWT used to authenticate.
[ "Ensure", "that", "the", "course_id", "kwarg", "provided", "to", "the", "view", "contains", "one", "of", "the", "organizations", "specified", "in", "the", "content", "provider", "filters", "in", "the", "JWT", "used", "to", "authenticate", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/permissions.py#L92-L107
edx/edx-drf-extensions
edx_rest_framework_extensions/permissions.py
JwtHasUserFilterForRequestedUser.has_permission
def has_permission(self, request, view): """ If the JWT has a user filter, verify that the filtered user value matches the user in the URL. """ user_filter = self._get_user_filter(request) if not user_filter: # no user filters are present in the token to limit...
python
def has_permission(self, request, view): """ If the JWT has a user filter, verify that the filtered user value matches the user in the URL. """ user_filter = self._get_user_filter(request) if not user_filter: # no user filters are present in the token to limit...
[ "def", "has_permission", "(", "self", ",", "request", ",", "view", ")", ":", "user_filter", "=", "self", ".", "_get_user_filter", "(", "request", ")", "if", "not", "user_filter", ":", "# no user filters are present in the token to limit access", "return", "True", "u...
If the JWT has a user filter, verify that the filtered user value matches the user in the URL.
[ "If", "the", "JWT", "has", "a", "user", "filter", "verify", "that", "the", "filtered", "user", "value", "matches", "the", "user", "in", "the", "URL", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/permissions.py#L117-L135
edx/edx-drf-extensions
edx_rest_framework_extensions/settings.py
_get_deprecated_jwt_issuers
def _get_deprecated_jwt_issuers(): """ Internal helper to retrieve the deprecated set of JWT_ISSUER data from the JWT_AUTH configuration Having this allows for easier testing/mocking """ # If JWT_ISSUERS is not defined, attempt to return the deprecated settings. warnings.warn( "'JWT_ISSU...
python
def _get_deprecated_jwt_issuers(): """ Internal helper to retrieve the deprecated set of JWT_ISSUER data from the JWT_AUTH configuration Having this allows for easier testing/mocking """ # If JWT_ISSUERS is not defined, attempt to return the deprecated settings. warnings.warn( "'JWT_ISSU...
[ "def", "_get_deprecated_jwt_issuers", "(", ")", ":", "# If JWT_ISSUERS is not defined, attempt to return the deprecated settings.", "warnings", ".", "warn", "(", "\"'JWT_ISSUERS' list not defined, checking for deprecated settings.\"", ",", "DeprecationWarning", ")", "return", "[", "{...
Internal helper to retrieve the deprecated set of JWT_ISSUER data from the JWT_AUTH configuration Having this allows for easier testing/mocking
[ "Internal", "helper", "to", "retrieve", "the", "deprecated", "set", "of", "JWT_ISSUER", "data", "from", "the", "JWT_AUTH", "configuration", "Having", "this", "allows", "for", "easier", "testing", "/", "mocking" ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/settings.py#L56-L73
edx/edx-drf-extensions
edx_rest_framework_extensions/middleware.py
RequestMetricsMiddleware.process_response
def process_response(self, request, response): """ Add metrics for various details of the request. """ self._set_request_auth_type_metric(request) self._set_request_user_agent_metrics(request) self._set_request_referer_metric(request) self._set_request_user_id_met...
python
def process_response(self, request, response): """ Add metrics for various details of the request. """ self._set_request_auth_type_metric(request) self._set_request_user_agent_metrics(request) self._set_request_referer_metric(request) self._set_request_user_id_met...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "self", ".", "_set_request_auth_type_metric", "(", "request", ")", "self", ".", "_set_request_user_agent_metrics", "(", "request", ")", "self", ".", "_set_request_referer_metric", "("...
Add metrics for various details of the request.
[ "Add", "metrics", "for", "various", "details", "of", "the", "request", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/middleware.py#L31-L40
edx/edx-drf-extensions
edx_rest_framework_extensions/middleware.py
RequestMetricsMiddleware._set_request_user_id_metric
def _set_request_user_id_metric(self, request): """ Add request_user_id metric Metrics: request_user_id """ if hasattr(request, 'user') and hasattr(request.user, 'id') and request.user.id: monitoring.set_custom_metric('request_user_id', request.user.id)
python
def _set_request_user_id_metric(self, request): """ Add request_user_id metric Metrics: request_user_id """ if hasattr(request, 'user') and hasattr(request.user, 'id') and request.user.id: monitoring.set_custom_metric('request_user_id', request.user.id)
[ "def", "_set_request_user_id_metric", "(", "self", ",", "request", ")", ":", "if", "hasattr", "(", "request", ",", "'user'", ")", "and", "hasattr", "(", "request", ".", "user", ",", "'id'", ")", "and", "request", ".", "user", ".", "id", ":", "monitoring"...
Add request_user_id metric Metrics: request_user_id
[ "Add", "request_user_id", "metric" ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/middleware.py#L42-L50
edx/edx-drf-extensions
edx_rest_framework_extensions/middleware.py
RequestMetricsMiddleware._set_request_referer_metric
def _set_request_referer_metric(self, request): """ Add metric 'request_referer' for http referer. """ if 'HTTP_REFERER' in request.META and request.META['HTTP_REFERER']: monitoring.set_custom_metric('request_referer', request.META['HTTP_REFERER'])
python
def _set_request_referer_metric(self, request): """ Add metric 'request_referer' for http referer. """ if 'HTTP_REFERER' in request.META and request.META['HTTP_REFERER']: monitoring.set_custom_metric('request_referer', request.META['HTTP_REFERER'])
[ "def", "_set_request_referer_metric", "(", "self", ",", "request", ")", ":", "if", "'HTTP_REFERER'", "in", "request", ".", "META", "and", "request", ".", "META", "[", "'HTTP_REFERER'", "]", ":", "monitoring", ".", "set_custom_metric", "(", "'request_referer'", "...
Add metric 'request_referer' for http referer.
[ "Add", "metric", "request_referer", "for", "http", "referer", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/middleware.py#L52-L57
edx/edx-drf-extensions
edx_rest_framework_extensions/middleware.py
RequestMetricsMiddleware._set_request_user_agent_metrics
def _set_request_user_agent_metrics(self, request): """ Add metrics for user agent for python. Metrics: request_user_agent request_client_name: The client name from edx-rest-api-client calls. """ if 'HTTP_USER_AGENT' in request.META and request.META['HT...
python
def _set_request_user_agent_metrics(self, request): """ Add metrics for user agent for python. Metrics: request_user_agent request_client_name: The client name from edx-rest-api-client calls. """ if 'HTTP_USER_AGENT' in request.META and request.META['HT...
[ "def", "_set_request_user_agent_metrics", "(", "self", ",", "request", ")", ":", "if", "'HTTP_USER_AGENT'", "in", "request", ".", "META", "and", "request", ".", "META", "[", "'HTTP_USER_AGENT'", "]", ":", "user_agent", "=", "request", ".", "META", "[", "'HTTP_...
Add metrics for user agent for python. Metrics: request_user_agent request_client_name: The client name from edx-rest-api-client calls.
[ "Add", "metrics", "for", "user", "agent", "for", "python", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/middleware.py#L59-L76
edx/edx-drf-extensions
edx_rest_framework_extensions/middleware.py
RequestMetricsMiddleware._set_request_auth_type_metric
def _set_request_auth_type_metric(self, request): """ Add metric 'request_auth_type' for the authentication type used. NOTE: This is a best guess at this point. Possible values include: no-user unauthenticated jwt/bearer/other-token-type session-...
python
def _set_request_auth_type_metric(self, request): """ Add metric 'request_auth_type' for the authentication type used. NOTE: This is a best guess at this point. Possible values include: no-user unauthenticated jwt/bearer/other-token-type session-...
[ "def", "_set_request_auth_type_metric", "(", "self", ",", "request", ")", ":", "if", "'HTTP_AUTHORIZATION'", "in", "request", ".", "META", "and", "request", ".", "META", "[", "'HTTP_AUTHORIZATION'", "]", ":", "token_parts", "=", "request", ".", "META", "[", "'...
Add metric 'request_auth_type' for the authentication type used. NOTE: This is a best guess at this point. Possible values include: no-user unauthenticated jwt/bearer/other-token-type session-or-unknown (catch all)
[ "Add", "metric", "request_auth_type", "for", "the", "authentication", "type", "used", "." ]
train
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/middleware.py#L78-L102
happyleavesaoc/python-snapcast
snapcast/control/protocol.py
jsonrpc_request
def jsonrpc_request(method, identifier, params=None): """Produce a JSONRPC request.""" return '{}\r\n'.format(json.dumps({ 'id': identifier, 'method': method, 'params': params or {}, 'jsonrpc': '2.0' })).encode()
python
def jsonrpc_request(method, identifier, params=None): """Produce a JSONRPC request.""" return '{}\r\n'.format(json.dumps({ 'id': identifier, 'method': method, 'params': params or {}, 'jsonrpc': '2.0' })).encode()
[ "def", "jsonrpc_request", "(", "method", ",", "identifier", ",", "params", "=", "None", ")", ":", "return", "'{}\\r\\n'", ".", "format", "(", "json", ".", "dumps", "(", "{", "'id'", ":", "identifier", ",", "'method'", ":", "method", ",", "'params'", ":",...
Produce a JSONRPC request.
[ "Produce", "a", "JSONRPC", "request", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/protocol.py#L10-L17
happyleavesaoc/python-snapcast
snapcast/control/protocol.py
SnapcastProtocol.data_received
def data_received(self, data): """Handle received data.""" self._data_buffer += data.decode() if not self._data_buffer.endswith('\r\n'): return data = self._data_buffer self._data_buffer = '' # clear buffer for cmd in data.strip().split('\r\n'): d...
python
def data_received(self, data): """Handle received data.""" self._data_buffer += data.decode() if not self._data_buffer.endswith('\r\n'): return data = self._data_buffer self._data_buffer = '' # clear buffer for cmd in data.strip().split('\r\n'): d...
[ "def", "data_received", "(", "self", ",", "data", ")", ":", "self", ".", "_data_buffer", "+=", "data", ".", "decode", "(", ")", "if", "not", "self", ".", "_data_buffer", ".", "endswith", "(", "'\\r\\n'", ")", ":", "return", "data", "=", "self", ".", ...
Handle received data.
[ "Handle", "received", "data", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/protocol.py#L38-L50
happyleavesaoc/python-snapcast
snapcast/control/protocol.py
SnapcastProtocol.handle_data
def handle_data(self, data): """Handle JSONRPC data.""" if 'id' in data: self.handle_response(data) else: self.handle_notification(data)
python
def handle_data(self, data): """Handle JSONRPC data.""" if 'id' in data: self.handle_response(data) else: self.handle_notification(data)
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "if", "'id'", "in", "data", ":", "self", ".", "handle_response", "(", "data", ")", "else", ":", "self", ".", "handle_notification", "(", "data", ")" ]
Handle JSONRPC data.
[ "Handle", "JSONRPC", "data", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/protocol.py#L52-L57
happyleavesaoc/python-snapcast
snapcast/control/protocol.py
SnapcastProtocol.handle_response
def handle_response(self, data): """Handle JSONRPC response.""" identifier = data.get('id') self._buffer[identifier]['data'] = data.get('result') self._buffer[identifier]['flag'].set()
python
def handle_response(self, data): """Handle JSONRPC response.""" identifier = data.get('id') self._buffer[identifier]['data'] = data.get('result') self._buffer[identifier]['flag'].set()
[ "def", "handle_response", "(", "self", ",", "data", ")", ":", "identifier", "=", "data", ".", "get", "(", "'id'", ")", "self", ".", "_buffer", "[", "identifier", "]", "[", "'data'", "]", "=", "data", ".", "get", "(", "'result'", ")", "self", ".", "...
Handle JSONRPC response.
[ "Handle", "JSONRPC", "response", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/protocol.py#L59-L63
happyleavesaoc/python-snapcast
snapcast/control/protocol.py
SnapcastProtocol.handle_notification
def handle_notification(self, data): """Handle JSONRPC notification.""" if data.get('method') in self._callbacks: self._callbacks.get(data.get('method'))(data.get('params'))
python
def handle_notification(self, data): """Handle JSONRPC notification.""" if data.get('method') in self._callbacks: self._callbacks.get(data.get('method'))(data.get('params'))
[ "def", "handle_notification", "(", "self", ",", "data", ")", ":", "if", "data", ".", "get", "(", "'method'", ")", "in", "self", ".", "_callbacks", ":", "self", ".", "_callbacks", ".", "get", "(", "data", ".", "get", "(", "'method'", ")", ")", "(", ...
Handle JSONRPC notification.
[ "Handle", "JSONRPC", "notification", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/protocol.py#L65-L68
happyleavesaoc/python-snapcast
snapcast/control/protocol.py
SnapcastProtocol.request
def request(self, method, params): """Send a JSONRPC request.""" identifier = random.randint(1, 1000) self._transport.write(jsonrpc_request(method, identifier, params)) self._buffer[identifier] = {'flag': asyncio.Event()} yield from self._buffer[identifier]['flag'].wait() ...
python
def request(self, method, params): """Send a JSONRPC request.""" identifier = random.randint(1, 1000) self._transport.write(jsonrpc_request(method, identifier, params)) self._buffer[identifier] = {'flag': asyncio.Event()} yield from self._buffer[identifier]['flag'].wait() ...
[ "def", "request", "(", "self", ",", "method", ",", "params", ")", ":", "identifier", "=", "random", ".", "randint", "(", "1", ",", "1000", ")", "self", ".", "_transport", ".", "write", "(", "jsonrpc_request", "(", "method", ",", "identifier", ",", "par...
Send a JSONRPC request.
[ "Send", "a", "JSONRPC", "request", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/protocol.py#L71-L79
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver.start
def start(self): """Initiate server connection.""" yield from self._do_connect() _LOGGER.info('connected to snapserver on %s:%s', self._host, self._port) status = yield from self.status() self.synchronize(status) self._on_server_connect()
python
def start(self): """Initiate server connection.""" yield from self._do_connect() _LOGGER.info('connected to snapserver on %s:%s', self._host, self._port) status = yield from self.status() self.synchronize(status) self._on_server_connect()
[ "def", "start", "(", "self", ")", ":", "yield", "from", "self", ".", "_do_connect", "(", ")", "_LOGGER", ".", "info", "(", "'connected to snapserver on %s:%s'", ",", "self", ".", "_host", ",", "self", ".", "_port", ")", "status", "=", "yield", "from", "s...
Initiate server connection.
[ "Initiate", "server", "connection", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L84-L90
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._do_connect
def _do_connect(self): """Perform the connection to the server.""" _, self._protocol = yield from self._loop.create_connection( lambda: SnapcastProtocol(self._callbacks), self._host, self._port)
python
def _do_connect(self): """Perform the connection to the server.""" _, self._protocol = yield from self._loop.create_connection( lambda: SnapcastProtocol(self._callbacks), self._host, self._port)
[ "def", "_do_connect", "(", "self", ")", ":", "_", ",", "self", ".", "_protocol", "=", "yield", "from", "self", ".", "_loop", ".", "create_connection", "(", "lambda", ":", "SnapcastProtocol", "(", "self", ".", "_callbacks", ")", ",", "self", ".", "_host",...
Perform the connection to the server.
[ "Perform", "the", "connection", "to", "the", "server", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L93-L96
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._reconnect_cb
def _reconnect_cb(self): """Callback to reconnect to the server.""" @asyncio.coroutine def try_reconnect(): """Actual coroutine ro try to reconnect or reschedule.""" try: yield from self._do_connect() except IOError: self._loop....
python
def _reconnect_cb(self): """Callback to reconnect to the server.""" @asyncio.coroutine def try_reconnect(): """Actual coroutine ro try to reconnect or reschedule.""" try: yield from self._do_connect() except IOError: self._loop....
[ "def", "_reconnect_cb", "(", "self", ")", ":", "@", "asyncio", ".", "coroutine", "def", "try_reconnect", "(", ")", ":", "\"\"\"Actual coroutine ro try to reconnect or reschedule.\"\"\"", "try", ":", "yield", "from", "self", ".", "_do_connect", "(", ")", "except", ...
Callback to reconnect to the server.
[ "Callback", "to", "reconnect", "to", "the", "server", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L98-L108
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._transact
def _transact(self, method, params=None): """Wrap requests.""" result = yield from self._protocol.request(method, params) return result
python
def _transact(self, method, params=None): """Wrap requests.""" result = yield from self._protocol.request(method, params) return result
[ "def", "_transact", "(", "self", ",", "method", ",", "params", "=", "None", ")", ":", "result", "=", "yield", "from", "self", ".", "_protocol", ".", "request", "(", "method", ",", "params", ")", "return", "result" ]
Wrap requests.
[ "Wrap", "requests", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L111-L114
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver.delete_client
def delete_client(self, identifier): """Delete client.""" params = {'id': identifier} response = yield from self._transact(SERVER_DELETECLIENT, params) self.synchronize(response)
python
def delete_client(self, identifier): """Delete client.""" params = {'id': identifier} response = yield from self._transact(SERVER_DELETECLIENT, params) self.synchronize(response)
[ "def", "delete_client", "(", "self", ",", "identifier", ")", ":", "params", "=", "{", "'id'", ":", "identifier", "}", "response", "=", "yield", "from", "self", ".", "_transact", "(", "SERVER_DELETECLIENT", ",", "params", ")", "self", ".", "synchronize", "(...
Delete client.
[ "Delete", "client", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L132-L136
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver.synchronize
def synchronize(self, status): """Synchronize snapserver.""" self._version = status.get('server').get('version') self._groups = {} self._clients = {} self._streams = {} for stream in status.get('server').get('streams'): self._streams[stream.get('id')] = Snapst...
python
def synchronize(self, status): """Synchronize snapserver.""" self._version = status.get('server').get('version') self._groups = {} self._clients = {} self._streams = {} for stream in status.get('server').get('streams'): self._streams[stream.get('id')] = Snapst...
[ "def", "synchronize", "(", "self", ",", "status", ")", ":", "self", ".", "_version", "=", "status", ".", "get", "(", "'server'", ")", ".", "get", "(", "'version'", ")", "self", ".", "_groups", "=", "{", "}", "self", ".", "_clients", "=", "{", "}", ...
Synchronize snapserver.
[ "Synchronize", "snapserver", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L197-L211
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._request
def _request(self, method, identifier, key=None, value=None): """Perform request with identifier.""" params = {'id': identifier} if key is not None and value is not None: params[key] = value result = yield from self._transact(method, params) return result.get(key)
python
def _request(self, method, identifier, key=None, value=None): """Perform request with identifier.""" params = {'id': identifier} if key is not None and value is not None: params[key] = value result = yield from self._transact(method, params) return result.get(key)
[ "def", "_request", "(", "self", ",", "method", ",", "identifier", ",", "key", "=", "None", ",", "value", "=", "None", ")", ":", "params", "=", "{", "'id'", ":", "identifier", "}", "if", "key", "is", "not", "None", "and", "value", "is", "not", "None...
Perform request with identifier.
[ "Perform", "request", "with", "identifier", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L214-L220
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_server_disconnect
def _on_server_disconnect(self, exception): """Handle server disconnection.""" self._protocol = None if self._on_disconnect_callback_func and callable(self._on_disconnect_callback_func): self._on_disconnect_callback_func(exception) if self._reconnect: self._reconn...
python
def _on_server_disconnect(self, exception): """Handle server disconnection.""" self._protocol = None if self._on_disconnect_callback_func and callable(self._on_disconnect_callback_func): self._on_disconnect_callback_func(exception) if self._reconnect: self._reconn...
[ "def", "_on_server_disconnect", "(", "self", ",", "exception", ")", ":", "self", ".", "_protocol", "=", "None", "if", "self", ".", "_on_disconnect_callback_func", "and", "callable", "(", "self", ".", "_on_disconnect_callback_func", ")", ":", "self", ".", "_on_di...
Handle server disconnection.
[ "Handle", "server", "disconnection", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L227-L233
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_group_mute
def _on_group_mute(self, data): """Handle group mute.""" self._groups.get(data.get('id')).update_mute(data)
python
def _on_group_mute(self, data): """Handle group mute.""" self._groups.get(data.get('id')).update_mute(data)
[ "def", "_on_group_mute", "(", "self", ",", "data", ")", ":", "self", ".", "_groups", ".", "get", "(", "data", ".", "get", "(", "'id'", ")", ")", ".", "update_mute", "(", "data", ")" ]
Handle group mute.
[ "Handle", "group", "mute", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L239-L241
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_group_stream_changed
def _on_group_stream_changed(self, data): """Handle group stream change.""" self._groups.get(data.get('id')).update_stream(data)
python
def _on_group_stream_changed(self, data): """Handle group stream change.""" self._groups.get(data.get('id')).update_stream(data)
[ "def", "_on_group_stream_changed", "(", "self", ",", "data", ")", ":", "self", ".", "_groups", ".", "get", "(", "data", ".", "get", "(", "'id'", ")", ")", ".", "update_stream", "(", "data", ")" ]
Handle group stream change.
[ "Handle", "group", "stream", "change", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L243-L245
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_client_connect
def _on_client_connect(self, data): """Handle client connect.""" client = None if data.get('id') in self._clients: client = self._clients[data.get('id')] client.update_connected(True) else: client = Snapclient(self, data.get('client')) self...
python
def _on_client_connect(self, data): """Handle client connect.""" client = None if data.get('id') in self._clients: client = self._clients[data.get('id')] client.update_connected(True) else: client = Snapclient(self, data.get('client')) self...
[ "def", "_on_client_connect", "(", "self", ",", "data", ")", ":", "client", "=", "None", "if", "data", ".", "get", "(", "'id'", ")", "in", "self", ".", "_clients", ":", "client", "=", "self", ".", "_clients", "[", "data", ".", "get", "(", "'id'", ")...
Handle client connect.
[ "Handle", "client", "connect", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L247-L258
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_client_disconnect
def _on_client_disconnect(self, data): """Handle client disconnect.""" self._clients[data.get('id')].update_connected(False) _LOGGER.info('client %s disconnected', self._clients[data.get('id')].friendly_name)
python
def _on_client_disconnect(self, data): """Handle client disconnect.""" self._clients[data.get('id')].update_connected(False) _LOGGER.info('client %s disconnected', self._clients[data.get('id')].friendly_name)
[ "def", "_on_client_disconnect", "(", "self", ",", "data", ")", ":", "self", ".", "_clients", "[", "data", ".", "get", "(", "'id'", ")", "]", ".", "update_connected", "(", "False", ")", "_LOGGER", ".", "info", "(", "'client %s disconnected'", ",", "self", ...
Handle client disconnect.
[ "Handle", "client", "disconnect", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L260-L263
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_client_volume_changed
def _on_client_volume_changed(self, data): """Handle client volume change.""" self._clients.get(data.get('id')).update_volume(data)
python
def _on_client_volume_changed(self, data): """Handle client volume change.""" self._clients.get(data.get('id')).update_volume(data)
[ "def", "_on_client_volume_changed", "(", "self", ",", "data", ")", ":", "self", ".", "_clients", ".", "get", "(", "data", ".", "get", "(", "'id'", ")", ")", ".", "update_volume", "(", "data", ")" ]
Handle client volume change.
[ "Handle", "client", "volume", "change", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L265-L267
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_client_name_changed
def _on_client_name_changed(self, data): """Handle client name changed.""" self._clients.get(data.get('id')).update_name(data)
python
def _on_client_name_changed(self, data): """Handle client name changed.""" self._clients.get(data.get('id')).update_name(data)
[ "def", "_on_client_name_changed", "(", "self", ",", "data", ")", ":", "self", ".", "_clients", ".", "get", "(", "data", ".", "get", "(", "'id'", ")", ")", ".", "update_name", "(", "data", ")" ]
Handle client name changed.
[ "Handle", "client", "name", "changed", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L269-L271
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_client_latency_changed
def _on_client_latency_changed(self, data): """Handle client latency changed.""" self._clients.get(data.get('id')).update_latency(data)
python
def _on_client_latency_changed(self, data): """Handle client latency changed.""" self._clients.get(data.get('id')).update_latency(data)
[ "def", "_on_client_latency_changed", "(", "self", ",", "data", ")", ":", "self", ".", "_clients", ".", "get", "(", "data", ".", "get", "(", "'id'", ")", ")", ".", "update_latency", "(", "data", ")" ]
Handle client latency changed.
[ "Handle", "client", "latency", "changed", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L273-L275
happyleavesaoc/python-snapcast
snapcast/control/server.py
Snapserver._on_stream_update
def _on_stream_update(self, data): """Handle stream update.""" self._streams[data.get('id')].update(data.get('stream')) _LOGGER.info('stream %s updated', self._streams[data.get('id')].friendly_name) for group in self._groups.values(): if group.stream == data.get('id'): ...
python
def _on_stream_update(self, data): """Handle stream update.""" self._streams[data.get('id')].update(data.get('stream')) _LOGGER.info('stream %s updated', self._streams[data.get('id')].friendly_name) for group in self._groups.values(): if group.stream == data.get('id'): ...
[ "def", "_on_stream_update", "(", "self", ",", "data", ")", ":", "self", ".", "_streams", "[", "data", ".", "get", "(", "'id'", ")", "]", ".", "update", "(", "data", ".", "get", "(", "'stream'", ")", ")", "_LOGGER", ".", "info", "(", "'stream %s updat...
Handle stream update.
[ "Handle", "stream", "update", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/server.py#L277-L283
happyleavesaoc/python-snapcast
snapcast/client/__init__.py
mac
def mac(): """ Get MAC. """ from uuid import getnode as get_mac return ':'.join(("%012x" % get_mac())[i:i+2] for i in range(0, 12, 2))
python
def mac(): """ Get MAC. """ from uuid import getnode as get_mac return ':'.join(("%012x" % get_mac())[i:i+2] for i in range(0, 12, 2))
[ "def", "mac", "(", ")", ":", "from", "uuid", "import", "getnode", "as", "get_mac", "return", "':'", ".", "join", "(", "(", "\"%012x\"", "%", "get_mac", "(", ")", ")", "[", "i", ":", "i", "+", "2", "]", "for", "i", "in", "range", "(", "0", ",", ...
Get MAC.
[ "Get", "MAC", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L31-L34
happyleavesaoc/python-snapcast
snapcast/client/__init__.py
Client.register
def register(self): """ Transact with server. """ self._queue.put(hello_packet(socket.gethostname(), mac(), __version__)) self._queue.put(request_packet(MSG_SERVER_SETTINGS)) self._queue.put(request_packet(MSG_SAMPLE_FORMAT)) self._queue.put(request_packet(MSG_HEADER))
python
def register(self): """ Transact with server. """ self._queue.put(hello_packet(socket.gethostname(), mac(), __version__)) self._queue.put(request_packet(MSG_SERVER_SETTINGS)) self._queue.put(request_packet(MSG_SAMPLE_FORMAT)) self._queue.put(request_packet(MSG_HEADER))
[ "def", "register", "(", "self", ")", ":", "self", ".", "_queue", ".", "put", "(", "hello_packet", "(", "socket", ".", "gethostname", "(", ")", ",", "mac", "(", ")", ",", "__version__", ")", ")", "self", ".", "_queue", ".", "put", "(", "request_packet...
Transact with server.
[ "Transact", "with", "server", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L55-L60
happyleavesaoc/python-snapcast
snapcast/client/__init__.py
Client.request_start
def request_start(self): """ Indicate readiness to receive stream. This is a blocking call. """ self._queue.put(command_packet(CMD_START_STREAM)) _LOGGER.info('Requesting stream') self._source.run()
python
def request_start(self): """ Indicate readiness to receive stream. This is a blocking call. """ self._queue.put(command_packet(CMD_START_STREAM)) _LOGGER.info('Requesting stream') self._source.run()
[ "def", "request_start", "(", "self", ")", ":", "self", ".", "_queue", ".", "put", "(", "command_packet", "(", "CMD_START_STREAM", ")", ")", "_LOGGER", ".", "info", "(", "'Requesting stream'", ")", "self", ".", "_source", ".", "run", "(", ")" ]
Indicate readiness to receive stream. This is a blocking call.
[ "Indicate", "readiness", "to", "receive", "stream", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L62-L69
happyleavesaoc/python-snapcast
snapcast/client/__init__.py
Client._read_socket
def _read_socket(self): """ Process incoming messages from socket. """ while True: base_bytes = self._socket.recv(BASE_SIZE) base = basemessage.parse(base_bytes) payload_bytes = self._socket.recv(base.payload_length) self._handle_message(packet.parse(base_...
python
def _read_socket(self): """ Process incoming messages from socket. """ while True: base_bytes = self._socket.recv(BASE_SIZE) base = basemessage.parse(base_bytes) payload_bytes = self._socket.recv(base.payload_length) self._handle_message(packet.parse(base_...
[ "def", "_read_socket", "(", "self", ")", ":", "while", "True", ":", "base_bytes", "=", "self", ".", "_socket", ".", "recv", "(", "BASE_SIZE", ")", "base", "=", "basemessage", ".", "parse", "(", "base_bytes", ")", "payload_bytes", "=", "self", ".", "_sock...
Process incoming messages from socket.
[ "Process", "incoming", "messages", "from", "socket", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L71-L77
happyleavesaoc/python-snapcast
snapcast/client/__init__.py
Client._handle_message
def _handle_message(self, data): """ Handle messages. """ if data.type == MSG_SERVER_SETTINGS: _LOGGER.info(data.payload) elif data.type == MSG_SAMPLE_FORMAT: _LOGGER.info(data.payload) self._connected = True elif data.type == MSG_TIME: if ...
python
def _handle_message(self, data): """ Handle messages. """ if data.type == MSG_SERVER_SETTINGS: _LOGGER.info(data.payload) elif data.type == MSG_SAMPLE_FORMAT: _LOGGER.info(data.payload) self._connected = True elif data.type == MSG_TIME: if ...
[ "def", "_handle_message", "(", "self", ",", "data", ")", ":", "if", "data", ".", "type", "==", "MSG_SERVER_SETTINGS", ":", "_LOGGER", ".", "info", "(", "data", ".", "payload", ")", "elif", "data", ".", "type", "==", "MSG_SAMPLE_FORMAT", ":", "_LOGGER", "...
Handle messages.
[ "Handle", "messages", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L79-L100
happyleavesaoc/python-snapcast
snapcast/client/__init__.py
Client._write_socket
def _write_socket(self): """ Pass messages from queue to socket. """ while True: now = time.time() if self._connected and (self._last_sync + SYNC_AFTER) < now: self._queue.put(request_packet(MSG_TIME)) self._last_sync = now if not self....
python
def _write_socket(self): """ Pass messages from queue to socket. """ while True: now = time.time() if self._connected and (self._last_sync + SYNC_AFTER) < now: self._queue.put(request_packet(MSG_TIME)) self._last_sync = now if not self....
[ "def", "_write_socket", "(", "self", ")", ":", "while", "True", ":", "now", "=", "time", ".", "time", "(", ")", "if", "self", ".", "_connected", "and", "(", "self", ".", "_last_sync", "+", "SYNC_AFTER", ")", "<", "now", ":", "self", ".", "_queue", ...
Pass messages from queue to socket.
[ "Pass", "messages", "from", "queue", "to", "socket", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L102-L110
happyleavesaoc/python-snapcast
snapcast/client/__init__.py
Client._play
def _play(self): """ Relay buffer to app source. """ while True: if self._buffered: self._source.push(self._buffer.get())
python
def _play(self): """ Relay buffer to app source. """ while True: if self._buffered: self._source.push(self._buffer.get())
[ "def", "_play", "(", "self", ")", ":", "while", "True", ":", "if", "self", ".", "_buffered", ":", "self", ".", "_source", ".", "push", "(", "self", ".", "_buffer", ".", "get", "(", ")", ")" ]
Relay buffer to app source.
[ "Relay", "buffer", "to", "app", "source", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L112-L116
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.set_stream
def set_stream(self, stream_id): """Set group stream.""" self._group['stream_id'] = stream_id yield from self._server.group_stream(self.identifier, stream_id) _LOGGER.info('set stream to %s on %s', stream_id, self.friendly_name)
python
def set_stream(self, stream_id): """Set group stream.""" self._group['stream_id'] = stream_id yield from self._server.group_stream(self.identifier, stream_id) _LOGGER.info('set stream to %s on %s', stream_id, self.friendly_name)
[ "def", "set_stream", "(", "self", ",", "stream_id", ")", ":", "self", ".", "_group", "[", "'stream_id'", "]", "=", "stream_id", "yield", "from", "self", ".", "_server", ".", "group_stream", "(", "self", ".", "identifier", ",", "stream_id", ")", "_LOGGER", ...
Set group stream.
[ "Set", "group", "stream", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L40-L44
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.set_muted
def set_muted(self, status): """Set group mute status.""" self._group['muted'] = status yield from self._server.group_mute(self.identifier, status) _LOGGER.info('set muted to %s on %s', status, self.friendly_name)
python
def set_muted(self, status): """Set group mute status.""" self._group['muted'] = status yield from self._server.group_mute(self.identifier, status) _LOGGER.info('set muted to %s on %s', status, self.friendly_name)
[ "def", "set_muted", "(", "self", ",", "status", ")", ":", "self", ".", "_group", "[", "'muted'", "]", "=", "status", "yield", "from", "self", ".", "_server", ".", "group_mute", "(", "self", ".", "identifier", ",", "status", ")", "_LOGGER", ".", "info",...
Set group mute status.
[ "Set", "group", "mute", "status", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L57-L61
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.volume
def volume(self): """Get volume.""" volume_sum = 0 for client in self._group.get('clients'): volume_sum += self._server.client(client.get('id')).volume return int(volume_sum / len(self._group.get('clients')))
python
def volume(self): """Get volume.""" volume_sum = 0 for client in self._group.get('clients'): volume_sum += self._server.client(client.get('id')).volume return int(volume_sum / len(self._group.get('clients')))
[ "def", "volume", "(", "self", ")", ":", "volume_sum", "=", "0", "for", "client", "in", "self", ".", "_group", ".", "get", "(", "'clients'", ")", ":", "volume_sum", "+=", "self", ".", "_server", ".", "client", "(", "client", ".", "get", "(", "'id'", ...
Get volume.
[ "Get", "volume", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L64-L69
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.set_volume
def set_volume(self, volume): """Set volume.""" for data in self._group.get('clients'): client = self._server.client(data.get('id')) yield from client.set_volume(volume, update_group=False) client.update_volume({ 'volume': { 'percen...
python
def set_volume(self, volume): """Set volume.""" for data in self._group.get('clients'): client = self._server.client(data.get('id')) yield from client.set_volume(volume, update_group=False) client.update_volume({ 'volume': { 'percen...
[ "def", "set_volume", "(", "self", ",", "volume", ")", ":", "for", "data", "in", "self", ".", "_group", ".", "get", "(", "'clients'", ")", ":", "client", "=", "self", ".", "_server", ".", "client", "(", "data", ".", "get", "(", "'id'", ")", ")", "...
Set volume.
[ "Set", "volume", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L72-L83
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.add_client
def add_client(self, client_identifier): """Add a client.""" if client_identifier in self.clients: _LOGGER.error('%s already in group %s', client_identifier, self.identifier) return new_clients = self.clients new_clients.append(client_identifier) yield fro...
python
def add_client(self, client_identifier): """Add a client.""" if client_identifier in self.clients: _LOGGER.error('%s already in group %s', client_identifier, self.identifier) return new_clients = self.clients new_clients.append(client_identifier) yield fro...
[ "def", "add_client", "(", "self", ",", "client_identifier", ")", ":", "if", "client_identifier", "in", "self", ".", "clients", ":", "_LOGGER", ".", "error", "(", "'%s already in group %s'", ",", "client_identifier", ",", "self", ".", "identifier", ")", "return",...
Add a client.
[ "Add", "a", "client", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L96-L106
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.remove_client
def remove_client(self, client_identifier): """Remove a client.""" new_clients = self.clients new_clients.remove(client_identifier) yield from self._server.group_clients(self.identifier, new_clients) _LOGGER.info('removed %s from %s', client_identifier, self.identifier) s...
python
def remove_client(self, client_identifier): """Remove a client.""" new_clients = self.clients new_clients.remove(client_identifier) yield from self._server.group_clients(self.identifier, new_clients) _LOGGER.info('removed %s from %s', client_identifier, self.identifier) s...
[ "def", "remove_client", "(", "self", ",", "client_identifier", ")", ":", "new_clients", "=", "self", ".", "clients", "new_clients", ".", "remove", "(", "client_identifier", ")", "yield", "from", "self", ".", "_server", ".", "group_clients", "(", "self", ".", ...
Remove a client.
[ "Remove", "a", "client", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L109-L116
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.update_mute
def update_mute(self, data): """Update mute.""" self._group['muted'] = data['mute'] self.callback() _LOGGER.info('updated mute on %s', self.friendly_name)
python
def update_mute(self, data): """Update mute.""" self._group['muted'] = data['mute'] self.callback() _LOGGER.info('updated mute on %s', self.friendly_name)
[ "def", "update_mute", "(", "self", ",", "data", ")", ":", "self", ".", "_group", "[", "'muted'", "]", "=", "data", "[", "'mute'", "]", "self", ".", "callback", "(", ")", "_LOGGER", ".", "info", "(", "'updated mute on %s'", ",", "self", ".", "friendly_n...
Update mute.
[ "Update", "mute", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L122-L126
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.update_stream
def update_stream(self, data): """Update stream.""" self._group['stream_id'] = data['stream_id'] self.callback() _LOGGER.info('updated stream to %s on %s', self.stream, self.friendly_name)
python
def update_stream(self, data): """Update stream.""" self._group['stream_id'] = data['stream_id'] self.callback() _LOGGER.info('updated stream to %s on %s', self.stream, self.friendly_name)
[ "def", "update_stream", "(", "self", ",", "data", ")", ":", "self", ".", "_group", "[", "'stream_id'", "]", "=", "data", "[", "'stream_id'", "]", "self", ".", "callback", "(", ")", "_LOGGER", ".", "info", "(", "'updated stream to %s on %s'", ",", "self", ...
Update stream.
[ "Update", "stream", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L128-L132
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.snapshot
def snapshot(self): """Snapshot current state.""" self._snapshot = { 'muted': self.muted, 'volume': self.volume, 'stream': self.stream } _LOGGER.info('took snapshot of current state of %s', self.friendly_name)
python
def snapshot(self): """Snapshot current state.""" self._snapshot = { 'muted': self.muted, 'volume': self.volume, 'stream': self.stream } _LOGGER.info('took snapshot of current state of %s', self.friendly_name)
[ "def", "snapshot", "(", "self", ")", ":", "self", ".", "_snapshot", "=", "{", "'muted'", ":", "self", ".", "muted", ",", "'volume'", ":", "self", ".", "volume", ",", "'stream'", ":", "self", ".", "stream", "}", "_LOGGER", ".", "info", "(", "'took sna...
Snapshot current state.
[ "Snapshot", "current", "state", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L134-L141
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.restore
def restore(self): """Restore snapshotted state.""" if not self._snapshot: return yield from self.set_muted(self._snapshot['muted']) yield from self.set_volume(self._snapshot['volume']) yield from self.set_stream(self._snapshot['stream']) self.callback() ...
python
def restore(self): """Restore snapshotted state.""" if not self._snapshot: return yield from self.set_muted(self._snapshot['muted']) yield from self.set_volume(self._snapshot['volume']) yield from self.set_stream(self._snapshot['stream']) self.callback() ...
[ "def", "restore", "(", "self", ")", ":", "if", "not", "self", ".", "_snapshot", ":", "return", "yield", "from", "self", ".", "set_muted", "(", "self", ".", "_snapshot", "[", "'muted'", "]", ")", "yield", "from", "self", ".", "set_volume", "(", "self", ...
Restore snapshotted state.
[ "Restore", "snapshotted", "state", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L144-L152
happyleavesaoc/python-snapcast
snapcast/control/group.py
Snapgroup.callback
def callback(self): """Run callback.""" if self._callback_func and callable(self._callback_func): self._callback_func(self)
python
def callback(self): """Run callback.""" if self._callback_func and callable(self._callback_func): self._callback_func(self)
[ "def", "callback", "(", "self", ")", ":", "if", "self", ".", "_callback_func", "and", "callable", "(", "self", ".", "_callback_func", ")", ":", "self", ".", "_callback_func", "(", "self", ")" ]
Run callback.
[ "Run", "callback", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L154-L157
happyleavesaoc/python-snapcast
snapcast/client/messages.py
message
def message(message_type, payload, payload_length): """ Build a message. """ return packet.build( Container( type=message_type, id=1, refer=0, sent=Container( secs=0, usecs=0 ), recv=Container( ...
python
def message(message_type, payload, payload_length): """ Build a message. """ return packet.build( Container( type=message_type, id=1, refer=0, sent=Container( secs=0, usecs=0 ), recv=Container( ...
[ "def", "message", "(", "message_type", ",", "payload", ",", "payload_length", ")", ":", "return", "packet", ".", "build", "(", "Container", "(", "type", "=", "message_type", ",", "id", "=", "1", ",", "refer", "=", "0", ",", "sent", "=", "Container", "(...
Build a message.
[ "Build", "a", "message", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/messages.py#L122-L140
happyleavesaoc/python-snapcast
snapcast/client/messages.py
map_helper
def map_helper(data): """ Build a map message. """ as_list = [] length = 2 for field, value in data.items(): as_list.append(Container(field=bytes(field, ENCODING), value=bytes(value, ENCODING))) length += len(field) + len(value) + 4 return (Container(...
python
def map_helper(data): """ Build a map message. """ as_list = [] length = 2 for field, value in data.items(): as_list.append(Container(field=bytes(field, ENCODING), value=bytes(value, ENCODING))) length += len(field) + len(value) + 4 return (Container(...
[ "def", "map_helper", "(", "data", ")", ":", "as_list", "=", "[", "]", "length", "=", "2", "for", "field", ",", "value", "in", "data", ".", "items", "(", ")", ":", "as_list", ".", "append", "(", "Container", "(", "field", "=", "bytes", "(", "field",...
Build a map message.
[ "Build", "a", "map", "message", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/messages.py#L143-L154
happyleavesaoc/python-snapcast
snapcast/client/messages.py
command_packet
def command_packet(cmd): """ Build a command message. """ return message('Command', Container(string_length=len(cmd), string=bytes(cmd, ENCODING)), len(cmd) + 2)
python
def command_packet(cmd): """ Build a command message. """ return message('Command', Container(string_length=len(cmd), string=bytes(cmd, ENCODING)), len(cmd) + 2)
[ "def", "command_packet", "(", "cmd", ")", ":", "return", "message", "(", "'Command'", ",", "Container", "(", "string_length", "=", "len", "(", "cmd", ")", ",", "string", "=", "bytes", "(", "cmd", ",", "ENCODING", ")", ")", ",", "len", "(", "cmd", ")"...
Build a command message.
[ "Build", "a", "command", "message", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/messages.py#L171-L176
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.group
def group(self): """Get group.""" for group in self._server.groups: if self.identifier in group.clients: return group
python
def group(self): """Get group.""" for group in self._server.groups: if self.identifier in group.clients: return group
[ "def", "group", "(", "self", ")", ":", "for", "group", "in", "self", ".", "_server", ".", "groups", ":", "if", "self", ".", "identifier", "in", "group", ".", "clients", ":", "return", "group" ]
Get group.
[ "Get", "group", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L27-L31
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.friendly_name
def friendly_name(self): """Get friendly name.""" if len(self._client.get('config').get('name')): return self._client.get('config').get('name') return self._client.get('host').get('name')
python
def friendly_name(self): """Get friendly name.""" if len(self._client.get('config').get('name')): return self._client.get('config').get('name') return self._client.get('host').get('name')
[ "def", "friendly_name", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_client", ".", "get", "(", "'config'", ")", ".", "get", "(", "'name'", ")", ")", ":", "return", "self", ".", "_client", ".", "get", "(", "'config'", ")", ".", "get", "...
Get friendly name.
[ "Get", "friendly", "name", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L34-L38
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.set_name
def set_name(self, name): """Set a client name.""" if not name: name = '' self._client['config']['name'] = name yield from self._server.client_name(self.identifier, name)
python
def set_name(self, name): """Set a client name.""" if not name: name = '' self._client['config']['name'] = name yield from self._server.client_name(self.identifier, name)
[ "def", "set_name", "(", "self", ",", "name", ")", ":", "if", "not", "name", ":", "name", "=", "''", "self", ".", "_client", "[", "'config'", "]", "[", "'name'", "]", "=", "name", "yield", "from", "self", ".", "_server", ".", "client_name", "(", "se...
Set a client name.
[ "Set", "a", "client", "name", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L56-L61
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.set_latency
def set_latency(self, latency): """Set client latency.""" self._client['config']['latency'] = latency yield from self._server.client_latency(self.identifier, latency)
python
def set_latency(self, latency): """Set client latency.""" self._client['config']['latency'] = latency yield from self._server.client_latency(self.identifier, latency)
[ "def", "set_latency", "(", "self", ",", "latency", ")", ":", "self", ".", "_client", "[", "'config'", "]", "[", "'latency'", "]", "=", "latency", "yield", "from", "self", ".", "_server", ".", "client_latency", "(", "self", ".", "identifier", ",", "latenc...
Set client latency.
[ "Set", "client", "latency", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L69-L72
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.set_muted
def set_muted(self, status): """Set client mute status.""" new_volume = self._client['config']['volume'] new_volume['muted'] = status self._client['config']['volume']['muted'] = status yield from self._server.client_volume(self.identifier, new_volume) _LOGGER.info('set mu...
python
def set_muted(self, status): """Set client mute status.""" new_volume = self._client['config']['volume'] new_volume['muted'] = status self._client['config']['volume']['muted'] = status yield from self._server.client_volume(self.identifier, new_volume) _LOGGER.info('set mu...
[ "def", "set_muted", "(", "self", ",", "status", ")", ":", "new_volume", "=", "self", ".", "_client", "[", "'config'", "]", "[", "'volume'", "]", "new_volume", "[", "'muted'", "]", "=", "status", "self", ".", "_client", "[", "'config'", "]", "[", "'volu...
Set client mute status.
[ "Set", "client", "mute", "status", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L80-L86
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.set_volume
def set_volume(self, percent, update_group=True): """Set client volume percent.""" if percent not in range(0, 101): raise ValueError('Volume percent out of range') new_volume = self._client['config']['volume'] new_volume['percent'] = percent self._client['config']['vo...
python
def set_volume(self, percent, update_group=True): """Set client volume percent.""" if percent not in range(0, 101): raise ValueError('Volume percent out of range') new_volume = self._client['config']['volume'] new_volume['percent'] = percent self._client['config']['vo...
[ "def", "set_volume", "(", "self", ",", "percent", ",", "update_group", "=", "True", ")", ":", "if", "percent", "not", "in", "range", "(", "0", ",", "101", ")", ":", "raise", "ValueError", "(", "'Volume percent out of range'", ")", "new_volume", "=", "self"...
Set client volume percent.
[ "Set", "client", "volume", "percent", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L94-L104
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.update_volume
def update_volume(self, data): """Update volume.""" self._client['config']['volume'] = data['volume'] _LOGGER.info('updated volume on %s', self.friendly_name) self._server.group(self.group.identifier).callback() self.callback()
python
def update_volume(self, data): """Update volume.""" self._client['config']['volume'] = data['volume'] _LOGGER.info('updated volume on %s', self.friendly_name) self._server.group(self.group.identifier).callback() self.callback()
[ "def", "update_volume", "(", "self", ",", "data", ")", ":", "self", ".", "_client", "[", "'config'", "]", "[", "'volume'", "]", "=", "data", "[", "'volume'", "]", "_LOGGER", ".", "info", "(", "'updated volume on %s'", ",", "self", ".", "friendly_name", "...
Update volume.
[ "Update", "volume", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L106-L111
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.update_name
def update_name(self, data): """Update name.""" self._client['config']['name'] = data['name'] _LOGGER.info('updated name on %s', self.friendly_name) self.callback()
python
def update_name(self, data): """Update name.""" self._client['config']['name'] = data['name'] _LOGGER.info('updated name on %s', self.friendly_name) self.callback()
[ "def", "update_name", "(", "self", ",", "data", ")", ":", "self", ".", "_client", "[", "'config'", "]", "[", "'name'", "]", "=", "data", "[", "'name'", "]", "_LOGGER", ".", "info", "(", "'updated name on %s'", ",", "self", ".", "friendly_name", ")", "s...
Update name.
[ "Update", "name", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L113-L117
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.update_latency
def update_latency(self, data): """Update latency.""" self._client['config']['latency'] = data['latency'] _LOGGER.info('updated latency on %s', self.friendly_name) self.callback()
python
def update_latency(self, data): """Update latency.""" self._client['config']['latency'] = data['latency'] _LOGGER.info('updated latency on %s', self.friendly_name) self.callback()
[ "def", "update_latency", "(", "self", ",", "data", ")", ":", "self", ".", "_client", "[", "'config'", "]", "[", "'latency'", "]", "=", "data", "[", "'latency'", "]", "_LOGGER", ".", "info", "(", "'updated latency on %s'", ",", "self", ".", "friendly_name",...
Update latency.
[ "Update", "latency", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L119-L123
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.update_connected
def update_connected(self, status): """Update connected.""" self._client['connected'] = status _LOGGER.info('updated connected status to %s on %s', status, self.friendly_name) self.callback()
python
def update_connected(self, status): """Update connected.""" self._client['connected'] = status _LOGGER.info('updated connected status to %s on %s', status, self.friendly_name) self.callback()
[ "def", "update_connected", "(", "self", ",", "status", ")", ":", "self", ".", "_client", "[", "'connected'", "]", "=", "status", "_LOGGER", ".", "info", "(", "'updated connected status to %s on %s'", ",", "status", ",", "self", ".", "friendly_name", ")", "self...
Update connected.
[ "Update", "connected", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L125-L129
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.snapshot
def snapshot(self): """Snapshot current state.""" self._snapshot = { 'name': self.name, 'volume': self.volume, 'muted': self.muted, 'latency': self.latency } _LOGGER.info('took snapshot of current state of %s', self.friendly_name)
python
def snapshot(self): """Snapshot current state.""" self._snapshot = { 'name': self.name, 'volume': self.volume, 'muted': self.muted, 'latency': self.latency } _LOGGER.info('took snapshot of current state of %s', self.friendly_name)
[ "def", "snapshot", "(", "self", ")", ":", "self", ".", "_snapshot", "=", "{", "'name'", ":", "self", ".", "name", ",", "'volume'", ":", "self", ".", "volume", ",", "'muted'", ":", "self", ".", "muted", ",", "'latency'", ":", "self", ".", "latency", ...
Snapshot current state.
[ "Snapshot", "current", "state", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L131-L139
happyleavesaoc/python-snapcast
snapcast/control/client.py
Snapclient.restore
def restore(self): """Restore snapshotted state.""" if not self._snapshot: return yield from self.set_name(self._snapshot['name']) yield from self.set_volume(self._snapshot['volume']) yield from self.set_muted(self._snapshot['muted']) yield from self.set_laten...
python
def restore(self): """Restore snapshotted state.""" if not self._snapshot: return yield from self.set_name(self._snapshot['name']) yield from self.set_volume(self._snapshot['volume']) yield from self.set_muted(self._snapshot['muted']) yield from self.set_laten...
[ "def", "restore", "(", "self", ")", ":", "if", "not", "self", ".", "_snapshot", ":", "return", "yield", "from", "self", ".", "set_name", "(", "self", ".", "_snapshot", "[", "'name'", "]", ")", "yield", "from", "self", ".", "set_volume", "(", "self", ...
Restore snapshotted state.
[ "Restore", "snapshotted", "state", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L142-L151
happyleavesaoc/python-snapcast
snapcast/client/gstreamer.py
GstreamerAppSrc.push
def push(self, buf): """ Push a buffer into the source. """ self._src.emit('push-buffer', Gst.Buffer.new_wrapped(buf))
python
def push(self, buf): """ Push a buffer into the source. """ self._src.emit('push-buffer', Gst.Buffer.new_wrapped(buf))
[ "def", "push", "(", "self", ",", "buf", ")", ":", "self", ".", "_src", ".", "emit", "(", "'push-buffer'", ",", "Gst", ".", "Buffer", ".", "new_wrapped", "(", "buf", ")", ")" ]
Push a buffer into the source.
[ "Push", "a", "buffer", "into", "the", "source", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/gstreamer.py#L59-L61
happyleavesaoc/python-snapcast
snapcast/control/__init__.py
create_server
def create_server(loop, host, port=CONTROL_PORT, reconnect=False): """Server factory.""" server = Snapserver(loop, host, port, reconnect) yield from server.start() return server
python
def create_server(loop, host, port=CONTROL_PORT, reconnect=False): """Server factory.""" server = Snapserver(loop, host, port, reconnect) yield from server.start() return server
[ "def", "create_server", "(", "loop", ",", "host", ",", "port", "=", "CONTROL_PORT", ",", "reconnect", "=", "False", ")", ":", "server", "=", "Snapserver", "(", "loop", ",", "host", ",", "port", ",", "reconnect", ")", "yield", "from", "server", ".", "st...
Server factory.
[ "Server", "factory", "." ]
train
https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/__init__.py#L8-L12
hmarr/django-debug-toolbar-mongo
debug_toolbar_mongo/operation_tracker.py
_get_ordering
def _get_ordering(son): """Helper function to extract formatted ordering from dict. """ def fmt(field, direction): return '{0}{1}'.format({-1: '-', 1: '+'}[direction], field) if '$orderby' in son: return ', '.join(fmt(f, d) for f, d in son['$orderby'].items())
python
def _get_ordering(son): """Helper function to extract formatted ordering from dict. """ def fmt(field, direction): return '{0}{1}'.format({-1: '-', 1: '+'}[direction], field) if '$orderby' in son: return ', '.join(fmt(f, d) for f, d in son['$orderby'].items())
[ "def", "_get_ordering", "(", "son", ")", ":", "def", "fmt", "(", "field", ",", "direction", ")", ":", "return", "'{0}{1}'", ".", "format", "(", "{", "-", "1", ":", "'-'", ",", "1", ":", "'+'", "}", "[", "direction", "]", ",", "field", ")", "if", ...
Helper function to extract formatted ordering from dict.
[ "Helper", "function", "to", "extract", "formatted", "ordering", "from", "dict", "." ]
train
https://github.com/hmarr/django-debug-toolbar-mongo/blob/b0686a76f1ce3532088c4aee6e76b9abe61cc808/debug_toolbar_mongo/operation_tracker.py#L218-L225
hmarr/django-debug-toolbar-mongo
debug_toolbar_mongo/operation_tracker.py
_tidy_stacktrace
def _tidy_stacktrace(stack): """ Clean up stacktrace and remove all entries that: 1. Are part of Django (except contrib apps) 2. Are part of SocketServer (used by Django's dev server) 3. Are the last entry (which is part of our stacktracing code) ``stack`` should be a list of frame tuples from ...
python
def _tidy_stacktrace(stack): """ Clean up stacktrace and remove all entries that: 1. Are part of Django (except contrib apps) 2. Are part of SocketServer (used by Django's dev server) 3. Are the last entry (which is part of our stacktracing code) ``stack`` should be a list of frame tuples from ...
[ "def", "_tidy_stacktrace", "(", "stack", ")", ":", "django_path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "dirname", "(", "django", ".", "__file__", ")", ")", "django_path", "=", "os", ".", "path", ".", "normpath", "(", ...
Clean up stacktrace and remove all entries that: 1. Are part of Django (except contrib apps) 2. Are part of SocketServer (used by Django's dev server) 3. Are the last entry (which is part of our stacktracing code) ``stack`` should be a list of frame tuples from ``inspect.stack()``
[ "Clean", "up", "stacktrace", "and", "remove", "all", "entries", "that", ":", "1", ".", "Are", "part", "of", "Django", "(", "except", "contrib", "apps", ")", "2", ".", "Are", "part", "of", "SocketServer", "(", "used", "by", "Django", "s", "dev", "server...
train
https://github.com/hmarr/django-debug-toolbar-mongo/blob/b0686a76f1ce3532088c4aee6e76b9abe61cc808/debug_toolbar_mongo/operation_tracker.py#L228-L261