repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
nooperpudd/weibopy
weibopy/weibo.py
filter_params
def filter_params(params): """ convert dict value if value is bool type, False -> "false" True -> "true" """ if params is not None: new_params = copy.deepcopy(params) new_params = dict((k, v) for k, v in new_params.items() if v is not None) for key, value in new_params.items(): if isinstance(value, bool): new_params[key] = "true" if value else "false" return new_params
python
def filter_params(params): """ convert dict value if value is bool type, False -> "false" True -> "true" """ if params is not None: new_params = copy.deepcopy(params) new_params = dict((k, v) for k, v in new_params.items() if v is not None) for key, value in new_params.items(): if isinstance(value, bool): new_params[key] = "true" if value else "false" return new_params
[ "def", "filter_params", "(", "params", ")", ":", "if", "params", "is", "not", "None", ":", "new_params", "=", "copy", ".", "deepcopy", "(", "params", ")", "new_params", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "new_params", ".", "items", "(", ")", "if", "v", "is", "not", "None", ")", "for", "key", ",", "value", "in", "new_params", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "new_params", "[", "key", "]", "=", "\"true\"", "if", "value", "else", "\"false\"", "return", "new_params" ]
convert dict value if value is bool type, False -> "false" True -> "true"
[ "convert", "dict", "value", "if", "value", "is", "bool", "type", "False", "-", ">", "false", "True", "-", ">", "true" ]
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/weibo.py#L9-L21
train
nooperpudd/weibopy
weibopy/weibo.py
WeiboClient._handler_response
def _handler_response(self, response, data=None): """ error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return: """ if response.status_code == 200: data = response.json() if isinstance(data, dict) and data.get("error_code"): raise WeiboAPIError(data.get("request"), data.get("error_code"), data.get("error")) else: return data else: raise WeiboRequestError( "Weibo API request error: status code: {code} url:{url} ->" " method:{method}: data={data}".format( code=response.status_code, url=response.url, method=response.request.method, data=data ) )
python
def _handler_response(self, response, data=None): """ error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return: """ if response.status_code == 200: data = response.json() if isinstance(data, dict) and data.get("error_code"): raise WeiboAPIError(data.get("request"), data.get("error_code"), data.get("error")) else: return data else: raise WeiboRequestError( "Weibo API request error: status code: {code} url:{url} ->" " method:{method}: data={data}".format( code=response.status_code, url=response.url, method=response.request.method, data=data ) )
[ "def", "_handler_response", "(", "self", ",", "response", ",", "data", "=", "None", ")", ":", "if", "response", ".", "status_code", "==", "200", ":", "data", "=", "response", ".", "json", "(", ")", "if", "isinstance", "(", "data", ",", "dict", ")", "and", "data", ".", "get", "(", "\"error_code\"", ")", ":", "raise", "WeiboAPIError", "(", "data", ".", "get", "(", "\"request\"", ")", ",", "data", ".", "get", "(", "\"error_code\"", ")", ",", "data", ".", "get", "(", "\"error\"", ")", ")", "else", ":", "return", "data", "else", ":", "raise", "WeiboRequestError", "(", "\"Weibo API request error: status code: {code} url:{url} ->\"", "\" method:{method}: data={data}\"", ".", "format", "(", "code", "=", "response", ".", "status_code", ",", "url", "=", "response", ".", "url", ",", "method", "=", "response", ".", "request", ".", "method", ",", "data", "=", "data", ")", ")" ]
error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return:
[ "error", "code", "response", ":", "{", "request", ":", "/", "statuses", "/", "home_timeline", ".", "json", "error_code", ":", "20502", "error", ":", "Need", "you", "follow", "uid", ".", "}", ":", "param", "response", ":", ":", "return", ":" ]
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/weibo.py#L37-L64
train
nooperpudd/weibopy
weibopy/weibo.py
WeiboClient.get
def get(self, suffix, params=None): """ request weibo api :param suffix: str, :param params: dict, url query parameters :return: """ url = self.base + suffix params = filter_params(params) response = self.session.get(url=url, params=params) return self._handler_response(response)
python
def get(self, suffix, params=None): """ request weibo api :param suffix: str, :param params: dict, url query parameters :return: """ url = self.base + suffix params = filter_params(params) response = self.session.get(url=url, params=params) return self._handler_response(response)
[ "def", "get", "(", "self", ",", "suffix", ",", "params", "=", "None", ")", ":", "url", "=", "self", ".", "base", "+", "suffix", "params", "=", "filter_params", "(", "params", ")", "response", "=", "self", ".", "session", ".", "get", "(", "url", "=", "url", ",", "params", "=", "params", ")", "return", "self", ".", "_handler_response", "(", "response", ")" ]
request weibo api :param suffix: str, :param params: dict, url query parameters :return:
[ "request", "weibo", "api", ":", "param", "suffix", ":", "str", ":", "param", "params", ":", "dict", "url", "query", "parameters", ":", "return", ":" ]
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/weibo.py#L66-L80
train
nooperpudd/weibopy
weibopy/weibo.py
WeiboClient.post
def post(self, suffix, params=None, data=None, files=None): """ :return: """ url = self.base + suffix params = filter_params(params) response = self.session.post(url=url, params=params, data=data, files=files) return self._handler_response(response, data=data)
python
def post(self, suffix, params=None, data=None, files=None): """ :return: """ url = self.base + suffix params = filter_params(params) response = self.session.post(url=url, params=params, data=data, files=files) return self._handler_response(response, data=data)
[ "def", "post", "(", "self", ",", "suffix", ",", "params", "=", "None", ",", "data", "=", "None", ",", "files", "=", "None", ")", ":", "url", "=", "self", ".", "base", "+", "suffix", "params", "=", "filter_params", "(", "params", ")", "response", "=", "self", ".", "session", ".", "post", "(", "url", "=", "url", ",", "params", "=", "params", ",", "data", "=", "data", ",", "files", "=", "files", ")", "return", "self", ".", "_handler_response", "(", "response", ",", "data", "=", "data", ")" ]
:return:
[ ":", "return", ":" ]
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/weibo.py#L82-L92
train
EUDAT-B2SAFE/B2HANDLE
b2handle/searcher.py
Searcher.search_handle
def search_handle(self, **args): ''' Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`. *Note:* If allowed search keys are configured, only these are used. If no allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet, possibly causing a :exc:`~b2handle.handleexceptions.ReverseLookupException`. Example calls: * list_of_handles = search_handle('http://www.foo.com') * list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999) * list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999) :param URL: Optional. The URL to search for (reverse lookup). [This is NOT the URL of the search servlet!] :param prefix: Optional. The Handle prefix to which the search should be limited to. If unspecified, the method will search across all prefixes present at the server given to the constructor. :param key_value_pairs: Optional. Several search fields and values can be specified as key-value-pairs, e.g. CHECKSUM=123456, URL=www.foo.com :raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that cannot be used, or if something else goes wrong. :return: A list of all Handles (strings) that bear the given key with given value of given prefix or server. The list may be empty and may also contain more than one element. ''' LOGGER.debug('search_handle...') if self.__has_search_access: return self.__search_handle(**args) else: LOGGER.error( 'Searching not possible. Reason: No access '+ 'to search system (endpoint: '+ str(self.__search_url)+').' ) return None
python
def search_handle(self, **args): ''' Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`. *Note:* If allowed search keys are configured, only these are used. If no allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet, possibly causing a :exc:`~b2handle.handleexceptions.ReverseLookupException`. Example calls: * list_of_handles = search_handle('http://www.foo.com') * list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999) * list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999) :param URL: Optional. The URL to search for (reverse lookup). [This is NOT the URL of the search servlet!] :param prefix: Optional. The Handle prefix to which the search should be limited to. If unspecified, the method will search across all prefixes present at the server given to the constructor. :param key_value_pairs: Optional. Several search fields and values can be specified as key-value-pairs, e.g. CHECKSUM=123456, URL=www.foo.com :raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that cannot be used, or if something else goes wrong. :return: A list of all Handles (strings) that bear the given key with given value of given prefix or server. The list may be empty and may also contain more than one element. ''' LOGGER.debug('search_handle...') if self.__has_search_access: return self.__search_handle(**args) else: LOGGER.error( 'Searching not possible. Reason: No access '+ 'to search system (endpoint: '+ str(self.__search_url)+').' ) return None
[ "def", "search_handle", "(", "self", ",", "*", "*", "args", ")", ":", "LOGGER", ".", "debug", "(", "'search_handle...'", ")", "if", "self", ".", "__has_search_access", ":", "return", "self", ".", "__search_handle", "(", "*", "*", "args", ")", "else", ":", "LOGGER", ".", "error", "(", "'Searching not possible. Reason: No access '", "+", "'to search system (endpoint: '", "+", "str", "(", "self", ".", "__search_url", ")", "+", "').'", ")", "return", "None" ]
Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`. *Note:* If allowed search keys are configured, only these are used. If no allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet, possibly causing a :exc:`~b2handle.handleexceptions.ReverseLookupException`. Example calls: * list_of_handles = search_handle('http://www.foo.com') * list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999) * list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999) :param URL: Optional. The URL to search for (reverse lookup). [This is NOT the URL of the search servlet!] :param prefix: Optional. The Handle prefix to which the search should be limited to. If unspecified, the method will search across all prefixes present at the server given to the constructor. :param key_value_pairs: Optional. Several search fields and values can be specified as key-value-pairs, e.g. CHECKSUM=123456, URL=www.foo.com :raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that cannot be used, or if something else goes wrong. :return: A list of all Handles (strings) that bear the given key with given value of given prefix or server. The list may be empty and may also contain more than one element.
[ "Search", "for", "handles", "containing", "the", "specified", "key", "with", "the", "specified", "value", ".", "The", "search", "terms", "are", "passed", "on", "to", "the", "reverse", "lookup", "servlet", "as", "-", "is", ".", "The", "servlet", "is", "supposed", "to", "be", "case", "-", "insensitive", "but", "if", "it", "isn", "t", "the", "wrong", "case", "will", "cause", "a", ":", "exc", ":", "~b2handle", ".", "handleexceptions", ".", "ReverseLookupException", "." ]
a6d216d459644e01fbdfd5b318a535950bc5cdbb
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/searcher.py#L210-L250
train
EUDAT-B2SAFE/B2HANDLE
b2handle/searcher.py
Searcher.create_revlookup_query
def create_revlookup_query(self, *fulltext_searchterms, **keyvalue_searchterms): ''' Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet. :param fulltext_searchterms: Optional. Any term specified will be used as search term. Not implemented yet, so will be ignored. :param keyvalue_searchterms: Optional. Key-value pairs. Any key-value pair will be used to search for the value in the field "key". Wildcards accepted (refer to the documentation of the reverse lookup servlet for syntax.) :return: The query string, after the "?". If no valid search terms were specified, None is returned. ''' LOGGER.debug('create_revlookup_query...') allowed_search_keys = self.__allowed_search_keys only_search_for_allowed_keys = False if len(allowed_search_keys) > 0: only_search_for_allowed_keys = True fulltext_searchterms_given = True fulltext_searchterms = b2handle.util.remove_value_none_from_list(fulltext_searchterms) if len(fulltext_searchterms) == 0: fulltext_searchterms_given = False if fulltext_searchterms_given: msg = 'Full-text search is not implemented yet.'+\ ' The provided searchterms '+str(fulltext_searchterms)+\ ' can not be used.' raise ReverseLookupException(msg=msg) keyvalue_searchterms_given = True keyvalue_searchterms = b2handle.util.remove_value_none_from_dict(keyvalue_searchterms) if len(keyvalue_searchterms) == 0: keyvalue_searchterms_given = False if not keyvalue_searchterms_given and not fulltext_searchterms_given: msg = 'No search terms have been specified. Please specify'+\ ' at least one key-value-pair.' raise ReverseLookupException(msg=msg) counter = 0 query = '?' for key, value in keyvalue_searchterms.items(): if only_search_for_allowed_keys and key not in allowed_search_keys: msg = 'Cannot search for key "'+key+'". Only searches '+\ 'for keys '+str(allowed_search_keys)+' are implemented.' raise ReverseLookupException(msg=msg) else: query = query+'&'+key+'='+value counter += 1 query = query.replace('?&', '?') LOGGER.debug('create_revlookup_query: query: '+query) if counter == 0: # unreachable? msg = 'No valid search terms have been specified.' raise ReverseLookupException(msg=msg) return query
python
def create_revlookup_query(self, *fulltext_searchterms, **keyvalue_searchterms): ''' Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet. :param fulltext_searchterms: Optional. Any term specified will be used as search term. Not implemented yet, so will be ignored. :param keyvalue_searchterms: Optional. Key-value pairs. Any key-value pair will be used to search for the value in the field "key". Wildcards accepted (refer to the documentation of the reverse lookup servlet for syntax.) :return: The query string, after the "?". If no valid search terms were specified, None is returned. ''' LOGGER.debug('create_revlookup_query...') allowed_search_keys = self.__allowed_search_keys only_search_for_allowed_keys = False if len(allowed_search_keys) > 0: only_search_for_allowed_keys = True fulltext_searchterms_given = True fulltext_searchterms = b2handle.util.remove_value_none_from_list(fulltext_searchterms) if len(fulltext_searchterms) == 0: fulltext_searchterms_given = False if fulltext_searchterms_given: msg = 'Full-text search is not implemented yet.'+\ ' The provided searchterms '+str(fulltext_searchterms)+\ ' can not be used.' raise ReverseLookupException(msg=msg) keyvalue_searchterms_given = True keyvalue_searchterms = b2handle.util.remove_value_none_from_dict(keyvalue_searchterms) if len(keyvalue_searchterms) == 0: keyvalue_searchterms_given = False if not keyvalue_searchterms_given and not fulltext_searchterms_given: msg = 'No search terms have been specified. Please specify'+\ ' at least one key-value-pair.' raise ReverseLookupException(msg=msg) counter = 0 query = '?' for key, value in keyvalue_searchterms.items(): if only_search_for_allowed_keys and key not in allowed_search_keys: msg = 'Cannot search for key "'+key+'". Only searches '+\ 'for keys '+str(allowed_search_keys)+' are implemented.' raise ReverseLookupException(msg=msg) else: query = query+'&'+key+'='+value counter += 1 query = query.replace('?&', '?') LOGGER.debug('create_revlookup_query: query: '+query) if counter == 0: # unreachable? msg = 'No valid search terms have been specified.' raise ReverseLookupException(msg=msg) return query
[ "def", "create_revlookup_query", "(", "self", ",", "*", "fulltext_searchterms", ",", "*", "*", "keyvalue_searchterms", ")", ":", "LOGGER", ".", "debug", "(", "'create_revlookup_query...'", ")", "allowed_search_keys", "=", "self", ".", "__allowed_search_keys", "only_search_for_allowed_keys", "=", "False", "if", "len", "(", "allowed_search_keys", ")", ">", "0", ":", "only_search_for_allowed_keys", "=", "True", "fulltext_searchterms_given", "=", "True", "fulltext_searchterms", "=", "b2handle", ".", "util", ".", "remove_value_none_from_list", "(", "fulltext_searchterms", ")", "if", "len", "(", "fulltext_searchterms", ")", "==", "0", ":", "fulltext_searchterms_given", "=", "False", "if", "fulltext_searchterms_given", ":", "msg", "=", "'Full-text search is not implemented yet.'", "+", "' The provided searchterms '", "+", "str", "(", "fulltext_searchterms", ")", "+", "' can not be used.'", "raise", "ReverseLookupException", "(", "msg", "=", "msg", ")", "keyvalue_searchterms_given", "=", "True", "keyvalue_searchterms", "=", "b2handle", ".", "util", ".", "remove_value_none_from_dict", "(", "keyvalue_searchterms", ")", "if", "len", "(", "keyvalue_searchterms", ")", "==", "0", ":", "keyvalue_searchterms_given", "=", "False", "if", "not", "keyvalue_searchterms_given", "and", "not", "fulltext_searchterms_given", ":", "msg", "=", "'No search terms have been specified. Please specify'", "+", "' at least one key-value-pair.'", "raise", "ReverseLookupException", "(", "msg", "=", "msg", ")", "counter", "=", "0", "query", "=", "'?'", "for", "key", ",", "value", "in", "keyvalue_searchterms", ".", "items", "(", ")", ":", "if", "only_search_for_allowed_keys", "and", "key", "not", "in", "allowed_search_keys", ":", "msg", "=", "'Cannot search for key \"'", "+", "key", "+", "'\". Only searches '", "+", "'for keys '", "+", "str", "(", "allowed_search_keys", ")", "+", "' are implemented.'", "raise", "ReverseLookupException", "(", "msg", "=", "msg", ")", "else", ":", "query", "=", "query", "+", "'&'", "+", "key", "+", "'='", "+", "value", "counter", "+=", "1", "query", "=", "query", ".", "replace", "(", "'?&'", ",", "'?'", ")", "LOGGER", ".", "debug", "(", "'create_revlookup_query: query: '", "+", "query", ")", "if", "counter", "==", "0", ":", "# unreachable?", "msg", "=", "'No valid search terms have been specified.'", "raise", "ReverseLookupException", "(", "msg", "=", "msg", ")", "return", "query" ]
Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet. :param fulltext_searchterms: Optional. Any term specified will be used as search term. Not implemented yet, so will be ignored. :param keyvalue_searchterms: Optional. Key-value pairs. Any key-value pair will be used to search for the value in the field "key". Wildcards accepted (refer to the documentation of the reverse lookup servlet for syntax.) :return: The query string, after the "?". If no valid search terms were specified, None is returned.
[ "Create", "the", "part", "of", "the", "solr", "request", "that", "comes", "after", "the", "question", "mark", "e", ".", "g", ".", "?URL", "=", "*", "dkrz", "*", "&CHECKSUM", "=", "*", "abc", "*", ".", "If", "allowed", "search", "keys", "are", "configured", "only", "these", "are", "used", ".", "If", "no", "allowed", "search", "keys", "are", "specified", "all", "key", "-", "value", "pairs", "are", "passed", "on", "to", "the", "reverse", "lookup", "servlet", "." ]
a6d216d459644e01fbdfd5b318a535950bc5cdbb
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/searcher.py#L340-L402
train
EUDAT-B2SAFE/B2HANDLE
b2handle/searcher.py
Searcher.__set_revlookup_auth_string
def __set_revlookup_auth_string(self, username, password): ''' Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password. ''' auth = b2handle.utilhandle.create_authentication_string(username, password) self.__revlookup_auth_string = auth
python
def __set_revlookup_auth_string(self, username, password): ''' Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password. ''' auth = b2handle.utilhandle.create_authentication_string(username, password) self.__revlookup_auth_string = auth
[ "def", "__set_revlookup_auth_string", "(", "self", ",", "username", ",", "password", ")", ":", "auth", "=", "b2handle", ".", "utilhandle", ".", "create_authentication_string", "(", "username", ",", "password", ")", "self", ".", "__revlookup_auth_string", "=", "auth" ]
Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password.
[ "Creates", "and", "sets", "the", "authentication", "string", "for", "accessing", "the", "reverse", "lookup", "servlet", ".", "No", "return", "the", "string", "is", "set", "as", "an", "attribute", "to", "the", "client", "instance", "." ]
a6d216d459644e01fbdfd5b318a535950bc5cdbb
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/searcher.py#L404-L414
train
EUDAT-B2SAFE/B2HANDLE
b2handle/clientcredentials.py
PIDClientCredentials.load_from_JSON
def load_from_JSON(json_filename): ''' Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_server_url": "https://url.to.your.handle.server", "username": "index:prefix/suffix", "password": "ZZZZZZZ", "prefix": "prefix_to_use_for_writing_handles", "handleowner": "username_to_own_handles" } Any additional key-value-pairs are stored in the instance as config. :raises: :exc:`~b2handle.handleexceptions.CredentialsFormatError` :raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError` :return: An instance. ''' try: jsonfilecontent = json.loads(open(json_filename, 'r').read()) except ValueError as exc: raise CredentialsFormatError(msg="Invalid JSON syntax: "+str(exc)) instance = PIDClientCredentials(credentials_filename=json_filename,**jsonfilecontent) return instance
python
def load_from_JSON(json_filename): ''' Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_server_url": "https://url.to.your.handle.server", "username": "index:prefix/suffix", "password": "ZZZZZZZ", "prefix": "prefix_to_use_for_writing_handles", "handleowner": "username_to_own_handles" } Any additional key-value-pairs are stored in the instance as config. :raises: :exc:`~b2handle.handleexceptions.CredentialsFormatError` :raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError` :return: An instance. ''' try: jsonfilecontent = json.loads(open(json_filename, 'r').read()) except ValueError as exc: raise CredentialsFormatError(msg="Invalid JSON syntax: "+str(exc)) instance = PIDClientCredentials(credentials_filename=json_filename,**jsonfilecontent) return instance
[ "def", "load_from_JSON", "(", "json_filename", ")", ":", "try", ":", "jsonfilecontent", "=", "json", ".", "loads", "(", "open", "(", "json_filename", ",", "'r'", ")", ".", "read", "(", ")", ")", "except", "ValueError", "as", "exc", ":", "raise", "CredentialsFormatError", "(", "msg", "=", "\"Invalid JSON syntax: \"", "+", "str", "(", "exc", ")", ")", "instance", "=", "PIDClientCredentials", "(", "credentials_filename", "=", "json_filename", ",", "*", "*", "jsonfilecontent", ")", "return", "instance" ]
Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_server_url": "https://url.to.your.handle.server", "username": "index:prefix/suffix", "password": "ZZZZZZZ", "prefix": "prefix_to_use_for_writing_handles", "handleowner": "username_to_own_handles" } Any additional key-value-pairs are stored in the instance as config. :raises: :exc:`~b2handle.handleexceptions.CredentialsFormatError` :raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError` :return: An instance.
[ "Create", "a", "new", "instance", "of", "a", "PIDClientCredentials", "with", "information", "read", "from", "a", "local", "JSON", "file", "." ]
a6d216d459644e01fbdfd5b318a535950bc5cdbb
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/clientcredentials.py#L29-L58
train
alexhayes/django-migration-fixture
django_migration_fixture/__init__.py
fixture
def fixture(app, fixtures, fixtures_dir='fixtures', raise_does_not_exist=False, reversible=True, models=[]): """ Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=False to prevent rolling back. Usage: import myapp import anotherapp operations = [ migrations.RunPython(**fixture(myapp, 'eggs.yaml')), migrations.RunPython(**fixture(anotherapp, ['sausage.json', 'walks.yaml'])) migrations.RunPython(**fixture(yap, ['foo.json'], reversible=False)) ] """ fixture_path = os.path.join(app.__path__[0], fixtures_dir) if isinstance(fixtures, string_types): fixtures = [fixtures] def get_format(fixture): return os.path.splitext(fixture)[1][1:] def get_objects(): for fixture in fixtures: with open(os.path.join(fixture_path, fixture), 'rb') as f: objects = serializers.deserialize(get_format(fixture), f, ignorenonexistent=True) for obj in objects: yield obj def patch_apps(func): """ Patch the app registry. Note that this is necessary so that the Deserializer does not use the current version of the model, which may not necessarily be representative of the model the fixture was created for. """ @wraps(func) def inner(apps, schema_editor): try: # Firstly patch the serializers registry original_apps = django.core.serializers.python.apps django.core.serializers.python.apps = apps return func(apps, schema_editor) finally: # Ensure we always unpatch the serializers registry django.core.serializers.python.apps = original_apps return inner @patch_apps def load_fixture(apps, schema_editor): for obj in get_objects(): obj.save() @patch_apps def unload_fixture(apps, schema_editor): for obj in get_objects(): model = apps.get_model(app.__name__, obj.object.__class__.__name__) kwargs = dict() if 'id' in obj.object.__dict__: kwargs.update(id=obj.object.__dict__.get('id')) elif 'slug' in obj.object.__dict__: kwargs.update(slug=obj.object.__dict__.get('slug')) else: kwargs.update(**obj.object.__dict__) try: model.objects.get(**kwargs).delete() except model.DoesNotExist: if not raise_does_not_exist: raise FixtureObjectDoesNotExist(("Model %s instance with " "kwargs %s does not exist." % (model, kwargs))) kwargs = dict(code=load_fixture) if reversible: kwargs['reverse_code'] = unload_fixture return kwargs
python
def fixture(app, fixtures, fixtures_dir='fixtures', raise_does_not_exist=False, reversible=True, models=[]): """ Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=False to prevent rolling back. Usage: import myapp import anotherapp operations = [ migrations.RunPython(**fixture(myapp, 'eggs.yaml')), migrations.RunPython(**fixture(anotherapp, ['sausage.json', 'walks.yaml'])) migrations.RunPython(**fixture(yap, ['foo.json'], reversible=False)) ] """ fixture_path = os.path.join(app.__path__[0], fixtures_dir) if isinstance(fixtures, string_types): fixtures = [fixtures] def get_format(fixture): return os.path.splitext(fixture)[1][1:] def get_objects(): for fixture in fixtures: with open(os.path.join(fixture_path, fixture), 'rb') as f: objects = serializers.deserialize(get_format(fixture), f, ignorenonexistent=True) for obj in objects: yield obj def patch_apps(func): """ Patch the app registry. Note that this is necessary so that the Deserializer does not use the current version of the model, which may not necessarily be representative of the model the fixture was created for. """ @wraps(func) def inner(apps, schema_editor): try: # Firstly patch the serializers registry original_apps = django.core.serializers.python.apps django.core.serializers.python.apps = apps return func(apps, schema_editor) finally: # Ensure we always unpatch the serializers registry django.core.serializers.python.apps = original_apps return inner @patch_apps def load_fixture(apps, schema_editor): for obj in get_objects(): obj.save() @patch_apps def unload_fixture(apps, schema_editor): for obj in get_objects(): model = apps.get_model(app.__name__, obj.object.__class__.__name__) kwargs = dict() if 'id' in obj.object.__dict__: kwargs.update(id=obj.object.__dict__.get('id')) elif 'slug' in obj.object.__dict__: kwargs.update(slug=obj.object.__dict__.get('slug')) else: kwargs.update(**obj.object.__dict__) try: model.objects.get(**kwargs).delete() except model.DoesNotExist: if not raise_does_not_exist: raise FixtureObjectDoesNotExist(("Model %s instance with " "kwargs %s does not exist." % (model, kwargs))) kwargs = dict(code=load_fixture) if reversible: kwargs['reverse_code'] = unload_fixture return kwargs
[ "def", "fixture", "(", "app", ",", "fixtures", ",", "fixtures_dir", "=", "'fixtures'", ",", "raise_does_not_exist", "=", "False", ",", "reversible", "=", "True", ",", "models", "=", "[", "]", ")", ":", "fixture_path", "=", "os", ".", "path", ".", "join", "(", "app", ".", "__path__", "[", "0", "]", ",", "fixtures_dir", ")", "if", "isinstance", "(", "fixtures", ",", "string_types", ")", ":", "fixtures", "=", "[", "fixtures", "]", "def", "get_format", "(", "fixture", ")", ":", "return", "os", ".", "path", ".", "splitext", "(", "fixture", ")", "[", "1", "]", "[", "1", ":", "]", "def", "get_objects", "(", ")", ":", "for", "fixture", "in", "fixtures", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "fixture_path", ",", "fixture", ")", ",", "'rb'", ")", "as", "f", ":", "objects", "=", "serializers", ".", "deserialize", "(", "get_format", "(", "fixture", ")", ",", "f", ",", "ignorenonexistent", "=", "True", ")", "for", "obj", "in", "objects", ":", "yield", "obj", "def", "patch_apps", "(", "func", ")", ":", "\"\"\"\n Patch the app registry.\n\n Note that this is necessary so that the Deserializer does not use the\n current version of the model, which may not necessarily be representative\n of the model the fixture was created for.\n \"\"\"", "@", "wraps", "(", "func", ")", "def", "inner", "(", "apps", ",", "schema_editor", ")", ":", "try", ":", "# Firstly patch the serializers registry", "original_apps", "=", "django", ".", "core", ".", "serializers", ".", "python", ".", "apps", "django", ".", "core", ".", "serializers", ".", "python", ".", "apps", "=", "apps", "return", "func", "(", "apps", ",", "schema_editor", ")", "finally", ":", "# Ensure we always unpatch the serializers registry", "django", ".", "core", ".", "serializers", ".", "python", ".", "apps", "=", "original_apps", "return", "inner", "@", "patch_apps", "def", "load_fixture", "(", "apps", ",", "schema_editor", ")", ":", "for", "obj", "in", "get_objects", "(", ")", ":", "obj", ".", "save", "(", ")", "@", "patch_apps", "def", "unload_fixture", "(", "apps", ",", "schema_editor", ")", ":", "for", "obj", "in", "get_objects", "(", ")", ":", "model", "=", "apps", ".", "get_model", "(", "app", ".", "__name__", ",", "obj", ".", "object", ".", "__class__", ".", "__name__", ")", "kwargs", "=", "dict", "(", ")", "if", "'id'", "in", "obj", ".", "object", ".", "__dict__", ":", "kwargs", ".", "update", "(", "id", "=", "obj", ".", "object", ".", "__dict__", ".", "get", "(", "'id'", ")", ")", "elif", "'slug'", "in", "obj", ".", "object", ".", "__dict__", ":", "kwargs", ".", "update", "(", "slug", "=", "obj", ".", "object", ".", "__dict__", ".", "get", "(", "'slug'", ")", ")", "else", ":", "kwargs", ".", "update", "(", "*", "*", "obj", ".", "object", ".", "__dict__", ")", "try", ":", "model", ".", "objects", ".", "get", "(", "*", "*", "kwargs", ")", ".", "delete", "(", ")", "except", "model", ".", "DoesNotExist", ":", "if", "not", "raise_does_not_exist", ":", "raise", "FixtureObjectDoesNotExist", "(", "(", "\"Model %s instance with \"", "\"kwargs %s does not exist.\"", "%", "(", "model", ",", "kwargs", ")", ")", ")", "kwargs", "=", "dict", "(", "code", "=", "load_fixture", ")", "if", "reversible", ":", "kwargs", "[", "'reverse_code'", "]", "=", "unload_fixture", "return", "kwargs" ]
Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=False to prevent rolling back. Usage: import myapp import anotherapp operations = [ migrations.RunPython(**fixture(myapp, 'eggs.yaml')), migrations.RunPython(**fixture(anotherapp, ['sausage.json', 'walks.yaml'])) migrations.RunPython(**fixture(yap, ['foo.json'], reversible=False)) ]
[ "Load", "fixtures", "using", "a", "data", "migration", "." ]
c0463edc599d96bc6f645084eb50e6e94e1f681a
https://github.com/alexhayes/django-migration-fixture/blob/c0463edc599d96bc6f645084eb50e6e94e1f681a/django_migration_fixture/__init__.py#L37-L124
train
wanji/bitmap
src/bitmap.py
BitMap.nonzero
def nonzero(self): """ Get all non-zero bits """ return [i for i in xrange(self.size()) if self.test(i)]
python
def nonzero(self): """ Get all non-zero bits """ return [i for i in xrange(self.size()) if self.test(i)]
[ "def", "nonzero", "(", "self", ")", ":", "return", "[", "i", "for", "i", "in", "xrange", "(", "self", ".", "size", "(", ")", ")", "if", "self", ".", "test", "(", "i", ")", "]" ]
Get all non-zero bits
[ "Get", "all", "non", "-", "zero", "bits" ]
beb750530045e4f7cf665675bfb28f82d6325007
https://github.com/wanji/bitmap/blob/beb750530045e4f7cf665675bfb28f82d6325007/src/bitmap.py#L95-L99
train
wanji/bitmap
src/bitmap.py
BitMap.tohexstring
def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2)
python
def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2)
[ "def", "tohexstring", "(", "self", ")", ":", "val", "=", "self", ".", "tostring", "(", ")", "st", "=", "\"{0:0x}\"", ".", "format", "(", "int", "(", "val", ",", "2", ")", ")", "return", "st", ".", "zfill", "(", "len", "(", "self", ".", "bitmap", ")", "*", "2", ")" ]
Returns a hexadecimal string
[ "Returns", "a", "hexadecimal", "string" ]
beb750530045e4f7cf665675bfb28f82d6325007
https://github.com/wanji/bitmap/blob/beb750530045e4f7cf665675bfb28f82d6325007/src/bitmap.py#L131-L137
train
wanji/bitmap
src/bitmap.py
BitMap.fromhexstring
def fromhexstring(cls, hexstring): """ Construct BitMap from hex string """ bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring)
python
def fromhexstring(cls, hexstring): """ Construct BitMap from hex string """ bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring)
[ "def", "fromhexstring", "(", "cls", ",", "hexstring", ")", ":", "bitstring", "=", "format", "(", "int", "(", "hexstring", ",", "16", ")", ",", "\"0\"", "+", "str", "(", "len", "(", "hexstring", ")", "/", "4", ")", "+", "\"b\"", ")", "return", "cls", ".", "fromstring", "(", "bitstring", ")" ]
Construct BitMap from hex string
[ "Construct", "BitMap", "from", "hex", "string" ]
beb750530045e4f7cf665675bfb28f82d6325007
https://github.com/wanji/bitmap/blob/beb750530045e4f7cf665675bfb28f82d6325007/src/bitmap.py#L140-L145
train
wanji/bitmap
src/bitmap.py
BitMap.fromstring
def fromstring(cls, bitstring): """ Construct BitMap from string """ nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': raise Exception("Invalid bit string!") return bm
python
def fromstring(cls, bitstring): """ Construct BitMap from string """ nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': raise Exception("Invalid bit string!") return bm
[ "def", "fromstring", "(", "cls", ",", "bitstring", ")", ":", "nbits", "=", "len", "(", "bitstring", ")", "bm", "=", "cls", "(", "nbits", ")", "for", "i", "in", "xrange", "(", "nbits", ")", ":", "if", "bitstring", "[", "-", "i", "-", "1", "]", "==", "'1'", ":", "bm", ".", "set", "(", "i", ")", "elif", "bitstring", "[", "-", "i", "-", "1", "]", "!=", "'0'", ":", "raise", "Exception", "(", "\"Invalid bit string!\"", ")", "return", "bm" ]
Construct BitMap from string
[ "Construct", "BitMap", "from", "string" ]
beb750530045e4f7cf665675bfb28f82d6325007
https://github.com/wanji/bitmap/blob/beb750530045e4f7cf665675bfb28f82d6325007/src/bitmap.py#L148-L159
train
csirtgadgets/bearded-avenger-sdk-py
cifsdk/_version.py
get_versions
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree"} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass _version_path = os.path.join(os.path.dirname(__file__), '_version') if os.path.exists(_version_path): with open(_version_path) as f: l = f.readline().strip() return { 'version': l, 'error': None, 'dirty': None, 'full-revisionid': l } return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version"}
python
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree"} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass _version_path = os.path.join(os.path.dirname(__file__), '_version') if os.path.exists(_version_path): with open(_version_path) as f: l = f.readline().strip() return { 'version': l, 'error': None, 'dirty': None, 'full-revisionid': l } return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version"}
[ "def", "get_versions", "(", ")", ":", "# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have", "# __file__, we can work backwards from there to the root. Some", "# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which", "# case we can only use expanded keywords.", "cfg", "=", "get_config", "(", ")", "verbose", "=", "cfg", ".", "verbose", "try", ":", "return", "git_versions_from_keywords", "(", "get_keywords", "(", ")", ",", "cfg", ".", "tag_prefix", ",", "verbose", ")", "except", "NotThisMethod", ":", "pass", "try", ":", "root", "=", "os", ".", "path", ".", "realpath", "(", "__file__", ")", "# versionfile_source is the relative path from the top of the source", "# tree (where the .git directory might live) to this file. Invert", "# this to find the root from __file__.", "for", "i", "in", "cfg", ".", "versionfile_source", ".", "split", "(", "'/'", ")", ":", "root", "=", "os", ".", "path", ".", "dirname", "(", "root", ")", "except", "NameError", ":", "return", "{", "\"version\"", ":", "\"0+unknown\"", ",", "\"full-revisionid\"", ":", "None", ",", "\"dirty\"", ":", "None", ",", "\"error\"", ":", "\"unable to find root of source tree\"", "}", "try", ":", "pieces", "=", "git_pieces_from_vcs", "(", "cfg", ".", "tag_prefix", ",", "root", ",", "verbose", ")", "return", "render", "(", "pieces", ",", "cfg", ".", "style", ")", "except", "NotThisMethod", ":", "pass", "try", ":", "if", "cfg", ".", "parentdir_prefix", ":", "return", "versions_from_parentdir", "(", "cfg", ".", "parentdir_prefix", ",", "root", ",", "verbose", ")", "except", "NotThisMethod", ":", "pass", "_version_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'_version'", ")", "if", "os", ".", "path", ".", "exists", "(", "_version_path", ")", ":", "with", "open", "(", "_version_path", ")", "as", "f", ":", "l", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", "return", "{", "'version'", ":", "l", ",", "'error'", ":", "None", ",", "'dirty'", ":", "None", ",", "'full-revisionid'", ":", "l", "}", "return", "{", "\"version\"", ":", "\"0+unknown\"", ",", "\"full-revisionid\"", ":", "None", ",", "\"dirty\"", ":", "None", ",", "\"error\"", ":", "\"unable to compute version\"", "}" ]
Get version information or return default if unable to do so.
[ "Get", "version", "information", "or", "return", "default", "if", "unable", "to", "do", "so", "." ]
2b3e96cb2e7703ee0402811096da8265a740f378
https://github.com/csirtgadgets/bearded-avenger-sdk-py/blob/2b3e96cb2e7703ee0402811096da8265a740f378/cifsdk/_version.py#L442-L495
train
EUDAT-B2SAFE/B2HANDLE
b2handle/util/utilconfig.py
get_valid_https_verify
def get_valid_https_verify(value): ''' Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE certificate :returns: True, False or a string. ''' http_verify_value = value bool_values = {'false': False, 'true': True} if isinstance(value, bool): http_verify_value = value elif (isinstance(value, str) or isinstance(value, unicode)) and value.lower() in bool_values.keys(): http_verify_value = bool_values[value.lower()] return http_verify_value
python
def get_valid_https_verify(value): ''' Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE certificate :returns: True, False or a string. ''' http_verify_value = value bool_values = {'false': False, 'true': True} if isinstance(value, bool): http_verify_value = value elif (isinstance(value, str) or isinstance(value, unicode)) and value.lower() in bool_values.keys(): http_verify_value = bool_values[value.lower()] return http_verify_value
[ "def", "get_valid_https_verify", "(", "value", ")", ":", "http_verify_value", "=", "value", "bool_values", "=", "{", "'false'", ":", "False", ",", "'true'", ":", "True", "}", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "http_verify_value", "=", "value", "elif", "(", "isinstance", "(", "value", ",", "str", ")", "or", "isinstance", "(", "value", ",", "unicode", ")", ")", "and", "value", ".", "lower", "(", ")", "in", "bool_values", ".", "keys", "(", ")", ":", "http_verify_value", "=", "bool_values", "[", "value", ".", "lower", "(", ")", "]", "return", "http_verify_value" ]
Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE certificate :returns: True, False or a string.
[ "Get", "a", "value", "that", "can", "be", "the", "boolean", "representation", "of", "a", "string", "or", "a", "boolean", "itself", "and", "returns", "It", "as", "a", "boolean", ".", "If", "this", "is", "not", "the", "case", "It", "returns", "a", "string", "." ]
a6d216d459644e01fbdfd5b318a535950bc5cdbb
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/util/utilconfig.py#L6-L24
train
inveniosoftware/invenio-assets
invenio_assets/filters.py
RequireJSFilter.setup
def setup(self): """Setup filter (only called when filter is actually used).""" super(RequireJSFilter, self).setup() excluded_files = [] for bundle in self.excluded_bundles: excluded_files.extend( map(lambda f: os.path.splitext(f)[0], bundle.contents) ) if excluded_files: self.argv.append( 'exclude={0}'.format(','.join(excluded_files)) )
python
def setup(self): """Setup filter (only called when filter is actually used).""" super(RequireJSFilter, self).setup() excluded_files = [] for bundle in self.excluded_bundles: excluded_files.extend( map(lambda f: os.path.splitext(f)[0], bundle.contents) ) if excluded_files: self.argv.append( 'exclude={0}'.format(','.join(excluded_files)) )
[ "def", "setup", "(", "self", ")", ":", "super", "(", "RequireJSFilter", ",", "self", ")", ".", "setup", "(", ")", "excluded_files", "=", "[", "]", "for", "bundle", "in", "self", ".", "excluded_bundles", ":", "excluded_files", ".", "extend", "(", "map", "(", "lambda", "f", ":", "os", ".", "path", ".", "splitext", "(", "f", ")", "[", "0", "]", ",", "bundle", ".", "contents", ")", ")", "if", "excluded_files", ":", "self", ".", "argv", ".", "append", "(", "'exclude={0}'", ".", "format", "(", "','", ".", "join", "(", "excluded_files", ")", ")", ")" ]
Setup filter (only called when filter is actually used).
[ "Setup", "filter", "(", "only", "called", "when", "filter", "is", "actually", "used", ")", "." ]
836cc75ebe0c179f0d72456bd8b784cdc18394a6
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/filters.py#L45-L59
train
inveniosoftware/invenio-assets
invenio_assets/filters.py
CleanCSSFilter.setup
def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
python
def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
[ "def", "setup", "(", "self", ")", ":", "super", "(", "CleanCSSFilter", ",", "self", ")", ".", "setup", "(", ")", "self", ".", "root", "=", "current_app", ".", "config", ".", "get", "(", "'COLLECT_STATIC_ROOT'", ")" ]
Initialize filter just before it will be used.
[ "Initialize", "filter", "just", "before", "it", "will", "be", "used", "." ]
836cc75ebe0c179f0d72456bd8b784cdc18394a6
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/filters.py#L71-L74
train
inveniosoftware/invenio-assets
invenio_assets/filters.py
CleanCSSFilter.rebase_opt
def rebase_opt(self): """Determine which option name to use.""" if not hasattr(self, '_rebase_opt'): # out = b"MAJOR.MINOR.REVISION" // b"3.4.19" or b"4.0.0" out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate() ver = int(out[:out.index(b'.')]) self._rebase_opt = ['--root', self.root] if ver == 3 else [] return self._rebase_opt
python
def rebase_opt(self): """Determine which option name to use.""" if not hasattr(self, '_rebase_opt'): # out = b"MAJOR.MINOR.REVISION" // b"3.4.19" or b"4.0.0" out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate() ver = int(out[:out.index(b'.')]) self._rebase_opt = ['--root', self.root] if ver == 3 else [] return self._rebase_opt
[ "def", "rebase_opt", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_rebase_opt'", ")", ":", "# out = b\"MAJOR.MINOR.REVISION\" // b\"3.4.19\" or b\"4.0.0\"", "out", ",", "err", "=", "Popen", "(", "[", "'cleancss'", ",", "'--version'", "]", ",", "stdout", "=", "PIPE", ")", ".", "communicate", "(", ")", "ver", "=", "int", "(", "out", "[", ":", "out", ".", "index", "(", "b'.'", ")", "]", ")", "self", ".", "_rebase_opt", "=", "[", "'--root'", ",", "self", ".", "root", "]", "if", "ver", "==", "3", "else", "[", "]", "return", "self", ".", "_rebase_opt" ]
Determine which option name to use.
[ "Determine", "which", "option", "name", "to", "use", "." ]
836cc75ebe0c179f0d72456bd8b784cdc18394a6
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/filters.py#L77-L85
train
inveniosoftware/invenio-assets
invenio_assets/filters.py
CleanCSSFilter.input
def input(self, _in, out, **kw): """Input filtering.""" args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
python
def input(self, _in, out, **kw): """Input filtering.""" args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
[ "def", "input", "(", "self", ",", "_in", ",", "out", ",", "*", "*", "kw", ")", ":", "args", "=", "[", "self", ".", "binary", "or", "'cleancss'", "]", "+", "self", ".", "rebase_opt", "if", "self", ".", "extra_args", ":", "args", ".", "extend", "(", "self", ".", "extra_args", ")", "self", ".", "subprocess", "(", "args", ",", "out", ",", "_in", ")" ]
Input filtering.
[ "Input", "filtering", "." ]
836cc75ebe0c179f0d72456bd8b784cdc18394a6
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/filters.py#L87-L92
train
inveniosoftware/invenio-assets
invenio_assets/filters.py
AngularGettextFilter.output
def output(self, _in, out, **kwargs): """Wrap translation in Angular module.""" out.write( 'angular.module("{0}", ["gettext"]).run(' '["gettextCatalog", function (gettextCatalog) {{'.format( self.catalog_name ) ) out.write(_in.read()) out.write('}]);')
python
def output(self, _in, out, **kwargs): """Wrap translation in Angular module.""" out.write( 'angular.module("{0}", ["gettext"]).run(' '["gettextCatalog", function (gettextCatalog) {{'.format( self.catalog_name ) ) out.write(_in.read()) out.write('}]);')
[ "def", "output", "(", "self", ",", "_in", ",", "out", ",", "*", "*", "kwargs", ")", ":", "out", ".", "write", "(", "'angular.module(\"{0}\", [\"gettext\"]).run('", "'[\"gettextCatalog\", function (gettextCatalog) {{'", ".", "format", "(", "self", ".", "catalog_name", ")", ")", "out", ".", "write", "(", "_in", ".", "read", "(", ")", ")", "out", ".", "write", "(", "'}]);'", ")" ]
Wrap translation in Angular module.
[ "Wrap", "translation", "in", "Angular", "module", "." ]
836cc75ebe0c179f0d72456bd8b784cdc18394a6
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/filters.py#L110-L119
train
inveniosoftware/invenio-assets
invenio_assets/filters.py
AngularGettextFilter.input
def input(self, _in, out, **kwargs): """Process individual translation file.""" language_code = _re_language_code.search(_in.read()).group( 'language_code' ) _in.seek(0) # move at the begining after matching the language catalog = read_po(_in) out.write('gettextCatalog.setStrings("{0}", '.format(language_code)) out.write(json.dumps({ key: value.string for key, value in catalog._messages.items() if key and value.string })) out.write(');')
python
def input(self, _in, out, **kwargs): """Process individual translation file.""" language_code = _re_language_code.search(_in.read()).group( 'language_code' ) _in.seek(0) # move at the begining after matching the language catalog = read_po(_in) out.write('gettextCatalog.setStrings("{0}", '.format(language_code)) out.write(json.dumps({ key: value.string for key, value in catalog._messages.items() if key and value.string })) out.write(');')
[ "def", "input", "(", "self", ",", "_in", ",", "out", ",", "*", "*", "kwargs", ")", ":", "language_code", "=", "_re_language_code", ".", "search", "(", "_in", ".", "read", "(", ")", ")", ".", "group", "(", "'language_code'", ")", "_in", ".", "seek", "(", "0", ")", "# move at the begining after matching the language", "catalog", "=", "read_po", "(", "_in", ")", "out", ".", "write", "(", "'gettextCatalog.setStrings(\"{0}\", '", ".", "format", "(", "language_code", ")", ")", "out", ".", "write", "(", "json", ".", "dumps", "(", "{", "key", ":", "value", ".", "string", "for", "key", ",", "value", "in", "catalog", ".", "_messages", ".", "items", "(", ")", "if", "key", "and", "value", ".", "string", "}", ")", ")", "out", ".", "write", "(", "');'", ")" ]
Process individual translation file.
[ "Process", "individual", "translation", "file", "." ]
836cc75ebe0c179f0d72456bd8b784cdc18394a6
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/filters.py#L121-L133
train
redhat-cip/dci-control-server
dci/auth_mechanism.py
BasicAuthMechanism.get_user_and_check_auth
def get_user_and_check_auth(self, username, password): """Check the combination username/password that is valid on the database. """ constraint = sql.or_( models.USERS.c.name == username, models.USERS.c.email == username ) user = self.identity_from_db(models.USERS, constraint) if user is None: raise dci_exc.DCIException('User %s does not exists.' % username, status_code=401) return user, auth.check_passwords_equal(password, user.password)
python
def get_user_and_check_auth(self, username, password): """Check the combination username/password that is valid on the database. """ constraint = sql.or_( models.USERS.c.name == username, models.USERS.c.email == username ) user = self.identity_from_db(models.USERS, constraint) if user is None: raise dci_exc.DCIException('User %s does not exists.' % username, status_code=401) return user, auth.check_passwords_equal(password, user.password)
[ "def", "get_user_and_check_auth", "(", "self", ",", "username", ",", "password", ")", ":", "constraint", "=", "sql", ".", "or_", "(", "models", ".", "USERS", ".", "c", ".", "name", "==", "username", ",", "models", ".", "USERS", ".", "c", ".", "email", "==", "username", ")", "user", "=", "self", ".", "identity_from_db", "(", "models", ".", "USERS", ",", "constraint", ")", "if", "user", "is", "None", ":", "raise", "dci_exc", ".", "DCIException", "(", "'User %s does not exists.'", "%", "username", ",", "status_code", "=", "401", ")", "return", "user", ",", "auth", ".", "check_passwords_equal", "(", "password", ",", "user", ".", "password", ")" ]
Check the combination username/password that is valid on the database.
[ "Check", "the", "combination", "username", "/", "password", "that", "is", "valid", "on", "the", "database", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/auth_mechanism.py#L135-L149
train
redhat-cip/dci-control-server
dci/trackers/github.py
Github.retrieve_info
def retrieve_info(self): """Query the Github API to retrieve the needed infos.""" path = urlparse(self.url).path path = path.split('/')[1:] sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE) self.product = sanity_filter.match(path[0]).group(0) self.component = sanity_filter.match(path[1]).group(0) self.issue_id = int(path[3]) github_url = '%s/%s/%s/issues/%s' % (_URL_BASE, self.product, self.component, self.issue_id) result = requests.get(github_url) self.status_code = result.status_code if result.status_code == 200: result = result.json() self.title = result['title'] self.reporter = result['user']['login'] if result['assignee'] is not None: self.assignee = result['assignee']['login'] self.status = result['state'] self.created_at = result['created_at'] self.updated_at = result['updated_at'] self.closed_at = result['closed_at'] elif result.status_code == 404: self.title = 'private issue'
python
def retrieve_info(self): """Query the Github API to retrieve the needed infos.""" path = urlparse(self.url).path path = path.split('/')[1:] sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE) self.product = sanity_filter.match(path[0]).group(0) self.component = sanity_filter.match(path[1]).group(0) self.issue_id = int(path[3]) github_url = '%s/%s/%s/issues/%s' % (_URL_BASE, self.product, self.component, self.issue_id) result = requests.get(github_url) self.status_code = result.status_code if result.status_code == 200: result = result.json() self.title = result['title'] self.reporter = result['user']['login'] if result['assignee'] is not None: self.assignee = result['assignee']['login'] self.status = result['state'] self.created_at = result['created_at'] self.updated_at = result['updated_at'] self.closed_at = result['closed_at'] elif result.status_code == 404: self.title = 'private issue'
[ "def", "retrieve_info", "(", "self", ")", ":", "path", "=", "urlparse", "(", "self", ".", "url", ")", ".", "path", "path", "=", "path", ".", "split", "(", "'/'", ")", "[", "1", ":", "]", "sanity_filter", "=", "re", ".", "compile", "(", "'[\\da-z-_]+'", ",", "re", ".", "IGNORECASE", ")", "self", ".", "product", "=", "sanity_filter", ".", "match", "(", "path", "[", "0", "]", ")", ".", "group", "(", "0", ")", "self", ".", "component", "=", "sanity_filter", ".", "match", "(", "path", "[", "1", "]", ")", ".", "group", "(", "0", ")", "self", ".", "issue_id", "=", "int", "(", "path", "[", "3", "]", ")", "github_url", "=", "'%s/%s/%s/issues/%s'", "%", "(", "_URL_BASE", ",", "self", ".", "product", ",", "self", ".", "component", ",", "self", ".", "issue_id", ")", "result", "=", "requests", ".", "get", "(", "github_url", ")", "self", ".", "status_code", "=", "result", ".", "status_code", "if", "result", ".", "status_code", "==", "200", ":", "result", "=", "result", ".", "json", "(", ")", "self", ".", "title", "=", "result", "[", "'title'", "]", "self", ".", "reporter", "=", "result", "[", "'user'", "]", "[", "'login'", "]", "if", "result", "[", "'assignee'", "]", "is", "not", "None", ":", "self", ".", "assignee", "=", "result", "[", "'assignee'", "]", "[", "'login'", "]", "self", ".", "status", "=", "result", "[", "'state'", "]", "self", ".", "created_at", "=", "result", "[", "'created_at'", "]", "self", ".", "updated_at", "=", "result", "[", "'updated_at'", "]", "self", ".", "closed_at", "=", "result", "[", "'closed_at'", "]", "elif", "result", ".", "status_code", "==", "404", ":", "self", ".", "title", "=", "'private issue'" ]
Query the Github API to retrieve the needed infos.
[ "Query", "the", "Github", "API", "to", "retrieve", "the", "needed", "infos", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/trackers/github.py#L32-L62
train
danijar/sets
sets/core/step.py
Step.disk_cache
def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ @utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): return function(*args, **kwargs) return wrapper(*args, **kwargs)
python
def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ @utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): return function(*args, **kwargs) return wrapper(*args, **kwargs)
[ "def", "disk_cache", "(", "cls", ",", "basename", ",", "function", ",", "*", "args", ",", "method", "=", "True", ",", "*", "*", "kwargs", ")", ":", "@", "utility", ".", "disk_cache", "(", "basename", ",", "cls", ".", "directory", "(", ")", ",", "method", "=", "method", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Cache the return value in the correct cache directory. Set 'method' to false for static methods.
[ "Cache", "the", "return", "value", "in", "the", "correct", "cache", "directory", ".", "Set", "method", "to", "false", "for", "static", "methods", "." ]
2542c28f43d0af18932cb5b82f54ffb6ae557d12
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/core/step.py#L12-L21
train
danijar/sets
sets/core/step.py
Step.download
def download(cls, url, filename=None): """ Download a file into the correct cache directory. """ return utility.download(url, cls.directory(), filename)
python
def download(cls, url, filename=None): """ Download a file into the correct cache directory. """ return utility.download(url, cls.directory(), filename)
[ "def", "download", "(", "cls", ",", "url", ",", "filename", "=", "None", ")", ":", "return", "utility", ".", "download", "(", "url", ",", "cls", ".", "directory", "(", ")", ",", "filename", ")" ]
Download a file into the correct cache directory.
[ "Download", "a", "file", "into", "the", "correct", "cache", "directory", "." ]
2542c28f43d0af18932cb5b82f54ffb6ae557d12
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/core/step.py#L24-L28
train
danijar/sets
sets/core/step.py
Step.directory
def directory(cls, prefix=None): """ Path that should be used for caching. Different for all subclasses. """ prefix = prefix or utility.read_config().directory name = cls.__name__.lower() directory = os.path.expanduser(os.path.join(prefix, name)) utility.ensure_directory(directory) return directory
python
def directory(cls, prefix=None): """ Path that should be used for caching. Different for all subclasses. """ prefix = prefix or utility.read_config().directory name = cls.__name__.lower() directory = os.path.expanduser(os.path.join(prefix, name)) utility.ensure_directory(directory) return directory
[ "def", "directory", "(", "cls", ",", "prefix", "=", "None", ")", ":", "prefix", "=", "prefix", "or", "utility", ".", "read_config", "(", ")", ".", "directory", "name", "=", "cls", ".", "__name__", ".", "lower", "(", ")", "directory", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "prefix", ",", "name", ")", ")", "utility", ".", "ensure_directory", "(", "directory", ")", "return", "directory" ]
Path that should be used for caching. Different for all subclasses.
[ "Path", "that", "should", "be", "used", "for", "caching", ".", "Different", "for", "all", "subclasses", "." ]
2542c28f43d0af18932cb5b82f54ffb6ae557d12
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/core/step.py#L31-L39
train
redhat-cip/dci-control-server
dci/api/v1/remotecis.py
get_last_rconfiguration_id
def get_last_rconfiguration_id(topic_id, remoteci_id, db_conn=None): """Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci """ db_conn = db_conn or flask.g.db_conn __TABLE = models.JOBS query = sql.select([__TABLE.c.rconfiguration_id]). \ order_by(sql.desc(__TABLE.c.created_at)). \ where(sql.and_(__TABLE.c.topic_id == topic_id, __TABLE.c.remoteci_id == remoteci_id)). \ limit(1) rconfiguration_id = db_conn.execute(query).fetchone() if rconfiguration_id is not None: return str(rconfiguration_id[0]) else: return None
python
def get_last_rconfiguration_id(topic_id, remoteci_id, db_conn=None): """Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci """ db_conn = db_conn or flask.g.db_conn __TABLE = models.JOBS query = sql.select([__TABLE.c.rconfiguration_id]). \ order_by(sql.desc(__TABLE.c.created_at)). \ where(sql.and_(__TABLE.c.topic_id == topic_id, __TABLE.c.remoteci_id == remoteci_id)). \ limit(1) rconfiguration_id = db_conn.execute(query).fetchone() if rconfiguration_id is not None: return str(rconfiguration_id[0]) else: return None
[ "def", "get_last_rconfiguration_id", "(", "topic_id", ",", "remoteci_id", ",", "db_conn", "=", "None", ")", ":", "db_conn", "=", "db_conn", "or", "flask", ".", "g", ".", "db_conn", "__TABLE", "=", "models", ".", "JOBS", "query", "=", "sql", ".", "select", "(", "[", "__TABLE", ".", "c", ".", "rconfiguration_id", "]", ")", ".", "order_by", "(", "sql", ".", "desc", "(", "__TABLE", ".", "c", ".", "created_at", ")", ")", ".", "where", "(", "sql", ".", "and_", "(", "__TABLE", ".", "c", ".", "topic_id", "==", "topic_id", ",", "__TABLE", ".", "c", ".", "remoteci_id", "==", "remoteci_id", ")", ")", ".", "limit", "(", "1", ")", "rconfiguration_id", "=", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchone", "(", ")", "if", "rconfiguration_id", "is", "not", "None", ":", "return", "str", "(", "rconfiguration_id", "[", "0", "]", ")", "else", ":", "return", "None" ]
Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci
[ "Get", "the", "rconfiguration_id", "of", "the", "last", "job", "run", "by", "the", "remoteci", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/remotecis.py#L409-L427
train
redhat-cip/dci-control-server
dci/api/v1/remotecis.py
get_remoteci_configuration
def get_remoteci_configuration(topic_id, remoteci_id, db_conn=None): """Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.""" db_conn = db_conn or flask.g.db_conn last_rconfiguration_id = get_last_rconfiguration_id( topic_id, remoteci_id, db_conn=db_conn) _RCONFIGURATIONS = models.REMOTECIS_RCONFIGURATIONS _J_RCONFIGURATIONS = models.JOIN_REMOTECIS_RCONFIGURATIONS query = sql.select([_RCONFIGURATIONS]). \ select_from(_J_RCONFIGURATIONS. join(_RCONFIGURATIONS)). \ where(_J_RCONFIGURATIONS.c.remoteci_id == remoteci_id) query = query.where(sql.and_(_RCONFIGURATIONS.c.state != 'archived', _RCONFIGURATIONS.c.topic_id == topic_id)) query = query.order_by(sql.desc(_RCONFIGURATIONS.c.created_at)) query = query.order_by(sql.asc(_RCONFIGURATIONS.c.name)) all_rconfigurations = db_conn.execute(query).fetchall() if len(all_rconfigurations) > 0: for i in range(len(all_rconfigurations)): if str(all_rconfigurations[i]['id']) == last_rconfiguration_id: # if i==0, then indice -1 is the last element return all_rconfigurations[i - 1] return all_rconfigurations[0] else: return None
python
def get_remoteci_configuration(topic_id, remoteci_id, db_conn=None): """Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.""" db_conn = db_conn or flask.g.db_conn last_rconfiguration_id = get_last_rconfiguration_id( topic_id, remoteci_id, db_conn=db_conn) _RCONFIGURATIONS = models.REMOTECIS_RCONFIGURATIONS _J_RCONFIGURATIONS = models.JOIN_REMOTECIS_RCONFIGURATIONS query = sql.select([_RCONFIGURATIONS]). \ select_from(_J_RCONFIGURATIONS. join(_RCONFIGURATIONS)). \ where(_J_RCONFIGURATIONS.c.remoteci_id == remoteci_id) query = query.where(sql.and_(_RCONFIGURATIONS.c.state != 'archived', _RCONFIGURATIONS.c.topic_id == topic_id)) query = query.order_by(sql.desc(_RCONFIGURATIONS.c.created_at)) query = query.order_by(sql.asc(_RCONFIGURATIONS.c.name)) all_rconfigurations = db_conn.execute(query).fetchall() if len(all_rconfigurations) > 0: for i in range(len(all_rconfigurations)): if str(all_rconfigurations[i]['id']) == last_rconfiguration_id: # if i==0, then indice -1 is the last element return all_rconfigurations[i - 1] return all_rconfigurations[0] else: return None
[ "def", "get_remoteci_configuration", "(", "topic_id", ",", "remoteci_id", ",", "db_conn", "=", "None", ")", ":", "db_conn", "=", "db_conn", "or", "flask", ".", "g", ".", "db_conn", "last_rconfiguration_id", "=", "get_last_rconfiguration_id", "(", "topic_id", ",", "remoteci_id", ",", "db_conn", "=", "db_conn", ")", "_RCONFIGURATIONS", "=", "models", ".", "REMOTECIS_RCONFIGURATIONS", "_J_RCONFIGURATIONS", "=", "models", ".", "JOIN_REMOTECIS_RCONFIGURATIONS", "query", "=", "sql", ".", "select", "(", "[", "_RCONFIGURATIONS", "]", ")", ".", "select_from", "(", "_J_RCONFIGURATIONS", ".", "join", "(", "_RCONFIGURATIONS", ")", ")", ".", "where", "(", "_J_RCONFIGURATIONS", ".", "c", ".", "remoteci_id", "==", "remoteci_id", ")", "query", "=", "query", ".", "where", "(", "sql", ".", "and_", "(", "_RCONFIGURATIONS", ".", "c", ".", "state", "!=", "'archived'", ",", "_RCONFIGURATIONS", ".", "c", ".", "topic_id", "==", "topic_id", ")", ")", "query", "=", "query", ".", "order_by", "(", "sql", ".", "desc", "(", "_RCONFIGURATIONS", ".", "c", ".", "created_at", ")", ")", "query", "=", "query", ".", "order_by", "(", "sql", ".", "asc", "(", "_RCONFIGURATIONS", ".", "c", ".", "name", ")", ")", "all_rconfigurations", "=", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchall", "(", ")", "if", "len", "(", "all_rconfigurations", ")", ">", "0", ":", "for", "i", "in", "range", "(", "len", "(", "all_rconfigurations", ")", ")", ":", "if", "str", "(", "all_rconfigurations", "[", "i", "]", "[", "'id'", "]", ")", "==", "last_rconfiguration_id", ":", "# if i==0, then indice -1 is the last element", "return", "all_rconfigurations", "[", "i", "-", "1", "]", "return", "all_rconfigurations", "[", "0", "]", "else", ":", "return", "None" ]
Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.
[ "Get", "a", "remoteci", "configuration", ".", "This", "will", "iterate", "over", "each", "configuration", "in", "a", "round", "robin", "manner", "depending", "on", "the", "last", "rconfiguration", "used", "by", "the", "remoteci", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/remotecis.py#L430-L457
train
BrighterCommand/Brightside
brightside/command_processor.py
CommandProcessor.send
def send(self, request: Request) -> None: """ Dispatches a request. Expects one and one only target handler :param request: The request to dispatch :return: None, will throw a ConfigurationException if more than one handler factor is registered for the command """ handler_factories = self._registry.lookup(request) if len(handler_factories) != 1: raise ConfigurationException("There is no handler registered for this request") handler = handler_factories[0]() handler.handle(request)
python
def send(self, request: Request) -> None: """ Dispatches a request. Expects one and one only target handler :param request: The request to dispatch :return: None, will throw a ConfigurationException if more than one handler factor is registered for the command """ handler_factories = self._registry.lookup(request) if len(handler_factories) != 1: raise ConfigurationException("There is no handler registered for this request") handler = handler_factories[0]() handler.handle(request)
[ "def", "send", "(", "self", ",", "request", ":", "Request", ")", "->", "None", ":", "handler_factories", "=", "self", ".", "_registry", ".", "lookup", "(", "request", ")", "if", "len", "(", "handler_factories", ")", "!=", "1", ":", "raise", "ConfigurationException", "(", "\"There is no handler registered for this request\"", ")", "handler", "=", "handler_factories", "[", "0", "]", "(", ")", "handler", ".", "handle", "(", "request", ")" ]
Dispatches a request. Expects one and one only target handler :param request: The request to dispatch :return: None, will throw a ConfigurationException if more than one handler factor is registered for the command
[ "Dispatches", "a", "request", ".", "Expects", "one", "and", "one", "only", "target", "handler", ":", "param", "request", ":", "The", "request", "to", "dispatch", ":", "return", ":", "None", "will", "throw", "a", "ConfigurationException", "if", "more", "than", "one", "handler", "factor", "is", "registered", "for", "the", "command" ]
53b2f8323c3972609010a7386130249f3758f5fb
https://github.com/BrighterCommand/Brightside/blob/53b2f8323c3972609010a7386130249f3758f5fb/brightside/command_processor.py#L54-L65
train
BrighterCommand/Brightside
brightside/command_processor.py
CommandProcessor.publish
def publish(self, request: Request) -> None: """ Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: None. """ handler_factories = self._registry.lookup(request) for factory in handler_factories: handler = factory() handler.handle(request)
python
def publish(self, request: Request) -> None: """ Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: None. """ handler_factories = self._registry.lookup(request) for factory in handler_factories: handler = factory() handler.handle(request)
[ "def", "publish", "(", "self", ",", "request", ":", "Request", ")", "->", "None", ":", "handler_factories", "=", "self", ".", "_registry", ".", "lookup", "(", "request", ")", "for", "factory", "in", "handler_factories", ":", "handler", "=", "factory", "(", ")", "handler", ".", "handle", "(", "request", ")" ]
Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: None.
[ "Dispatches", "a", "request", ".", "Expects", "zero", "or", "more", "target", "handlers", ":", "param", "request", ":", "The", "request", "to", "dispatch", ":", "return", ":", "None", "." ]
53b2f8323c3972609010a7386130249f3758f5fb
https://github.com/BrighterCommand/Brightside/blob/53b2f8323c3972609010a7386130249f3758f5fb/brightside/command_processor.py#L67-L76
train
BrighterCommand/Brightside
brightside/command_processor.py
CommandProcessor.post
def post(self, request: Request) -> None: """ Dispatches a request over middleware. Returns when message put onto outgoing channel by producer, does not wait for response from a consuming application i.e. is fire-and-forget :param request: The request to dispatch :return: None """ if self._producer is None: raise ConfigurationException("Command Processor requires a BrightsideProducer to post to a Broker") if self._message_mapper_registry is None: raise ConfigurationException("Command Processor requires a BrightsideMessage Mapper Registry to post to a Broker") message_mapper = self._message_mapper_registry.lookup(request) message = message_mapper(request) self._message_store.add(message) self._producer.send(message)
python
def post(self, request: Request) -> None: """ Dispatches a request over middleware. Returns when message put onto outgoing channel by producer, does not wait for response from a consuming application i.e. is fire-and-forget :param request: The request to dispatch :return: None """ if self._producer is None: raise ConfigurationException("Command Processor requires a BrightsideProducer to post to a Broker") if self._message_mapper_registry is None: raise ConfigurationException("Command Processor requires a BrightsideMessage Mapper Registry to post to a Broker") message_mapper = self._message_mapper_registry.lookup(request) message = message_mapper(request) self._message_store.add(message) self._producer.send(message)
[ "def", "post", "(", "self", ",", "request", ":", "Request", ")", "->", "None", ":", "if", "self", ".", "_producer", "is", "None", ":", "raise", "ConfigurationException", "(", "\"Command Processor requires a BrightsideProducer to post to a Broker\"", ")", "if", "self", ".", "_message_mapper_registry", "is", "None", ":", "raise", "ConfigurationException", "(", "\"Command Processor requires a BrightsideMessage Mapper Registry to post to a Broker\"", ")", "message_mapper", "=", "self", ".", "_message_mapper_registry", ".", "lookup", "(", "request", ")", "message", "=", "message_mapper", "(", "request", ")", "self", ".", "_message_store", ".", "add", "(", "message", ")", "self", ".", "_producer", ".", "send", "(", "message", ")" ]
Dispatches a request over middleware. Returns when message put onto outgoing channel by producer, does not wait for response from a consuming application i.e. is fire-and-forget :param request: The request to dispatch :return: None
[ "Dispatches", "a", "request", "over", "middleware", ".", "Returns", "when", "message", "put", "onto", "outgoing", "channel", "by", "producer", "does", "not", "wait", "for", "response", "from", "a", "consuming", "application", "i", ".", "e", ".", "is", "fire", "-", "and", "-", "forget", ":", "param", "request", ":", "The", "request", "to", "dispatch", ":", "return", ":", "None" ]
53b2f8323c3972609010a7386130249f3758f5fb
https://github.com/BrighterCommand/Brightside/blob/53b2f8323c3972609010a7386130249f3758f5fb/brightside/command_processor.py#L78-L94
train
jmurty/xml4h
xml4h/impls/interface.py
XmlImplAdapter.ignore_whitespace_text_nodes
def ignore_whitespace_text_nodes(cls, wrapped_node): """ Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML document. """ for child in wrapped_node.children: if child.is_text and child.value.strip() == '': child.delete() else: cls.ignore_whitespace_text_nodes(child)
python
def ignore_whitespace_text_nodes(cls, wrapped_node): """ Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML document. """ for child in wrapped_node.children: if child.is_text and child.value.strip() == '': child.delete() else: cls.ignore_whitespace_text_nodes(child)
[ "def", "ignore_whitespace_text_nodes", "(", "cls", ",", "wrapped_node", ")", ":", "for", "child", "in", "wrapped_node", ".", "children", ":", "if", "child", ".", "is_text", "and", "child", ".", "value", ".", "strip", "(", ")", "==", "''", ":", "child", ".", "delete", "(", ")", "else", ":", "cls", ".", "ignore_whitespace_text_nodes", "(", "child", ")" ]
Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML document.
[ "Find", "and", "delete", "any", "text", "nodes", "containing", "nothing", "but", "whitespace", "in", "in", "the", "given", "node", "and", "its", "descendents", "." ]
adbb45e27a01a869a505aee7bc16bad2f517b511
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/impls/interface.py#L32-L44
train
jmurty/xml4h
xml4h/impls/interface.py
XmlImplAdapter.get_ns_info_from_node_name
def get_ns_info_from_node_name(self, name, impl_node): """ Return a three-element tuple with the prefix, local name, and namespace URI for the given element/attribute name (in the context of the given node's hierarchy). If the name has no associated prefix or namespace information, None is return for those tuple members. """ if '}' in name: ns_uri, name = name.split('}') ns_uri = ns_uri[1:] prefix = self.get_ns_prefix_for_uri(impl_node, ns_uri) elif ':' in name: prefix, name = name.split(':') ns_uri = self.get_ns_uri_for_prefix(impl_node, prefix) if ns_uri is None: raise exceptions.UnknownNamespaceException( "Prefix '%s' does not have a defined namespace URI" % prefix) else: prefix, ns_uri = None, None return prefix, name, ns_uri
python
def get_ns_info_from_node_name(self, name, impl_node): """ Return a three-element tuple with the prefix, local name, and namespace URI for the given element/attribute name (in the context of the given node's hierarchy). If the name has no associated prefix or namespace information, None is return for those tuple members. """ if '}' in name: ns_uri, name = name.split('}') ns_uri = ns_uri[1:] prefix = self.get_ns_prefix_for_uri(impl_node, ns_uri) elif ':' in name: prefix, name = name.split(':') ns_uri = self.get_ns_uri_for_prefix(impl_node, prefix) if ns_uri is None: raise exceptions.UnknownNamespaceException( "Prefix '%s' does not have a defined namespace URI" % prefix) else: prefix, ns_uri = None, None return prefix, name, ns_uri
[ "def", "get_ns_info_from_node_name", "(", "self", ",", "name", ",", "impl_node", ")", ":", "if", "'}'", "in", "name", ":", "ns_uri", ",", "name", "=", "name", ".", "split", "(", "'}'", ")", "ns_uri", "=", "ns_uri", "[", "1", ":", "]", "prefix", "=", "self", ".", "get_ns_prefix_for_uri", "(", "impl_node", ",", "ns_uri", ")", "elif", "':'", "in", "name", ":", "prefix", ",", "name", "=", "name", ".", "split", "(", "':'", ")", "ns_uri", "=", "self", ".", "get_ns_uri_for_prefix", "(", "impl_node", ",", "prefix", ")", "if", "ns_uri", "is", "None", ":", "raise", "exceptions", ".", "UnknownNamespaceException", "(", "\"Prefix '%s' does not have a defined namespace URI\"", "%", "prefix", ")", "else", ":", "prefix", ",", "ns_uri", "=", "None", ",", "None", "return", "prefix", ",", "name", ",", "ns_uri" ]
Return a three-element tuple with the prefix, local name, and namespace URI for the given element/attribute name (in the context of the given node's hierarchy). If the name has no associated prefix or namespace information, None is return for those tuple members.
[ "Return", "a", "three", "-", "element", "tuple", "with", "the", "prefix", "local", "name", "and", "namespace", "URI", "for", "the", "given", "element", "/", "attribute", "name", "(", "in", "the", "context", "of", "the", "given", "node", "s", "hierarchy", ")", ".", "If", "the", "name", "has", "no", "associated", "prefix", "or", "namespace", "information", "None", "is", "return", "for", "those", "tuple", "members", "." ]
adbb45e27a01a869a505aee7bc16bad2f517b511
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/impls/interface.py#L141-L161
train
jmurty/xml4h
xml4h/builder.py
Builder.up
def up(self, count=1, to_name=None): """ :return: a builder representing an ancestor of the current element, by default the parent element. :param count: return the n'th ancestor element; defaults to 1 which means the immediate parent. If *count* is greater than the number of number of ancestors return the document's root element. :type count: integer >= 1 or None :param to_name: return the nearest ancestor element with the matching name, or the document's root element if there are no matching elements. This argument trumps the ``count`` argument. :type to_name: string or None """ elem = self._element up_count = 0 while True: # Don't go up beyond the document root if elem.is_root or elem.parent is None: break elem = elem.parent if to_name is None: up_count += 1 if up_count >= count: break else: if elem.name == to_name: break return Builder(elem)
python
def up(self, count=1, to_name=None): """ :return: a builder representing an ancestor of the current element, by default the parent element. :param count: return the n'th ancestor element; defaults to 1 which means the immediate parent. If *count* is greater than the number of number of ancestors return the document's root element. :type count: integer >= 1 or None :param to_name: return the nearest ancestor element with the matching name, or the document's root element if there are no matching elements. This argument trumps the ``count`` argument. :type to_name: string or None """ elem = self._element up_count = 0 while True: # Don't go up beyond the document root if elem.is_root or elem.parent is None: break elem = elem.parent if to_name is None: up_count += 1 if up_count >= count: break else: if elem.name == to_name: break return Builder(elem)
[ "def", "up", "(", "self", ",", "count", "=", "1", ",", "to_name", "=", "None", ")", ":", "elem", "=", "self", ".", "_element", "up_count", "=", "0", "while", "True", ":", "# Don't go up beyond the document root", "if", "elem", ".", "is_root", "or", "elem", ".", "parent", "is", "None", ":", "break", "elem", "=", "elem", ".", "parent", "if", "to_name", "is", "None", ":", "up_count", "+=", "1", "if", "up_count", ">=", "count", ":", "break", "else", ":", "if", "elem", ".", "name", "==", "to_name", ":", "break", "return", "Builder", "(", "elem", ")" ]
:return: a builder representing an ancestor of the current element, by default the parent element. :param count: return the n'th ancestor element; defaults to 1 which means the immediate parent. If *count* is greater than the number of number of ancestors return the document's root element. :type count: integer >= 1 or None :param to_name: return the nearest ancestor element with the matching name, or the document's root element if there are no matching elements. This argument trumps the ``count`` argument. :type to_name: string or None
[ ":", "return", ":", "a", "builder", "representing", "an", "ancestor", "of", "the", "current", "element", "by", "default", "the", "parent", "element", "." ]
adbb45e27a01a869a505aee7bc16bad2f517b511
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/builder.py#L103-L131
train
jmurty/xml4h
xml4h/builder.py
Builder.element
def element(self, *args, **kwargs): """ Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`. """ child_element = self._element.add_element(*args, **kwargs) return Builder(child_element)
python
def element(self, *args, **kwargs): """ Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`. """ child_element = self._element.add_element(*args, **kwargs) return Builder(child_element)
[ "def", "element", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "child_element", "=", "self", ".", "_element", ".", "add_element", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "Builder", "(", "child_element", ")" ]
Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`.
[ "Add", "a", "child", "element", "to", "the", ":", "class", ":", "xml4h", ".", "nodes", ".", "Element", "node", "represented", "by", "this", "Builder", "." ]
adbb45e27a01a869a505aee7bc16bad2f517b511
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/builder.py#L159-L169
train
jmurty/xml4h
xml4h/builder.py
Builder.attributes
def attributes(self, *args, **kwargs): """ Add one or more attributes to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_attributes`. """ self._element.set_attributes(*args, **kwargs) return self
python
def attributes(self, *args, **kwargs): """ Add one or more attributes to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_attributes`. """ self._element.set_attributes(*args, **kwargs) return self
[ "def", "attributes", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_element", ".", "set_attributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self" ]
Add one or more attributes to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_attributes`.
[ "Add", "one", "or", "more", "attributes", "to", "the", ":", "class", ":", "xml4h", ".", "nodes", ".", "Element", "node", "represented", "by", "this", "Builder", "." ]
adbb45e27a01a869a505aee7bc16bad2f517b511
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/builder.py#L177-L187
train
jmurty/xml4h
xml4h/builder.py
Builder.processing_instruction
def processing_instruction(self, target, data): """ Add a processing instruction node to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.add_instruction`. """ self._element.add_instruction(target, data) return self
python
def processing_instruction(self, target, data): """ Add a processing instruction node to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.add_instruction`. """ self._element.add_instruction(target, data) return self
[ "def", "processing_instruction", "(", "self", ",", "target", ",", "data", ")", ":", "self", ".", "_element", ".", "add_instruction", "(", "target", ",", "data", ")", "return", "self" ]
Add a processing instruction node to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.add_instruction`.
[ "Add", "a", "processing", "instruction", "node", "to", "the", ":", "class", ":", "xml4h", ".", "nodes", ".", "Element", "node", "represented", "by", "this", "Builder", "." ]
adbb45e27a01a869a505aee7bc16bad2f517b511
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/builder.py#L225-L235
train
jmurty/xml4h
xml4h/builder.py
Builder.ns_prefix
def ns_prefix(self, prefix, ns_uri): """ Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`. """ self._element.set_ns_prefix(prefix, ns_uri) return self
python
def ns_prefix(self, prefix, ns_uri): """ Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`. """ self._element.set_ns_prefix(prefix, ns_uri) return self
[ "def", "ns_prefix", "(", "self", ",", "prefix", ",", "ns_uri", ")", ":", "self", ".", "_element", ".", "set_ns_prefix", "(", "prefix", ",", "ns_uri", ")", "return", "self" ]
Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`.
[ "Set", "the", "namespace", "prefix", "of", "the", ":", "class", ":", "xml4h", ".", "nodes", ".", "Element", "node", "represented", "by", "this", "Builder", "." ]
adbb45e27a01a869a505aee7bc16bad2f517b511
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/builder.py#L261-L271
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
createCertRequest
def createCertRequest(pkey, digest="sha256"): """ Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible arguments are: C - Country name ST - State or province name L - Locality name O - Organization name OU - Organizational unit name CN - Common name emailAddress - E-mail address Returns: The certificate request in an X509Req object """ req = crypto.X509Req() req.get_subject().C = "FR" req.get_subject().ST = "IDF" req.get_subject().L = "Paris" req.get_subject().O = "RedHat" # noqa req.get_subject().OU = "DCI" req.get_subject().CN = "DCI-remoteCI" req.set_pubkey(pkey) req.sign(pkey, digest) return req
python
def createCertRequest(pkey, digest="sha256"): """ Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible arguments are: C - Country name ST - State or province name L - Locality name O - Organization name OU - Organizational unit name CN - Common name emailAddress - E-mail address Returns: The certificate request in an X509Req object """ req = crypto.X509Req() req.get_subject().C = "FR" req.get_subject().ST = "IDF" req.get_subject().L = "Paris" req.get_subject().O = "RedHat" # noqa req.get_subject().OU = "DCI" req.get_subject().CN = "DCI-remoteCI" req.set_pubkey(pkey) req.sign(pkey, digest) return req
[ "def", "createCertRequest", "(", "pkey", ",", "digest", "=", "\"sha256\"", ")", ":", "req", "=", "crypto", ".", "X509Req", "(", ")", "req", ".", "get_subject", "(", ")", ".", "C", "=", "\"FR\"", "req", ".", "get_subject", "(", ")", ".", "ST", "=", "\"IDF\"", "req", ".", "get_subject", "(", ")", ".", "L", "=", "\"Paris\"", "req", ".", "get_subject", "(", ")", ".", "O", "=", "\"RedHat\"", "# noqa", "req", ".", "get_subject", "(", ")", ".", "OU", "=", "\"DCI\"", "req", ".", "get_subject", "(", ")", ".", "CN", "=", "\"DCI-remoteCI\"", "req", ".", "set_pubkey", "(", "pkey", ")", "req", ".", "sign", "(", "pkey", ",", "digest", ")", "return", "req" ]
Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible arguments are: C - Country name ST - State or province name L - Locality name O - Organization name OU - Organizational unit name CN - Common name emailAddress - E-mail address Returns: The certificate request in an X509Req object
[ "Create", "a", "certificate", "request", ".", "Arguments", ":", "pkey", "-", "The", "key", "to", "associate", "with", "the", "request", "digest", "-", "Digestion", "method", "to", "use", "for", "signing", "default", "is", "sha256", "**", "name", "-", "The", "name", "of", "the", "subject", "of", "the", "request", "possible", "arguments", "are", ":", "C", "-", "Country", "name", "ST", "-", "State", "or", "province", "name", "L", "-", "Locality", "name", "O", "-", "Organization", "name", "OU", "-", "Organizational", "unit", "name", "CN", "-", "Common", "name", "emailAddress", "-", "E", "-", "mail", "address", "Returns", ":", "The", "certificate", "request", "in", "an", "X509Req", "object" ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L41-L68
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
verify_existence_and_get
def verify_existence_and_get(id, table, name=None, get_id=False): """Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the row to look for :param get_id: if True, return only the ID :return: """ where_clause = table.c.id == id if name: where_clause = table.c.name == name if 'state' in table.columns: where_clause = sql.and_(table.c.state != 'archived', where_clause) query = sql.select([table]).where(where_clause) result = flask.g.db_conn.execute(query).fetchone() if result is None: raise dci_exc.DCIException('Resource "%s" not found.' % id, status_code=404) if get_id: return result.id return result
python
def verify_existence_and_get(id, table, name=None, get_id=False): """Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the row to look for :param get_id: if True, return only the ID :return: """ where_clause = table.c.id == id if name: where_clause = table.c.name == name if 'state' in table.columns: where_clause = sql.and_(table.c.state != 'archived', where_clause) query = sql.select([table]).where(where_clause) result = flask.g.db_conn.execute(query).fetchone() if result is None: raise dci_exc.DCIException('Resource "%s" not found.' % id, status_code=404) if get_id: return result.id return result
[ "def", "verify_existence_and_get", "(", "id", ",", "table", ",", "name", "=", "None", ",", "get_id", "=", "False", ")", ":", "where_clause", "=", "table", ".", "c", ".", "id", "==", "id", "if", "name", ":", "where_clause", "=", "table", ".", "c", ".", "name", "==", "name", "if", "'state'", "in", "table", ".", "columns", ":", "where_clause", "=", "sql", ".", "and_", "(", "table", ".", "c", ".", "state", "!=", "'archived'", ",", "where_clause", ")", "query", "=", "sql", ".", "select", "(", "[", "table", "]", ")", ".", "where", "(", "where_clause", ")", "result", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchone", "(", ")", "if", "result", "is", "None", ":", "raise", "dci_exc", ".", "DCIException", "(", "'Resource \"%s\" not found.'", "%", "id", ",", "status_code", "=", "404", ")", "if", "get_id", ":", "return", "result", ".", "id", "return", "result" ]
Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the row to look for :param get_id: if True, return only the ID :return:
[ "Verify", "the", "existence", "of", "a", "resource", "in", "the", "database", "and", "then", "return", "it", "if", "it", "exists", "according", "to", "the", "condition", "or", "raise", "an", "exception", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L91-L118
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
user_topic_ids
def user_topic_ids(user): """Retrieve the list of topics IDs a user has access to.""" if user.is_super_admin() or user.is_read_only_user(): query = sql.select([models.TOPICS]) else: query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id]) .select_from( models.JOINS_TOPICS_TEAMS.join( models.TOPICS, sql.and_(models.JOINS_TOPICS_TEAMS.c.topic_id == models.TOPICS.c.id, # noqa models.TOPICS.c.state == 'active')) # noqa ).where( sql.or_(models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.teams_ids), # noqa models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.child_teams_ids)))) # noqa rows = flask.g.db_conn.execute(query).fetchall() return [str(row[0]) for row in rows]
python
def user_topic_ids(user): """Retrieve the list of topics IDs a user has access to.""" if user.is_super_admin() or user.is_read_only_user(): query = sql.select([models.TOPICS]) else: query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id]) .select_from( models.JOINS_TOPICS_TEAMS.join( models.TOPICS, sql.and_(models.JOINS_TOPICS_TEAMS.c.topic_id == models.TOPICS.c.id, # noqa models.TOPICS.c.state == 'active')) # noqa ).where( sql.or_(models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.teams_ids), # noqa models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.child_teams_ids)))) # noqa rows = flask.g.db_conn.execute(query).fetchall() return [str(row[0]) for row in rows]
[ "def", "user_topic_ids", "(", "user", ")", ":", "if", "user", ".", "is_super_admin", "(", ")", "or", "user", ".", "is_read_only_user", "(", ")", ":", "query", "=", "sql", ".", "select", "(", "[", "models", ".", "TOPICS", "]", ")", "else", ":", "query", "=", "(", "sql", ".", "select", "(", "[", "models", ".", "JOINS_TOPICS_TEAMS", ".", "c", ".", "topic_id", "]", ")", ".", "select_from", "(", "models", ".", "JOINS_TOPICS_TEAMS", ".", "join", "(", "models", ".", "TOPICS", ",", "sql", ".", "and_", "(", "models", ".", "JOINS_TOPICS_TEAMS", ".", "c", ".", "topic_id", "==", "models", ".", "TOPICS", ".", "c", ".", "id", ",", "# noqa", "models", ".", "TOPICS", ".", "c", ".", "state", "==", "'active'", ")", ")", "# noqa", ")", ".", "where", "(", "sql", ".", "or_", "(", "models", ".", "JOINS_TOPICS_TEAMS", ".", "c", ".", "team_id", ".", "in_", "(", "user", ".", "teams_ids", ")", ",", "# noqa", "models", ".", "JOINS_TOPICS_TEAMS", ".", "c", ".", "team_id", ".", "in_", "(", "user", ".", "child_teams_ids", ")", ")", ")", ")", "# noqa", "rows", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchall", "(", ")", "return", "[", "str", "(", "row", "[", "0", "]", ")", "for", "row", "in", "rows", "]" ]
Retrieve the list of topics IDs a user has access to.
[ "Retrieve", "the", "list", "of", "topics", "IDs", "a", "user", "has", "access", "to", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L121-L137
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
verify_team_in_topic
def verify_team_in_topic(user, topic_id): """Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics. """ if user.is_super_admin() or user.is_read_only_user(): return if str(topic_id) not in user_topic_ids(user): raise dci_exc.Unauthorized()
python
def verify_team_in_topic(user, topic_id): """Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics. """ if user.is_super_admin() or user.is_read_only_user(): return if str(topic_id) not in user_topic_ids(user): raise dci_exc.Unauthorized()
[ "def", "verify_team_in_topic", "(", "user", ",", "topic_id", ")", ":", "if", "user", ".", "is_super_admin", "(", ")", "or", "user", ".", "is_read_only_user", "(", ")", ":", "return", "if", "str", "(", "topic_id", ")", "not", "in", "user_topic_ids", "(", "user", ")", ":", "raise", "dci_exc", ".", "Unauthorized", "(", ")" ]
Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics.
[ "Verify", "that", "the", "user", "s", "team", "does", "belongs", "to", "the", "given", "topic", ".", "If", "the", "user", "is", "an", "admin", "or", "read", "only", "user", "then", "it", "belongs", "to", "all", "topics", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L140-L147
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
_format_level_1
def _format_level_1(rows, root_table_name): """ Transform sqlalchemy source: [{'a_id' : 'id1', 'a_name' : 'name1, 'b_id' : 'id2', 'b_name' : 'name2}, {'a_id' : 'id3', 'a_name' : 'name3, 'b_id' : 'id4', 'b_name' : 'name4} ] to [{'id' : 'id1', 'name': 'name2', 'b' : {'id': 'id2', 'name': 'name2'}, {'id' : 'id3', 'name': 'name3', 'b' : {'id': 'id4', 'name': 'name4'} ] """ result_rows = [] for row in rows: row = dict(row) result_row = {} prefixes_to_remove = [] for field in row: if field.startswith('next_topic'): prefix = 'next_topic' suffix = field[11:] if suffix == 'id_1': suffix = 'id' else: prefix, suffix = field.split('_', 1) if suffix == 'id' and row[field] is None: prefixes_to_remove.append(prefix) if prefix not in result_row: result_row[prefix] = {suffix: row[field]} else: result_row[prefix].update({suffix: row[field]}) # remove field with id == null for prefix_to_remove in prefixes_to_remove: result_row.pop(prefix_to_remove) root_table_fields = result_row.pop(root_table_name) result_row.update(root_table_fields) result_rows.append(result_row) return result_rows
python
def _format_level_1(rows, root_table_name): """ Transform sqlalchemy source: [{'a_id' : 'id1', 'a_name' : 'name1, 'b_id' : 'id2', 'b_name' : 'name2}, {'a_id' : 'id3', 'a_name' : 'name3, 'b_id' : 'id4', 'b_name' : 'name4} ] to [{'id' : 'id1', 'name': 'name2', 'b' : {'id': 'id2', 'name': 'name2'}, {'id' : 'id3', 'name': 'name3', 'b' : {'id': 'id4', 'name': 'name4'} ] """ result_rows = [] for row in rows: row = dict(row) result_row = {} prefixes_to_remove = [] for field in row: if field.startswith('next_topic'): prefix = 'next_topic' suffix = field[11:] if suffix == 'id_1': suffix = 'id' else: prefix, suffix = field.split('_', 1) if suffix == 'id' and row[field] is None: prefixes_to_remove.append(prefix) if prefix not in result_row: result_row[prefix] = {suffix: row[field]} else: result_row[prefix].update({suffix: row[field]}) # remove field with id == null for prefix_to_remove in prefixes_to_remove: result_row.pop(prefix_to_remove) root_table_fields = result_row.pop(root_table_name) result_row.update(root_table_fields) result_rows.append(result_row) return result_rows
[ "def", "_format_level_1", "(", "rows", ",", "root_table_name", ")", ":", "result_rows", "=", "[", "]", "for", "row", "in", "rows", ":", "row", "=", "dict", "(", "row", ")", "result_row", "=", "{", "}", "prefixes_to_remove", "=", "[", "]", "for", "field", "in", "row", ":", "if", "field", ".", "startswith", "(", "'next_topic'", ")", ":", "prefix", "=", "'next_topic'", "suffix", "=", "field", "[", "11", ":", "]", "if", "suffix", "==", "'id_1'", ":", "suffix", "=", "'id'", "else", ":", "prefix", ",", "suffix", "=", "field", ".", "split", "(", "'_'", ",", "1", ")", "if", "suffix", "==", "'id'", "and", "row", "[", "field", "]", "is", "None", ":", "prefixes_to_remove", ".", "append", "(", "prefix", ")", "if", "prefix", "not", "in", "result_row", ":", "result_row", "[", "prefix", "]", "=", "{", "suffix", ":", "row", "[", "field", "]", "}", "else", ":", "result_row", "[", "prefix", "]", ".", "update", "(", "{", "suffix", ":", "row", "[", "field", "]", "}", ")", "# remove field with id == null", "for", "prefix_to_remove", "in", "prefixes_to_remove", ":", "result_row", ".", "pop", "(", "prefix_to_remove", ")", "root_table_fields", "=", "result_row", ".", "pop", "(", "root_table_name", ")", "result_row", ".", "update", "(", "root_table_fields", ")", "result_rows", ".", "append", "(", "result_row", ")", "return", "result_rows" ]
Transform sqlalchemy source: [{'a_id' : 'id1', 'a_name' : 'name1, 'b_id' : 'id2', 'b_name' : 'name2}, {'a_id' : 'id3', 'a_name' : 'name3, 'b_id' : 'id4', 'b_name' : 'name4} ] to [{'id' : 'id1', 'name': 'name2', 'b' : {'id': 'id2', 'name': 'name2'}, {'id' : 'id3', 'name': 'name3', 'b' : {'id': 'id4', 'name': 'name4'} ]
[ "Transform", "sqlalchemy", "source", ":", "[", "{", "a_id", ":", "id1", "a_name", ":", "name1", "b_id", ":", "id2", "b_name", ":", "name2", "}", "{", "a_id", ":", "id3", "a_name", ":", "name3", "b_id", ":", "id4", "b_name", ":", "name4", "}", "]", "to", "[", "{", "id", ":", "id1", "name", ":", "name2", "b", ":", "{", "id", ":", "id2", "name", ":", "name2", "}", "{", "id", ":", "id3", "name", ":", "name3", "b", ":", "{", "id", ":", "id4", "name", ":", "name4", "}", "]" ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L417-L463
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
_format_level_2
def _format_level_2(rows, list_embeds, embed_many): """ From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as join result. For example: [{'id' : 'id1', 'name' : 'name1, 'b' : {'id': 'id2, 'name': 'name2'} } {'id' : 'id1', 'name' : 'name1, 'b' : {'id' : 'id4', 'name' : 'name4} } ] Here there is two elements which correspond to one rows because of the embed field 'b'. So we should transform it to: [{'id' : 'id1', 'name' : 'name1, 'b' : [{'id': 'id2, 'name': 'name2'}, {'id' : 'id4', 'name' : 'name4}] } ] This is the purpose of this function. """ def _uniqify_list(list_of_dicts): # list() for py34 result = [] set_ids = set() for v in list_of_dicts: if v['id'] in set_ids: continue set_ids.add(v['id']) result.append(v) return result row_ids_to_embed_values = {} for row in rows: # for each row, associate rows's id -> {all embeds values} if row['id'] not in row_ids_to_embed_values: row_ids_to_embed_values[row['id']] = {} # add embeds values to the current row for embd in list_embeds: if embd not in row: continue if embd not in row_ids_to_embed_values[row['id']]: # create a list or a dict depending on embed_many if embed_many[embd]: row_ids_to_embed_values[row['id']][embd] = [row[embd]] else: row_ids_to_embed_values[row['id']][embd] = row[embd] else: if embed_many[embd]: row_ids_to_embed_values[row['id']][embd].append(row[embd]) # uniqify each embed list for embd in list_embeds: if embd in row_ids_to_embed_values[row['id']]: embed_values = row_ids_to_embed_values[row['id']][embd] if isinstance(embed_values, list): row_ids_to_embed_values[row['id']][embd] = _uniqify_list(embed_values) # noqa else: row_ids_to_embed_values[row['id']][embd] = {} if embed_many[embd]: row_ids_to_embed_values[row['id']][embd] = [] # last loop over the initial rows in order to keep the ordering result = [] # if row id in seen set then it means the row has been completely processed seen = set() for row in rows: if row['id'] in seen: continue seen.add(row['id']) new_row = {} # adds level 1 fields for field in row: if field not in list_embeds: new_row[field] = row[field] # adds all level 2 fields # list() for py34 row_ids_to_embed_values_keys = list(row_ids_to_embed_values[new_row['id']].keys()) # noqa row_ids_to_embed_values_keys.sort() # adds the nested fields if there is somes for embd in list_embeds: if embd in row_ids_to_embed_values_keys: if '.' in embd: prefix, suffix = embd.split('.', 1) new_row[prefix][suffix] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new_row[embd] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new_row_embd_value = {} if embed_many[embd]: new_row_embd_value = [] if '.' in embd: prefix, suffix = embd.split('.', 1) new_row[prefix][suffix] = new_row_embd_value else: new_row[embd] = new_row_embd_value # row is complete ! result.append(new_row) return result
python
def _format_level_2(rows, list_embeds, embed_many): """ From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as join result. For example: [{'id' : 'id1', 'name' : 'name1, 'b' : {'id': 'id2, 'name': 'name2'} } {'id' : 'id1', 'name' : 'name1, 'b' : {'id' : 'id4', 'name' : 'name4} } ] Here there is two elements which correspond to one rows because of the embed field 'b'. So we should transform it to: [{'id' : 'id1', 'name' : 'name1, 'b' : [{'id': 'id2, 'name': 'name2'}, {'id' : 'id4', 'name' : 'name4}] } ] This is the purpose of this function. """ def _uniqify_list(list_of_dicts): # list() for py34 result = [] set_ids = set() for v in list_of_dicts: if v['id'] in set_ids: continue set_ids.add(v['id']) result.append(v) return result row_ids_to_embed_values = {} for row in rows: # for each row, associate rows's id -> {all embeds values} if row['id'] not in row_ids_to_embed_values: row_ids_to_embed_values[row['id']] = {} # add embeds values to the current row for embd in list_embeds: if embd not in row: continue if embd not in row_ids_to_embed_values[row['id']]: # create a list or a dict depending on embed_many if embed_many[embd]: row_ids_to_embed_values[row['id']][embd] = [row[embd]] else: row_ids_to_embed_values[row['id']][embd] = row[embd] else: if embed_many[embd]: row_ids_to_embed_values[row['id']][embd].append(row[embd]) # uniqify each embed list for embd in list_embeds: if embd in row_ids_to_embed_values[row['id']]: embed_values = row_ids_to_embed_values[row['id']][embd] if isinstance(embed_values, list): row_ids_to_embed_values[row['id']][embd] = _uniqify_list(embed_values) # noqa else: row_ids_to_embed_values[row['id']][embd] = {} if embed_many[embd]: row_ids_to_embed_values[row['id']][embd] = [] # last loop over the initial rows in order to keep the ordering result = [] # if row id in seen set then it means the row has been completely processed seen = set() for row in rows: if row['id'] in seen: continue seen.add(row['id']) new_row = {} # adds level 1 fields for field in row: if field not in list_embeds: new_row[field] = row[field] # adds all level 2 fields # list() for py34 row_ids_to_embed_values_keys = list(row_ids_to_embed_values[new_row['id']].keys()) # noqa row_ids_to_embed_values_keys.sort() # adds the nested fields if there is somes for embd in list_embeds: if embd in row_ids_to_embed_values_keys: if '.' in embd: prefix, suffix = embd.split('.', 1) new_row[prefix][suffix] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new_row[embd] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new_row_embd_value = {} if embed_many[embd]: new_row_embd_value = [] if '.' in embd: prefix, suffix = embd.split('.', 1) new_row[prefix][suffix] = new_row_embd_value else: new_row[embd] = new_row_embd_value # row is complete ! result.append(new_row) return result
[ "def", "_format_level_2", "(", "rows", ",", "list_embeds", ",", "embed_many", ")", ":", "def", "_uniqify_list", "(", "list_of_dicts", ")", ":", "# list() for py34", "result", "=", "[", "]", "set_ids", "=", "set", "(", ")", "for", "v", "in", "list_of_dicts", ":", "if", "v", "[", "'id'", "]", "in", "set_ids", ":", "continue", "set_ids", ".", "add", "(", "v", "[", "'id'", "]", ")", "result", ".", "append", "(", "v", ")", "return", "result", "row_ids_to_embed_values", "=", "{", "}", "for", "row", "in", "rows", ":", "# for each row, associate rows's id -> {all embeds values}", "if", "row", "[", "'id'", "]", "not", "in", "row_ids_to_embed_values", ":", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "=", "{", "}", "# add embeds values to the current row", "for", "embd", "in", "list_embeds", ":", "if", "embd", "not", "in", "row", ":", "continue", "if", "embd", "not", "in", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", ":", "# create a list or a dict depending on embed_many", "if", "embed_many", "[", "embd", "]", ":", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "[", "embd", "]", "=", "[", "row", "[", "embd", "]", "]", "else", ":", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "[", "embd", "]", "=", "row", "[", "embd", "]", "else", ":", "if", "embed_many", "[", "embd", "]", ":", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "[", "embd", "]", ".", "append", "(", "row", "[", "embd", "]", ")", "# uniqify each embed list", "for", "embd", "in", "list_embeds", ":", "if", "embd", "in", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", ":", "embed_values", "=", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "[", "embd", "]", "if", "isinstance", "(", "embed_values", ",", "list", ")", ":", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "[", "embd", "]", "=", "_uniqify_list", "(", "embed_values", ")", "# noqa", "else", ":", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "[", "embd", "]", "=", "{", "}", "if", "embed_many", "[", "embd", "]", ":", "row_ids_to_embed_values", "[", "row", "[", "'id'", "]", "]", "[", "embd", "]", "=", "[", "]", "# last loop over the initial rows in order to keep the ordering", "result", "=", "[", "]", "# if row id in seen set then it means the row has been completely processed", "seen", "=", "set", "(", ")", "for", "row", "in", "rows", ":", "if", "row", "[", "'id'", "]", "in", "seen", ":", "continue", "seen", ".", "add", "(", "row", "[", "'id'", "]", ")", "new_row", "=", "{", "}", "# adds level 1 fields", "for", "field", "in", "row", ":", "if", "field", "not", "in", "list_embeds", ":", "new_row", "[", "field", "]", "=", "row", "[", "field", "]", "# adds all level 2 fields", "# list() for py34", "row_ids_to_embed_values_keys", "=", "list", "(", "row_ids_to_embed_values", "[", "new_row", "[", "'id'", "]", "]", ".", "keys", "(", ")", ")", "# noqa", "row_ids_to_embed_values_keys", ".", "sort", "(", ")", "# adds the nested fields if there is somes", "for", "embd", "in", "list_embeds", ":", "if", "embd", "in", "row_ids_to_embed_values_keys", ":", "if", "'.'", "in", "embd", ":", "prefix", ",", "suffix", "=", "embd", ".", "split", "(", "'.'", ",", "1", ")", "new_row", "[", "prefix", "]", "[", "suffix", "]", "=", "row_ids_to_embed_values", "[", "new_row", "[", "'id'", "]", "]", "[", "embd", "]", "# noqa", "else", ":", "new_row", "[", "embd", "]", "=", "row_ids_to_embed_values", "[", "new_row", "[", "'id'", "]", "]", "[", "embd", "]", "# noqa", "else", ":", "new_row_embd_value", "=", "{", "}", "if", "embed_many", "[", "embd", "]", ":", "new_row_embd_value", "=", "[", "]", "if", "'.'", "in", "embd", ":", "prefix", ",", "suffix", "=", "embd", ".", "split", "(", "'.'", ",", "1", ")", "new_row", "[", "prefix", "]", "[", "suffix", "]", "=", "new_row_embd_value", "else", ":", "new_row", "[", "embd", "]", "=", "new_row_embd_value", "# row is complete !", "result", ".", "append", "(", "new_row", ")", "return", "result" ]
From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as join result. For example: [{'id' : 'id1', 'name' : 'name1, 'b' : {'id': 'id2, 'name': 'name2'} } {'id' : 'id1', 'name' : 'name1, 'b' : {'id' : 'id4', 'name' : 'name4} } ] Here there is two elements which correspond to one rows because of the embed field 'b'. So we should transform it to: [{'id' : 'id1', 'name' : 'name1, 'b' : [{'id': 'id2, 'name': 'name2'}, {'id' : 'id4', 'name' : 'name4}] } ] This is the purpose of this function.
[ "From", "the", "_format_level_1", "function", "we", "have", "a", "list", "of", "rows", ".", "Because", "of", "using", "joins", "we", "have", "as", "many", "rows", "as", "join", "result", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L466-L575
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
common_values_dict
def common_values_dict(): """Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. """ now = datetime.datetime.utcnow().isoformat() etag = utils.gen_etag() values = { 'id': utils.gen_uuid(), 'created_at': now, 'updated_at': now, 'etag': etag } return values
python
def common_values_dict(): """Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. """ now = datetime.datetime.utcnow().isoformat() etag = utils.gen_etag() values = { 'id': utils.gen_uuid(), 'created_at': now, 'updated_at': now, 'etag': etag } return values
[ "def", "common_values_dict", "(", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", "etag", "=", "utils", ".", "gen_etag", "(", ")", "values", "=", "{", "'id'", ":", "utils", ".", "gen_uuid", "(", ")", ",", "'created_at'", ":", "now", ",", "'updated_at'", ":", "now", ",", "'etag'", ":", "etag", "}", "return", "values" ]
Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place.
[ "Build", "a", "basic", "values", "object", "used", "in", "every", "create", "method", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L586-L602
train
redhat-cip/dci-control-server
dci/api/v1/utils.py
QueryBuilder.execute
def execute(self, fetchall=False, fetchone=False, use_labels=True): """ :param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return: """ query = self.get_query(use_labels=use_labels) if fetchall: return flask.g.db_conn.execute(query).fetchall() elif fetchone: return flask.g.db_conn.execute(query).fetchone()
python
def execute(self, fetchall=False, fetchone=False, use_labels=True): """ :param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return: """ query = self.get_query(use_labels=use_labels) if fetchall: return flask.g.db_conn.execute(query).fetchall() elif fetchone: return flask.g.db_conn.execute(query).fetchone()
[ "def", "execute", "(", "self", ",", "fetchall", "=", "False", ",", "fetchone", "=", "False", ",", "use_labels", "=", "True", ")", ":", "query", "=", "self", ".", "get_query", "(", "use_labels", "=", "use_labels", ")", "if", "fetchall", ":", "return", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchall", "(", ")", "elif", "fetchone", ":", "return", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchone", "(", ")" ]
:param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return:
[ ":", "param", "fetchall", ":", "get", "all", "rows", ":", "param", "fetchone", ":", "get", "only", "one", "row", ":", "param", "use_labels", ":", "prefix", "row", "columns", "names", "by", "the", "table", "name", ":", "return", ":" ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/utils.py#L399-L410
train
redhat-cip/dci-control-server
dci/api/v1/identity.py
get_identity
def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( json.dumps( { 'identity': { 'id': identity.id, 'etag': identity.etag, 'name': identity.name, 'fullname': identity.fullname, 'email': identity.email, 'timezone': identity.timezone, 'teams': _encode_dict(identity.teams) } } ), 200, headers={'ETag': identity.etag}, content_type='application/json' )
python
def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( json.dumps( { 'identity': { 'id': identity.id, 'etag': identity.etag, 'name': identity.name, 'fullname': identity.fullname, 'email': identity.email, 'timezone': identity.timezone, 'teams': _encode_dict(identity.teams) } } ), 200, headers={'ETag': identity.etag}, content_type='application/json' )
[ "def", "get_identity", "(", "identity", ")", ":", "return", "flask", ".", "Response", "(", "json", ".", "dumps", "(", "{", "'identity'", ":", "{", "'id'", ":", "identity", ".", "id", ",", "'etag'", ":", "identity", ".", "etag", ",", "'name'", ":", "identity", ".", "name", ",", "'fullname'", ":", "identity", ".", "fullname", ",", "'email'", ":", "identity", ".", "email", ",", "'timezone'", ":", "identity", ".", "timezone", ",", "'teams'", ":", "_encode_dict", "(", "identity", ".", "teams", ")", "}", "}", ")", ",", "200", ",", "headers", "=", "{", "'ETag'", ":", "identity", ".", "etag", "}", ",", "content_type", "=", "'application/json'", ")" ]
Returns some information about the currently authenticated identity
[ "Returns", "some", "information", "about", "the", "currently", "authenticated", "identity" ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/identity.py#L36-L54
train
redhat-cip/dci-control-server
dci/api/v1/issues.py
get_issues_by_resource
def get_issues_by_resource(resource_id, table): """Get all issues for a specific job.""" v1_utils.verify_existence_and_get(resource_id, table) # When retrieving the issues for a job, we actually retrieve # the issues attach to the job itself + the issues attached to # the components the job has been run with. if table.name == 'jobs': JJI = models.JOIN_JOBS_ISSUES JJC = models.JOIN_JOBS_COMPONENTS JCI = models.JOIN_COMPONENTS_ISSUES # Get all the issues attach to all the components attach to a job j1 = sql.join( _TABLE, sql.join( JCI, JJC, sql.and_( JCI.c.component_id == JJC.c.component_id, JJC.c.job_id == resource_id, ), ), _TABLE.c.id == JCI.c.issue_id, ) query = sql.select([_TABLE]).select_from(j1) rows = flask.g.db_conn.execute(query) rows = [dict(row) for row in rows] # Get all the issues attach to a job j2 = sql.join( _TABLE, JJI, sql.and_( _TABLE.c.id == JJI.c.issue_id, JJI.c.job_id == resource_id ) ) query2 = sql.select([_TABLE]).select_from(j2) rows2 = flask.g.db_conn.execute(query2) rows += [dict(row) for row in rows2] # When retrieving the issues for a component, we only retrieve the # issues attached to the specified component. else: JCI = models.JOIN_COMPONENTS_ISSUES query = (sql.select([_TABLE]) .select_from(JCI.join(_TABLE)) .where(JCI.c.component_id == resource_id)) rows = flask.g.db_conn.execute(query) rows = [dict(row) for row in rows] for row in rows: if row['tracker'] == 'github': l_tracker = github.Github(row['url']) elif row['tracker'] == 'bugzilla': l_tracker = bugzilla.Bugzilla(row['url']) row.update(l_tracker.dump()) return flask.jsonify({'issues': rows, '_meta': {'count': len(rows)}})
python
def get_issues_by_resource(resource_id, table): """Get all issues for a specific job.""" v1_utils.verify_existence_and_get(resource_id, table) # When retrieving the issues for a job, we actually retrieve # the issues attach to the job itself + the issues attached to # the components the job has been run with. if table.name == 'jobs': JJI = models.JOIN_JOBS_ISSUES JJC = models.JOIN_JOBS_COMPONENTS JCI = models.JOIN_COMPONENTS_ISSUES # Get all the issues attach to all the components attach to a job j1 = sql.join( _TABLE, sql.join( JCI, JJC, sql.and_( JCI.c.component_id == JJC.c.component_id, JJC.c.job_id == resource_id, ), ), _TABLE.c.id == JCI.c.issue_id, ) query = sql.select([_TABLE]).select_from(j1) rows = flask.g.db_conn.execute(query) rows = [dict(row) for row in rows] # Get all the issues attach to a job j2 = sql.join( _TABLE, JJI, sql.and_( _TABLE.c.id == JJI.c.issue_id, JJI.c.job_id == resource_id ) ) query2 = sql.select([_TABLE]).select_from(j2) rows2 = flask.g.db_conn.execute(query2) rows += [dict(row) for row in rows2] # When retrieving the issues for a component, we only retrieve the # issues attached to the specified component. else: JCI = models.JOIN_COMPONENTS_ISSUES query = (sql.select([_TABLE]) .select_from(JCI.join(_TABLE)) .where(JCI.c.component_id == resource_id)) rows = flask.g.db_conn.execute(query) rows = [dict(row) for row in rows] for row in rows: if row['tracker'] == 'github': l_tracker = github.Github(row['url']) elif row['tracker'] == 'bugzilla': l_tracker = bugzilla.Bugzilla(row['url']) row.update(l_tracker.dump()) return flask.jsonify({'issues': rows, '_meta': {'count': len(rows)}})
[ "def", "get_issues_by_resource", "(", "resource_id", ",", "table", ")", ":", "v1_utils", ".", "verify_existence_and_get", "(", "resource_id", ",", "table", ")", "# When retrieving the issues for a job, we actually retrieve", "# the issues attach to the job itself + the issues attached to", "# the components the job has been run with.", "if", "table", ".", "name", "==", "'jobs'", ":", "JJI", "=", "models", ".", "JOIN_JOBS_ISSUES", "JJC", "=", "models", ".", "JOIN_JOBS_COMPONENTS", "JCI", "=", "models", ".", "JOIN_COMPONENTS_ISSUES", "# Get all the issues attach to all the components attach to a job", "j1", "=", "sql", ".", "join", "(", "_TABLE", ",", "sql", ".", "join", "(", "JCI", ",", "JJC", ",", "sql", ".", "and_", "(", "JCI", ".", "c", ".", "component_id", "==", "JJC", ".", "c", ".", "component_id", ",", "JJC", ".", "c", ".", "job_id", "==", "resource_id", ",", ")", ",", ")", ",", "_TABLE", ".", "c", ".", "id", "==", "JCI", ".", "c", ".", "issue_id", ",", ")", "query", "=", "sql", ".", "select", "(", "[", "_TABLE", "]", ")", ".", "select_from", "(", "j1", ")", "rows", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", "rows", "=", "[", "dict", "(", "row", ")", "for", "row", "in", "rows", "]", "# Get all the issues attach to a job", "j2", "=", "sql", ".", "join", "(", "_TABLE", ",", "JJI", ",", "sql", ".", "and_", "(", "_TABLE", ".", "c", ".", "id", "==", "JJI", ".", "c", ".", "issue_id", ",", "JJI", ".", "c", ".", "job_id", "==", "resource_id", ")", ")", "query2", "=", "sql", ".", "select", "(", "[", "_TABLE", "]", ")", ".", "select_from", "(", "j2", ")", "rows2", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query2", ")", "rows", "+=", "[", "dict", "(", "row", ")", "for", "row", "in", "rows2", "]", "# When retrieving the issues for a component, we only retrieve the", "# issues attached to the specified component.", "else", ":", "JCI", "=", "models", ".", "JOIN_COMPONENTS_ISSUES", "query", "=", "(", "sql", ".", "select", "(", "[", "_TABLE", "]", ")", ".", "select_from", "(", "JCI", ".", "join", "(", "_TABLE", ")", ")", ".", "where", "(", "JCI", ".", "c", ".", "component_id", "==", "resource_id", ")", ")", "rows", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", "rows", "=", "[", "dict", "(", "row", ")", "for", "row", "in", "rows", "]", "for", "row", "in", "rows", ":", "if", "row", "[", "'tracker'", "]", "==", "'github'", ":", "l_tracker", "=", "github", ".", "Github", "(", "row", "[", "'url'", "]", ")", "elif", "row", "[", "'tracker'", "]", "==", "'bugzilla'", ":", "l_tracker", "=", "bugzilla", ".", "Bugzilla", "(", "row", "[", "'url'", "]", ")", "row", ".", "update", "(", "l_tracker", ".", "dump", "(", ")", ")", "return", "flask", ".", "jsonify", "(", "{", "'issues'", ":", "rows", ",", "'_meta'", ":", "{", "'count'", ":", "len", "(", "rows", ")", "}", "}", ")" ]
Get all issues for a specific job.
[ "Get", "all", "issues", "for", "a", "specific", "job", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/issues.py#L63-L127
train
redhat-cip/dci-control-server
dci/api/v1/issues.py
unattach_issue
def unattach_issue(resource_id, issue_id, table): """Unattach an issue from a specific job.""" v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_id == resource_id, join_table.c.issue_id == issue_id) else: join_table = models.JOIN_COMPONENTS_ISSUES where_clause = sql.and_(join_table.c.component_id == resource_id, join_table.c.issue_id == issue_id) query = join_table.delete().where(where_clause) result = flask.g.db_conn.execute(query) if not result.rowcount: raise dci_exc.DCIConflict('%s_issues' % table.name, issue_id) return flask.Response(None, 204, content_type='application/json')
python
def unattach_issue(resource_id, issue_id, table): """Unattach an issue from a specific job.""" v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_id == resource_id, join_table.c.issue_id == issue_id) else: join_table = models.JOIN_COMPONENTS_ISSUES where_clause = sql.and_(join_table.c.component_id == resource_id, join_table.c.issue_id == issue_id) query = join_table.delete().where(where_clause) result = flask.g.db_conn.execute(query) if not result.rowcount: raise dci_exc.DCIConflict('%s_issues' % table.name, issue_id) return flask.Response(None, 204, content_type='application/json')
[ "def", "unattach_issue", "(", "resource_id", ",", "issue_id", ",", "table", ")", ":", "v1_utils", ".", "verify_existence_and_get", "(", "issue_id", ",", "_TABLE", ")", "if", "table", ".", "name", "==", "'jobs'", ":", "join_table", "=", "models", ".", "JOIN_JOBS_ISSUES", "where_clause", "=", "sql", ".", "and_", "(", "join_table", ".", "c", ".", "job_id", "==", "resource_id", ",", "join_table", ".", "c", ".", "issue_id", "==", "issue_id", ")", "else", ":", "join_table", "=", "models", ".", "JOIN_COMPONENTS_ISSUES", "where_clause", "=", "sql", ".", "and_", "(", "join_table", ".", "c", ".", "component_id", "==", "resource_id", ",", "join_table", ".", "c", ".", "issue_id", "==", "issue_id", ")", "query", "=", "join_table", ".", "delete", "(", ")", ".", "where", "(", "where_clause", ")", "result", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", "if", "not", "result", ".", "rowcount", ":", "raise", "dci_exc", ".", "DCIConflict", "(", "'%s_issues'", "%", "table", ".", "name", ",", "issue_id", ")", "return", "flask", ".", "Response", "(", "None", ",", "204", ",", "content_type", "=", "'application/json'", ")" ]
Unattach an issue from a specific job.
[ "Unattach", "an", "issue", "from", "a", "specific", "job", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/issues.py#L130-L149
train
redhat-cip/dci-control-server
dci/api/v1/issues.py
attach_issue
def attach_issue(resource_id, table, user_id): """Attach an issue to a specific job.""" data = schemas.issue.post(flask.request.json) issue = _get_or_create_issue(data) # Second, insert a join record in the JOIN_JOBS_ISSUES or # JOIN_COMPONENTS_ISSUES database. if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES else: join_table = models.JOIN_COMPONENTS_ISSUES key = '%s_id' % table.name[0:-1] query = join_table.insert().values({ 'user_id': user_id, 'issue_id': issue['id'], key: resource_id }) try: flask.g.db_conn.execute(query) except sa_exc.IntegrityError: raise dci_exc.DCICreationConflict(join_table.name, '%s, issue_id' % key) result = json.dumps({'issue': dict(issue)}) return flask.Response(result, 201, content_type='application/json')
python
def attach_issue(resource_id, table, user_id): """Attach an issue to a specific job.""" data = schemas.issue.post(flask.request.json) issue = _get_or_create_issue(data) # Second, insert a join record in the JOIN_JOBS_ISSUES or # JOIN_COMPONENTS_ISSUES database. if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES else: join_table = models.JOIN_COMPONENTS_ISSUES key = '%s_id' % table.name[0:-1] query = join_table.insert().values({ 'user_id': user_id, 'issue_id': issue['id'], key: resource_id }) try: flask.g.db_conn.execute(query) except sa_exc.IntegrityError: raise dci_exc.DCICreationConflict(join_table.name, '%s, issue_id' % key) result = json.dumps({'issue': dict(issue)}) return flask.Response(result, 201, content_type='application/json')
[ "def", "attach_issue", "(", "resource_id", ",", "table", ",", "user_id", ")", ":", "data", "=", "schemas", ".", "issue", ".", "post", "(", "flask", ".", "request", ".", "json", ")", "issue", "=", "_get_or_create_issue", "(", "data", ")", "# Second, insert a join record in the JOIN_JOBS_ISSUES or", "# JOIN_COMPONENTS_ISSUES database.", "if", "table", ".", "name", "==", "'jobs'", ":", "join_table", "=", "models", ".", "JOIN_JOBS_ISSUES", "else", ":", "join_table", "=", "models", ".", "JOIN_COMPONENTS_ISSUES", "key", "=", "'%s_id'", "%", "table", ".", "name", "[", "0", ":", "-", "1", "]", "query", "=", "join_table", ".", "insert", "(", ")", ".", "values", "(", "{", "'user_id'", ":", "user_id", ",", "'issue_id'", ":", "issue", "[", "'id'", "]", ",", "key", ":", "resource_id", "}", ")", "try", ":", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", "except", "sa_exc", ".", "IntegrityError", ":", "raise", "dci_exc", ".", "DCICreationConflict", "(", "join_table", ".", "name", ",", "'%s, issue_id'", "%", "key", ")", "result", "=", "json", ".", "dumps", "(", "{", "'issue'", ":", "dict", "(", "issue", ")", "}", ")", "return", "flask", ".", "Response", "(", "result", ",", "201", ",", "content_type", "=", "'application/json'", ")" ]
Attach an issue to a specific job.
[ "Attach", "an", "issue", "to", "a", "specific", "job", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/issues.py#L152-L178
train
inveniosoftware/invenio-assets
invenio_assets/collect.py
collect_staticroot_removal
def collect_staticroot_removal(app, blueprints): """Remove collect's static root folder from list.""" collect_root = app.extensions['collect'].static_root return [bp for bp in blueprints if ( bp.has_static_folder and bp.static_folder != collect_root)]
python
def collect_staticroot_removal(app, blueprints): """Remove collect's static root folder from list.""" collect_root = app.extensions['collect'].static_root return [bp for bp in blueprints if ( bp.has_static_folder and bp.static_folder != collect_root)]
[ "def", "collect_staticroot_removal", "(", "app", ",", "blueprints", ")", ":", "collect_root", "=", "app", ".", "extensions", "[", "'collect'", "]", ".", "static_root", "return", "[", "bp", "for", "bp", "in", "blueprints", "if", "(", "bp", ".", "has_static_folder", "and", "bp", ".", "static_folder", "!=", "collect_root", ")", "]" ]
Remove collect's static root folder from list.
[ "Remove", "collect", "s", "static", "root", "folder", "from", "list", "." ]
836cc75ebe0c179f0d72456bd8b784cdc18394a6
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/collect.py#L14-L18
train
redhat-cip/dci-control-server
dci/api/v1/jobstates.py
get_all_jobstates
def get_all_jobstates(user, job_id): """Get all jobstates. """ args = schemas.args(flask.request.args.to_dict()) job = v1_utils.verify_existence_and_get(job_id, models.JOBS) if user.is_not_super_admin() and user.is_not_read_only_user(): if (job['team_id'] not in user.teams_ids and job['team_id'] not in user.child_teams_ids): raise dci_exc.Unauthorized() query = v1_utils.QueryBuilder(_TABLE, args, _JS_COLUMNS) query.add_extra_condition(_TABLE.c.job_id == job_id) # get the number of rows for the '_meta' section nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name, args['embed'], _EMBED_MANY) return flask.jsonify({'jobstates': rows, '_meta': {'count': nb_rows}})
python
def get_all_jobstates(user, job_id): """Get all jobstates. """ args = schemas.args(flask.request.args.to_dict()) job = v1_utils.verify_existence_and_get(job_id, models.JOBS) if user.is_not_super_admin() and user.is_not_read_only_user(): if (job['team_id'] not in user.teams_ids and job['team_id'] not in user.child_teams_ids): raise dci_exc.Unauthorized() query = v1_utils.QueryBuilder(_TABLE, args, _JS_COLUMNS) query.add_extra_condition(_TABLE.c.job_id == job_id) # get the number of rows for the '_meta' section nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name, args['embed'], _EMBED_MANY) return flask.jsonify({'jobstates': rows, '_meta': {'count': nb_rows}})
[ "def", "get_all_jobstates", "(", "user", ",", "job_id", ")", ":", "args", "=", "schemas", ".", "args", "(", "flask", ".", "request", ".", "args", ".", "to_dict", "(", ")", ")", "job", "=", "v1_utils", ".", "verify_existence_and_get", "(", "job_id", ",", "models", ".", "JOBS", ")", "if", "user", ".", "is_not_super_admin", "(", ")", "and", "user", ".", "is_not_read_only_user", "(", ")", ":", "if", "(", "job", "[", "'team_id'", "]", "not", "in", "user", ".", "teams_ids", "and", "job", "[", "'team_id'", "]", "not", "in", "user", ".", "child_teams_ids", ")", ":", "raise", "dci_exc", ".", "Unauthorized", "(", ")", "query", "=", "v1_utils", ".", "QueryBuilder", "(", "_TABLE", ",", "args", ",", "_JS_COLUMNS", ")", "query", ".", "add_extra_condition", "(", "_TABLE", ".", "c", ".", "job_id", "==", "job_id", ")", "# get the number of rows for the '_meta' section", "nb_rows", "=", "query", ".", "get_number_of_rows", "(", ")", "rows", "=", "query", ".", "execute", "(", "fetchall", "=", "True", ")", "rows", "=", "v1_utils", ".", "format_result", "(", "rows", ",", "_TABLE", ".", "name", ",", "args", "[", "'embed'", "]", ",", "_EMBED_MANY", ")", "return", "flask", ".", "jsonify", "(", "{", "'jobstates'", ":", "rows", ",", "'_meta'", ":", "{", "'count'", ":", "nb_rows", "}", "}", ")" ]
Get all jobstates.
[ "Get", "all", "jobstates", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/jobstates.py#L100-L118
train
redhat-cip/dci-control-server
bin/keycloak-provision.py
create_client
def create_client(access_token): """Create the dci client in the master realm.""" url = 'http://keycloak:8080/auth/admin/realms/dci-test/clients' r = requests.post(url, data=json.dumps(client_data), headers=get_auth_headers(access_token)) if r.status_code in (201, 409): print('Keycloak client dci created successfully.') else: raise Exception( 'Error while creating Keycloak client dci:\nstatus code %s\n' 'error: %s' % (r.status_code, r.content) )
python
def create_client(access_token): """Create the dci client in the master realm.""" url = 'http://keycloak:8080/auth/admin/realms/dci-test/clients' r = requests.post(url, data=json.dumps(client_data), headers=get_auth_headers(access_token)) if r.status_code in (201, 409): print('Keycloak client dci created successfully.') else: raise Exception( 'Error while creating Keycloak client dci:\nstatus code %s\n' 'error: %s' % (r.status_code, r.content) )
[ "def", "create_client", "(", "access_token", ")", ":", "url", "=", "'http://keycloak:8080/auth/admin/realms/dci-test/clients'", "r", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "client_data", ")", ",", "headers", "=", "get_auth_headers", "(", "access_token", ")", ")", "if", "r", ".", "status_code", "in", "(", "201", ",", "409", ")", ":", "print", "(", "'Keycloak client dci created successfully.'", ")", "else", ":", "raise", "Exception", "(", "'Error while creating Keycloak client dci:\\nstatus code %s\\n'", "'error: %s'", "%", "(", "r", ".", "status_code", ",", "r", ".", "content", ")", ")" ]
Create the dci client in the master realm.
[ "Create", "the", "dci", "client", "in", "the", "master", "realm", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/bin/keycloak-provision.py#L193-L205
train
redhat-cip/dci-control-server
bin/keycloak-provision.py
create_user_dci
def create_user_dci(access_token): """Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io""" user_data = {'username': 'dci', 'email': 'dci@distributed-ci.io', 'enabled': True, 'emailVerified': True, 'credentials': [{'type': 'password', 'value': 'dci'}]} r = requests.post('http://keycloak:8080/auth/admin/realms/dci-test/users', data=json.dumps(user_data), headers=get_auth_headers(access_token)) if r.status_code in (201, 409): print('Keycloak user dci created successfully.') else: raise Exception('Error while creating user dci:\nstatus code %s\n' 'error: %s' % (r.status_code, r.content))
python
def create_user_dci(access_token): """Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io""" user_data = {'username': 'dci', 'email': 'dci@distributed-ci.io', 'enabled': True, 'emailVerified': True, 'credentials': [{'type': 'password', 'value': 'dci'}]} r = requests.post('http://keycloak:8080/auth/admin/realms/dci-test/users', data=json.dumps(user_data), headers=get_auth_headers(access_token)) if r.status_code in (201, 409): print('Keycloak user dci created successfully.') else: raise Exception('Error while creating user dci:\nstatus code %s\n' 'error: %s' % (r.status_code, r.content))
[ "def", "create_user_dci", "(", "access_token", ")", ":", "user_data", "=", "{", "'username'", ":", "'dci'", ",", "'email'", ":", "'dci@distributed-ci.io'", ",", "'enabled'", ":", "True", ",", "'emailVerified'", ":", "True", ",", "'credentials'", ":", "[", "{", "'type'", ":", "'password'", ",", "'value'", ":", "'dci'", "}", "]", "}", "r", "=", "requests", ".", "post", "(", "'http://keycloak:8080/auth/admin/realms/dci-test/users'", ",", "data", "=", "json", ".", "dumps", "(", "user_data", ")", ",", "headers", "=", "get_auth_headers", "(", "access_token", ")", ")", "if", "r", ".", "status_code", "in", "(", "201", ",", "409", ")", ":", "print", "(", "'Keycloak user dci created successfully.'", ")", "else", ":", "raise", "Exception", "(", "'Error while creating user dci:\\nstatus code %s\\n'", "'error: %s'", "%", "(", "r", ".", "status_code", ",", "r", ".", "content", ")", ")" ]
Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io
[ "Create", "the", "a", "dci", "user", ".", "username", "=", "dci", "password", "=", "dci", "email", "=", "dci" ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/bin/keycloak-provision.py#L208-L224
train
mediawiki-utilities/python-mwxml
mwxml/iteration/site_info.py
SiteInfo.initialize
def initialize(self, name=None, dbname=None, base=None, generator=None, case=None, namespaces=None): self.name = none_or(name, str) """ The name of the site. : str | `None` """ self.dbname = none_or(dbname, str) """ The dbname of the site. : str | `None` """ self.base = none_or(base, str) """ TODO: ??? : str | `None` """ self.generator = none_or(generator, str) """ TODO: ??? : str | `None` """ self.case = none_or(case, str) """ TODO: ??? : str | `None` """ self.namespaces = none_or(namespaces, list) """ A list of :class:`mwtypes.Namespace` | `None` """
python
def initialize(self, name=None, dbname=None, base=None, generator=None, case=None, namespaces=None): self.name = none_or(name, str) """ The name of the site. : str | `None` """ self.dbname = none_or(dbname, str) """ The dbname of the site. : str | `None` """ self.base = none_or(base, str) """ TODO: ??? : str | `None` """ self.generator = none_or(generator, str) """ TODO: ??? : str | `None` """ self.case = none_or(case, str) """ TODO: ??? : str | `None` """ self.namespaces = none_or(namespaces, list) """ A list of :class:`mwtypes.Namespace` | `None` """
[ "def", "initialize", "(", "self", ",", "name", "=", "None", ",", "dbname", "=", "None", ",", "base", "=", "None", ",", "generator", "=", "None", ",", "case", "=", "None", ",", "namespaces", "=", "None", ")", ":", "self", ".", "name", "=", "none_or", "(", "name", ",", "str", ")", "self", ".", "dbname", "=", "none_or", "(", "dbname", ",", "str", ")", "\"\"\"\n The dbname of the site. : str | `None`\n \"\"\"", "self", ".", "base", "=", "none_or", "(", "base", ",", "str", ")", "\"\"\"\n TODO: ??? : str | `None`\n \"\"\"", "self", ".", "generator", "=", "none_or", "(", "generator", ",", "str", ")", "\"\"\"\n TODO: ??? : str | `None`\n \"\"\"", "self", ".", "case", "=", "none_or", "(", "case", ",", "str", ")", "\"\"\"\n TODO: ??? : str | `None`\n \"\"\"", "self", ".", "namespaces", "=", "none_or", "(", "namespaces", ",", "list", ")", "\"\"\"\n A list of :class:`mwtypes.Namespace` | `None`\n \"\"\"" ]
The name of the site. : str | `None`
[ "The", "name", "of", "the", "site", ".", ":", "str", "|", "None" ]
6a8c18be99cd0bcee9c496e607f08bf4dfe5b510
https://github.com/mediawiki-utilities/python-mwxml/blob/6a8c18be99cd0bcee9c496e607f08bf4dfe5b510/mwxml/iteration/site_info.py#L32-L63
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom._serializeBooleans
def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower()
python
def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower()
[ "def", "_serializeBooleans", "(", "params", ")", ":", "serialized", "=", "{", "}", "for", "name", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "value", "is", "True", ":", "value", "=", "'true'", "elif", "value", "is", "False", ":", "value", "=", "'false'", "serialized", "[", "name", "]", "=", "value", "return", "serialized", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "bool", ")", ":", "params", "[", "k", "]", "=", "str", "(", "v", ")", ".", "lower", "(", ")" ]
Convert all booleans to lowercase strings
[ "Convert", "all", "booleans", "to", "lowercase", "strings" ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L37-L50
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.request
def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response
python
def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "parameters", "=", "dict", "(", ")", ")", ":", "# The requests library uses urllib, which serializes to \"True\"/\"False\" while Pingdom requires lowercase", "parameters", "=", "self", ".", "_serializeBooleans", "(", "parameters", ")", "headers", "=", "{", "'App-Key'", ":", "self", ".", "apikey", "}", "if", "self", ".", "accountemail", ":", "headers", ".", "update", "(", "{", "'Account-Email'", ":", "self", ".", "accountemail", "}", ")", "# Method selection handling", "if", "method", ".", "upper", "(", ")", "==", "'GET'", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "url", ",", "params", "=", "parameters", ",", "auth", "=", "(", "self", ".", "username", ",", "self", ".", "password", ")", ",", "headers", "=", "headers", ")", "elif", "method", ".", "upper", "(", ")", "==", "'POST'", ":", "response", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "url", ",", "data", "=", "parameters", ",", "auth", "=", "(", "self", ".", "username", ",", "self", ".", "password", ")", ",", "headers", "=", "headers", ")", "elif", "method", ".", "upper", "(", ")", "==", "'PUT'", ":", "response", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "url", ",", "data", "=", "parameters", ",", "auth", "=", "(", "self", ".", "username", ",", "self", ".", "password", ")", ",", "headers", "=", "headers", ")", "elif", "method", ".", "upper", "(", ")", "==", "'DELETE'", ":", "response", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "url", ",", "params", "=", "parameters", ",", "auth", "=", "(", "self", ".", "username", ",", "self", ".", "password", ")", ",", "headers", "=", "headers", ")", "else", ":", "raise", "Exception", "(", "\"Invalid method in pingdom request\"", ")", "# Store pingdom api limits", "self", ".", "shortlimit", "=", "response", ".", "headers", ".", "get", "(", "'Req-Limit-Short'", ",", "self", ".", "shortlimit", ")", "self", ".", "longlimit", "=", "response", ".", "headers", ".", "get", "(", "'Req-Limit-Long'", ",", "self", ".", "longlimit", ")", "# Verify OK response", "if", "response", ".", "status_code", "!=", "200", ":", "sys", ".", "stderr", ".", "write", "(", "'ERROR from %s: %d'", "%", "(", "response", ".", "url", ",", "response", ".", "status_code", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'Returned data: %s\\n'", "%", "response", ".", "json", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response" ]
Requests wrapper function
[ "Requests", "wrapper", "function" ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L52-L97
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.actions
def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions']
python
def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions']
[ "def", "actions", "(", "self", ",", "*", "*", "parameters", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "parameters", ":", "if", "key", "not", "in", "[", "'from'", ",", "'to'", ",", "'limit'", ",", "'offset'", ",", "'checkids'", ",", "'contactids'", ",", "'status'", ",", "'via'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "'%s not a valid argument for actions()\\n'", "%", "key", ")", "response", "=", "self", ".", "request", "(", "'GET'", ",", "'actions'", ",", "parameters", ")", "return", "response", ".", "json", "(", ")", "[", "'actions'", "]" ]
Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] }
[ "Returns", "a", "list", "of", "actions", "(", "alerts", ")", "that", "have", "been", "generated", "for", "your", "account", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L99-L183
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.getChecks
def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']]
python
def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']]
[ "def", "getChecks", "(", "self", ",", "*", "*", "parameters", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "parameters", ":", "if", "key", "not", "in", "[", "'limit'", ",", "'offset'", ",", "'tags'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "'%s not a valid argument for getChecks()\\n'", "%", "key", ")", "response", "=", "self", ".", "request", "(", "'GET'", ",", "'checks'", ",", "parameters", ")", "return", "[", "PingdomCheck", "(", "self", ",", "x", ")", "for", "x", "in", "response", ".", "json", "(", ")", "[", "'checks'", "]", "]" ]
Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None
[ "Pulls", "all", "checks", "from", "pingdom" ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L191-L219
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.getCheck
def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check
python
def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check
[ "def", "getCheck", "(", "self", ",", "checkid", ")", ":", "check", "=", "PingdomCheck", "(", "self", ",", "{", "'id'", ":", "checkid", "}", ")", "check", ".", "getDetails", "(", ")", "return", "check" ]
Returns a detailed description of a specified check.
[ "Returns", "a", "detailed", "description", "of", "a", "specified", "check", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L221-L226
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.probes
def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes']
python
def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes']
[ "def", "probes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "[", "'limit'", ",", "'offset'", ",", "'onlyactive'", ",", "'includedeleted'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "\"'%s'\"", "%", "key", "+", "' is not a valid argument '", "+", "'of probes()\\n'", ")", "return", "self", ".", "request", "(", "\"GET\"", ",", "\"probes\"", ",", "kwargs", ")", ".", "json", "(", ")", "[", "'probes'", "]" ]
Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ]
[ "Returns", "a", "list", "of", "all", "Pingdom", "probe", "servers" ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L621-L664
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.traceroute
def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute']
python
def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute']
[ "def", "traceroute", "(", "self", ",", "host", ",", "probeid", ")", ":", "response", "=", "self", ".", "request", "(", "'GET'", ",", "'traceroute'", ",", "{", "'host'", ":", "host", ",", "'probeid'", ":", "probeid", "}", ")", "return", "response", ".", "json", "(", ")", "[", "'traceroute'", "]" ]
Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description }
[ "Perform", "a", "traceroute", "to", "a", "specified", "target", "from", "a", "specified", "Pingdom", "probe", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L733-L749
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.getContacts
def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']]
python
def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']]
[ "def", "getContacts", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "[", "'limit'", ",", "'offset'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "\"'%s'\"", "%", "key", "+", "' is not a valid argument '", "+", "'of getContacts()\\n'", ")", "return", "[", "PingdomContact", "(", "self", ",", "x", ")", "for", "x", "in", "self", ".", "request", "(", "\"GET\"", ",", "\"notification_contacts\"", ",", "kwargs", ")", ".", "json", "(", ")", "[", "'contacts'", "]", "]" ]
Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ]
[ "Returns", "a", "list", "of", "all", "contacts", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L756-L793
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.newContact
def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo)
python
def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo)
[ "def", "newContact", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "[", "'email'", ",", "'cellphone'", ",", "'countrycode'", ",", "'countryiso'", ",", "'defaultsmsprovider'", ",", "'directtwitter'", ",", "'twitteruser'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "\"'%s'\"", "%", "key", "+", "' is not a valid argument '", "+", "'of newContact()\\n'", ")", "kwargs", "[", "'name'", "]", "=", "name", "contactinfo", "=", "self", ".", "request", "(", "\"POST\"", ",", "\"notification_contacts\"", ",", "kwargs", ")", ".", "json", "(", ")", "[", "'contact'", "]", "return", "PingdomContact", "(", "self", ",", "contactinfo", ")" ]
Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String
[ "Create", "a", "new", "contact", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L795-L844
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.modifyContacts
def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message']
python
def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message']
[ "def", "modifyContacts", "(", "self", ",", "contactids", ",", "paused", ")", ":", "response", "=", "self", ".", "request", "(", "\"PUT\"", ",", "\"notification_contacts\"", ",", "{", "'contactids'", ":", "contactids", ",", "'paused'", ":", "paused", "}", ")", "return", "response", ".", "json", "(", ")", "[", "'message'", "]" ]
Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message
[ "Modifies", "a", "list", "of", "contacts", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L846-L856
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.getEmailReports
def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports
python
def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports
[ "def", "getEmailReports", "(", "self", ")", ":", "reports", "=", "[", "PingdomEmailReport", "(", "self", ",", "x", ")", "for", "x", "in", "self", ".", "request", "(", "'GET'", ",", "'reports.email'", ")", ".", "json", "(", ")", "[", "'subscriptions'", "]", "]", "return", "reports" ]
Returns a list of PingdomEmailReport instances.
[ "Returns", "a", "list", "of", "PingdomEmailReport", "instances", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1170-L1177
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.newEmailReport
def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message']
python
def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message']
[ "def", "newEmailReport", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "[", "'checkid'", ",", "'frequency'", ",", "'contactids'", ",", "'additionalemails'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "\"'%s'\"", "%", "key", "+", "' is not a valid argument '", "+", "'of newEmailReport()\\n'", ")", "parameters", "=", "{", "'name'", ":", "name", "}", "for", "key", ",", "value", "in", "kwargs", ".", "iteritems", "(", ")", ":", "parameters", "[", "key", "]", "=", "value", "return", "self", ".", "request", "(", "'POST'", ",", "'reports.email'", ",", "parameters", ")", ".", "json", "(", ")", "[", "'message'", "]" ]
Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String
[ "Creates", "a", "new", "email", "report" ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1179-L1214
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.getSharedReports
def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports
python
def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports
[ "def", "getSharedReports", "(", "self", ")", ":", "response", "=", "self", ".", "request", "(", "'GET'", ",", "'reports.shared'", ")", ".", "json", "(", ")", "[", "'shared'", "]", "[", "'banners'", "]", "reports", "=", "[", "PingdomSharedReport", "(", "self", ",", "x", ")", "for", "x", "in", "response", "]", "return", "reports" ]
Returns a list of PingdomSharedReport instances
[ "Returns", "a", "list", "of", "PingdomSharedReport", "instances" ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1232-L1239
train
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.newSharedReport
def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
python
def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
[ "def", "newSharedReport", "(", "self", ",", "checkid", ",", "*", "*", "kwargs", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "[", "'auto'", ",", "'type'", ",", "'fromyear'", ",", "'frommonth'", ",", "'fromday'", ",", "'toyear'", ",", "'tomonth'", ",", "'today'", ",", "'sharedtype'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "\"'%s'\"", "%", "key", "+", "' is not a valid argument '", "+", "'of newSharedReport()\\n'", ")", "parameters", "=", "{", "'checkid'", ":", "checkid", ",", "'sharedtype'", ":", "'banner'", "}", "for", "key", ",", "value", "in", "kwargs", ".", "iteritems", "(", ")", ":", "parameters", "[", "key", "]", "=", "value", "return", "self", ".", "request", "(", "'POST'", ",", "'reports.shared'", ",", "parameters", ")", ".", "json", "(", ")", "[", "'message'", "]" ]
Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer
[ "Create", "a", "shared", "report", "(", "banner", ")", "." ]
3ed1e481f9c9d16b032558d62fb05c2166e162ed
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1241-L1286
train
Antidote1911/cryptoshop
cryptoshop/_cascade_engine.py
encry_decry_cascade
def encry_decry_cascade(data, masterkey, bool_encry, assoc_data): """ When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is True, data is encrypted. Else, it will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data. """ engine1 = botan.cipher(algo="Serpent/GCM", encrypt=bool_encry) engine2 = botan.cipher(algo="AES-256/GCM", encrypt=bool_encry) engine3 = botan.cipher(algo="Twofish/GCM", encrypt=bool_encry) hash1 = botan.hash_function(algo="SHA-256") hash1.update(masterkey) hashed1 = hash1.final() hash2 = botan.hash_function(algo="SHA-256") hash2.update(hashed1) hashed2 = hash2.final() engine1.set_key(key=masterkey) engine1.set_assoc_data(assoc_data) engine2.set_key(key=hashed1) engine2.set_assoc_data(assoc_data) engine3.set_key(key=hashed2) engine3.set_assoc_data(assoc_data) if bool_encry is True: nonce1 = generate_nonce_timestamp() nonce2 = generate_nonce_timestamp() nonce3 = generate_nonce_timestamp() engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) cipher1 = engine1.finish(data) cipher2 = engine2.finish(cipher1) cipher3 = engine3.finish(cipher2) return nonce1 + nonce2 + nonce3 + cipher3 else: nonce1 = data[:__nonce_length__] nonce2 = data[__nonce_length__:__nonce_length__ * 2] nonce3 = data[__nonce_length__ * 2:__nonce_length__ * 3] encrypteddata = data[__nonce_length__ * 3:] engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) decrypteddata1 = engine3.finish(encrypteddata) if decrypteddata1 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata2 = engine2.finish(decrypteddata1) if decrypteddata2 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata3 = engine1.finish(decrypteddata2) if decrypteddata3 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") else: return decrypteddata3
python
def encry_decry_cascade(data, masterkey, bool_encry, assoc_data): """ When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is True, data is encrypted. Else, it will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data. """ engine1 = botan.cipher(algo="Serpent/GCM", encrypt=bool_encry) engine2 = botan.cipher(algo="AES-256/GCM", encrypt=bool_encry) engine3 = botan.cipher(algo="Twofish/GCM", encrypt=bool_encry) hash1 = botan.hash_function(algo="SHA-256") hash1.update(masterkey) hashed1 = hash1.final() hash2 = botan.hash_function(algo="SHA-256") hash2.update(hashed1) hashed2 = hash2.final() engine1.set_key(key=masterkey) engine1.set_assoc_data(assoc_data) engine2.set_key(key=hashed1) engine2.set_assoc_data(assoc_data) engine3.set_key(key=hashed2) engine3.set_assoc_data(assoc_data) if bool_encry is True: nonce1 = generate_nonce_timestamp() nonce2 = generate_nonce_timestamp() nonce3 = generate_nonce_timestamp() engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) cipher1 = engine1.finish(data) cipher2 = engine2.finish(cipher1) cipher3 = engine3.finish(cipher2) return nonce1 + nonce2 + nonce3 + cipher3 else: nonce1 = data[:__nonce_length__] nonce2 = data[__nonce_length__:__nonce_length__ * 2] nonce3 = data[__nonce_length__ * 2:__nonce_length__ * 3] encrypteddata = data[__nonce_length__ * 3:] engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) decrypteddata1 = engine3.finish(encrypteddata) if decrypteddata1 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata2 = engine2.finish(decrypteddata1) if decrypteddata2 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata3 = engine1.finish(decrypteddata2) if decrypteddata3 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") else: return decrypteddata3
[ "def", "encry_decry_cascade", "(", "data", ",", "masterkey", ",", "bool_encry", ",", "assoc_data", ")", ":", "engine1", "=", "botan", ".", "cipher", "(", "algo", "=", "\"Serpent/GCM\"", ",", "encrypt", "=", "bool_encry", ")", "engine2", "=", "botan", ".", "cipher", "(", "algo", "=", "\"AES-256/GCM\"", ",", "encrypt", "=", "bool_encry", ")", "engine3", "=", "botan", ".", "cipher", "(", "algo", "=", "\"Twofish/GCM\"", ",", "encrypt", "=", "bool_encry", ")", "hash1", "=", "botan", ".", "hash_function", "(", "algo", "=", "\"SHA-256\"", ")", "hash1", ".", "update", "(", "masterkey", ")", "hashed1", "=", "hash1", ".", "final", "(", ")", "hash2", "=", "botan", ".", "hash_function", "(", "algo", "=", "\"SHA-256\"", ")", "hash2", ".", "update", "(", "hashed1", ")", "hashed2", "=", "hash2", ".", "final", "(", ")", "engine1", ".", "set_key", "(", "key", "=", "masterkey", ")", "engine1", ".", "set_assoc_data", "(", "assoc_data", ")", "engine2", ".", "set_key", "(", "key", "=", "hashed1", ")", "engine2", ".", "set_assoc_data", "(", "assoc_data", ")", "engine3", ".", "set_key", "(", "key", "=", "hashed2", ")", "engine3", ".", "set_assoc_data", "(", "assoc_data", ")", "if", "bool_encry", "is", "True", ":", "nonce1", "=", "generate_nonce_timestamp", "(", ")", "nonce2", "=", "generate_nonce_timestamp", "(", ")", "nonce3", "=", "generate_nonce_timestamp", "(", ")", "engine1", ".", "start", "(", "nonce", "=", "nonce1", ")", "engine2", ".", "start", "(", "nonce", "=", "nonce2", ")", "engine3", ".", "start", "(", "nonce", "=", "nonce3", ")", "cipher1", "=", "engine1", ".", "finish", "(", "data", ")", "cipher2", "=", "engine2", ".", "finish", "(", "cipher1", ")", "cipher3", "=", "engine3", ".", "finish", "(", "cipher2", ")", "return", "nonce1", "+", "nonce2", "+", "nonce3", "+", "cipher3", "else", ":", "nonce1", "=", "data", "[", ":", "__nonce_length__", "]", "nonce2", "=", "data", "[", "__nonce_length__", ":", "__nonce_length__", "*", "2", "]", "nonce3", "=", "data", "[", "__nonce_length__", "*", "2", ":", "__nonce_length__", "*", "3", "]", "encrypteddata", "=", "data", "[", "__nonce_length__", "*", "3", ":", "]", "engine1", ".", "start", "(", "nonce", "=", "nonce1", ")", "engine2", ".", "start", "(", "nonce", "=", "nonce2", ")", "engine3", ".", "start", "(", "nonce", "=", "nonce3", ")", "decrypteddata1", "=", "engine3", ".", "finish", "(", "encrypteddata", ")", "if", "decrypteddata1", "==", "b\"\"", ":", "raise", "Exception", "(", "\"Integrity failure: Invalid passphrase or corrupted data\"", ")", "decrypteddata2", "=", "engine2", ".", "finish", "(", "decrypteddata1", ")", "if", "decrypteddata2", "==", "b\"\"", ":", "raise", "Exception", "(", "\"Integrity failure: Invalid passphrase or corrupted data\"", ")", "decrypteddata3", "=", "engine1", ".", "finish", "(", "decrypteddata2", ")", "if", "decrypteddata3", "==", "b\"\"", ":", "raise", "Exception", "(", "\"Integrity failure: Invalid passphrase or corrupted data\"", ")", "else", ":", "return", "decrypteddata3" ]
When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is True, data is encrypted. Else, it will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data.
[ "When", "bool_encry", "is", "True", "encrypt", "the", "data", "with", "master", "key", ".", "When", "it", "is", "False", "the", "function", "extract", "the", "three", "nonce", "from", "the", "encrypted", "data", "(", "first", "3", "*", "21", "bytes", ")", "and", "decrypt", "the", "data", ".", ":", "param", "data", ":", "the", "data", "to", "encrypt", "or", "decrypt", ".", ":", "param", "masterkey", ":", "a", "32", "bytes", "key", "in", "bytes", ".", ":", "param", "bool_encry", ":", "if", "bool_encry", "is", "True", "data", "is", "encrypted", ".", "Else", "it", "will", "be", "decrypted", ".", ":", "param", "assoc_data", ":", "Additional", "data", "added", "to", "GCM", "authentication", ".", ":", "return", ":", "if", "bool_encry", "is", "True", "corresponding", "nonce", "+", "encrypted", "data", ".", "Else", "the", "decrypted", "data", "." ]
0b7ff4a6848f2733f4737606957e8042a4d6ca0b
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/_cascade_engine.py#L39-L104
train
BrighterCommand/Brightside
brightside/registry.py
Registry.register
def register(self, request_class: Request, handler_factory: Callable[[], Handler]) -> None: """ Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispatch to :return: """ key = request_class.__name__ is_command = request_class.is_command() is_event = request_class.is_event() is_present = key in self._registry if is_command and is_present: raise ConfigurationException("A handler for this request has already been registered") elif is_event and is_present: self._registry[key].append(handler_factory) elif is_command or is_event: self._registry[key] = [handler_factory]
python
def register(self, request_class: Request, handler_factory: Callable[[], Handler]) -> None: """ Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispatch to :return: """ key = request_class.__name__ is_command = request_class.is_command() is_event = request_class.is_event() is_present = key in self._registry if is_command and is_present: raise ConfigurationException("A handler for this request has already been registered") elif is_event and is_present: self._registry[key].append(handler_factory) elif is_command or is_event: self._registry[key] = [handler_factory]
[ "def", "register", "(", "self", ",", "request_class", ":", "Request", ",", "handler_factory", ":", "Callable", "[", "[", "]", ",", "Handler", "]", ")", "->", "None", ":", "key", "=", "request_class", ".", "__name__", "is_command", "=", "request_class", ".", "is_command", "(", ")", "is_event", "=", "request_class", ".", "is_event", "(", ")", "is_present", "=", "key", "in", "self", ".", "_registry", "if", "is_command", "and", "is_present", ":", "raise", "ConfigurationException", "(", "\"A handler for this request has already been registered\"", ")", "elif", "is_event", "and", "is_present", ":", "self", ".", "_registry", "[", "key", "]", ".", "append", "(", "handler_factory", ")", "elif", "is_command", "or", "is_event", ":", "self", ".", "_registry", "[", "key", "]", "=", "[", "handler_factory", "]" ]
Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispatch to :return:
[ "Register", "the", "handler", "for", "the", "command", ":", "param", "request_class", ":", "The", "command", "or", "event", "to", "dispatch", ".", "It", "must", "implement", "getKey", "()", ":", "param", "handler_factory", ":", "A", "factory", "method", "to", "create", "the", "handler", "to", "dispatch", "to", ":", "return", ":" ]
53b2f8323c3972609010a7386130249f3758f5fb
https://github.com/BrighterCommand/Brightside/blob/53b2f8323c3972609010a7386130249f3758f5fb/brightside/registry.py#L45-L61
train
BrighterCommand/Brightside
brightside/registry.py
Registry.lookup
def lookup(self, request: Request) -> List[Callable[[], Handler]]: """ Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return: """ key = request.__class__.__name__ if key not in self._registry: if request.is_command(): raise ConfigurationException("There is no handler registered for this request") elif request.is_event(): return [] # type: Callable[[] Handler] return self._registry[key]
python
def lookup(self, request: Request) -> List[Callable[[], Handler]]: """ Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return: """ key = request.__class__.__name__ if key not in self._registry: if request.is_command(): raise ConfigurationException("There is no handler registered for this request") elif request.is_event(): return [] # type: Callable[[] Handler] return self._registry[key]
[ "def", "lookup", "(", "self", ",", "request", ":", "Request", ")", "->", "List", "[", "Callable", "[", "[", "]", ",", "Handler", "]", "]", ":", "key", "=", "request", ".", "__class__", ".", "__name__", "if", "key", "not", "in", "self", ".", "_registry", ":", "if", "request", ".", "is_command", "(", ")", ":", "raise", "ConfigurationException", "(", "\"There is no handler registered for this request\"", ")", "elif", "request", ".", "is_event", "(", ")", ":", "return", "[", "]", "# type: Callable[[] Handler]", "return", "self", ".", "_registry", "[", "key", "]" ]
Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return:
[ "Looks", "up", "the", "handler", "associated", "with", "a", "request", "-", "matches", "the", "key", "on", "the", "request", "to", "a", "registered", "handler", ":", "param", "request", ":", "The", "request", "we", "want", "to", "find", "a", "handler", "for", ":", "return", ":" ]
53b2f8323c3972609010a7386130249f3758f5fb
https://github.com/BrighterCommand/Brightside/blob/53b2f8323c3972609010a7386130249f3758f5fb/brightside/registry.py#L63-L76
train
BrighterCommand/Brightside
brightside/registry.py
MessageMapperRegistry.register
def register(self, request_class: Request, mapper_func: Callable[[Request], BrightsideMessage]) -> None: """Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type """ key = request_class.__name__ if key not in self._registry: self._registry[key] = mapper_func else: raise ConfigurationException("There is already a message mapper defined for this key; there can be only one")
python
def register(self, request_class: Request, mapper_func: Callable[[Request], BrightsideMessage]) -> None: """Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type """ key = request_class.__name__ if key not in self._registry: self._registry[key] = mapper_func else: raise ConfigurationException("There is already a message mapper defined for this key; there can be only one")
[ "def", "register", "(", "self", ",", "request_class", ":", "Request", ",", "mapper_func", ":", "Callable", "[", "[", "Request", "]", ",", "BrightsideMessage", "]", ")", "->", "None", ":", "key", "=", "request_class", ".", "__name__", "if", "key", "not", "in", "self", ".", "_registry", ":", "self", ".", "_registry", "[", "key", "]", "=", "mapper_func", "else", ":", "raise", "ConfigurationException", "(", "\"There is already a message mapper defined for this key; there can be only one\"", ")" ]
Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type
[ "Adds", "a", "message", "mapper", "to", "a", "factory", "using", "the", "requests", "key", ":", "param", "mapper_func", ":", "A", "callback", "that", "creates", "a", "BrightsideMessage", "from", "a", "Request", ":", "param", "request_class", ":", "A", "request", "type" ]
53b2f8323c3972609010a7386130249f3758f5fb
https://github.com/BrighterCommand/Brightside/blob/53b2f8323c3972609010a7386130249f3758f5fb/brightside/registry.py#L89-L99
train
BrighterCommand/Brightside
brightside/registry.py
MessageMapperRegistry.lookup
def lookup(self, request_class: Request) -> Callable[[Request], BrightsideMessage]: """ Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_class: :return: """ key = request_class.__class__.__name__ if key not in self._registry: raise ConfigurationException("There is no message mapper associated with this key; we require a mapper") else: return self._registry[key]
python
def lookup(self, request_class: Request) -> Callable[[Request], BrightsideMessage]: """ Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_class: :return: """ key = request_class.__class__.__name__ if key not in self._registry: raise ConfigurationException("There is no message mapper associated with this key; we require a mapper") else: return self._registry[key]
[ "def", "lookup", "(", "self", ",", "request_class", ":", "Request", ")", "->", "Callable", "[", "[", "Request", "]", ",", "BrightsideMessage", "]", ":", "key", "=", "request_class", ".", "__class__", ".", "__name__", "if", "key", "not", "in", "self", ".", "_registry", ":", "raise", "ConfigurationException", "(", "\"There is no message mapper associated with this key; we require a mapper\"", ")", "else", ":", "return", "self", ".", "_registry", "[", "key", "]" ]
Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_class: :return:
[ "Looks", "up", "the", "message", "mapper", "function", "associated", "with", "this", "class", ".", "Function", "should", "take", "in", "a", "Request", "derived", "class", "and", "return", "a", "BrightsideMessage", "derived", "class", "for", "sending", "on", "the", "wire", ":", "param", "request_class", ":", ":", "return", ":" ]
53b2f8323c3972609010a7386130249f3758f5fb
https://github.com/BrighterCommand/Brightside/blob/53b2f8323c3972609010a7386130249f3758f5fb/brightside/registry.py#L101-L112
train
smarie/python-valid8
valid8/validation_lib/types.py
instance_of
def instance_of(*args): """ This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `instance_of(x, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode value, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if isinstance(value, ref_type): return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type) else: # ref_type is a set match = False # test against each of the provided types for ref in ref_type: if isinstance(value, ref): match = True break if match: return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): # ref_type is a single type def instance_of_ref(x): if isinstance(x, ref_type): return True else: raise HasWrongType(wrong_value=x, ref_type=ref_type) else: # ref_type is a set def instance_of_ref(x): match = False # test against each of the provided types for ref in ref_type: if isinstance(x, ref): match = True break if match: return True else: raise HasWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') instance_of_ref.__name__ = 'instance_of_{}'.format(ref_type) return instance_of_ref else: raise TypeError('instance_of expected 2 (normal) or 1 (function generator) arguments, got ' + str(len(args)))
python
def instance_of(*args): """ This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `instance_of(x, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode value, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if isinstance(value, ref_type): return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type) else: # ref_type is a set match = False # test against each of the provided types for ref in ref_type: if isinstance(value, ref): match = True break if match: return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): # ref_type is a single type def instance_of_ref(x): if isinstance(x, ref_type): return True else: raise HasWrongType(wrong_value=x, ref_type=ref_type) else: # ref_type is a set def instance_of_ref(x): match = False # test against each of the provided types for ref in ref_type: if isinstance(x, ref): match = True break if match: return True else: raise HasWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') instance_of_ref.__name__ = 'instance_of_{}'.format(ref_type) return instance_of_ref else: raise TypeError('instance_of expected 2 (normal) or 1 (function generator) arguments, got ' + str(len(args)))
[ "def", "instance_of", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "# Standard mode", "value", ",", "ref_type", "=", "args", "if", "not", "isinstance", "(", "ref_type", ",", "set", ")", ":", "# ref_type is a single type", "if", "isinstance", "(", "value", ",", "ref_type", ")", ":", "return", "True", "else", ":", "raise", "HasWrongType", "(", "wrong_value", "=", "value", ",", "ref_type", "=", "ref_type", ")", "else", ":", "# ref_type is a set", "match", "=", "False", "# test against each of the provided types", "for", "ref", "in", "ref_type", ":", "if", "isinstance", "(", "value", ",", "ref", ")", ":", "match", "=", "True", "break", "if", "match", ":", "return", "True", "else", ":", "raise", "HasWrongType", "(", "wrong_value", "=", "value", ",", "ref_type", "=", "ref_type", ",", "help_msg", "=", "'Value should be an instance of any of {ref_type}'", ")", "elif", "len", "(", "args", ")", "==", "1", ":", "# Function generator mode", "ref_type", "=", "args", "[", "0", "]", "if", "not", "isinstance", "(", "ref_type", ",", "set", ")", ":", "# ref_type is a single type", "def", "instance_of_ref", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "ref_type", ")", ":", "return", "True", "else", ":", "raise", "HasWrongType", "(", "wrong_value", "=", "x", ",", "ref_type", "=", "ref_type", ")", "else", ":", "# ref_type is a set", "def", "instance_of_ref", "(", "x", ")", ":", "match", "=", "False", "# test against each of the provided types", "for", "ref", "in", "ref_type", ":", "if", "isinstance", "(", "x", ",", "ref", ")", ":", "match", "=", "True", "break", "if", "match", ":", "return", "True", "else", ":", "raise", "HasWrongType", "(", "wrong_value", "=", "x", ",", "ref_type", "=", "ref_type", ",", "help_msg", "=", "'Value should be an instance of any of {ref_type}'", ")", "instance_of_ref", ".", "__name__", "=", "'instance_of_{}'", ".", "format", "(", "ref_type", ")", "return", "instance_of_ref", "else", ":", "raise", "TypeError", "(", "'instance_of expected 2 (normal) or 1 (function generator) arguments, got '", "+", "str", "(", "len", "(", "args", ")", ")", ")" ]
This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `instance_of(x, ref_type)`. :param args: :return:
[ "This", "type", "validation", "function", "can", "be", "used", "in", "two", "modes", ":", "*", "providing", "two", "arguments", "(", "x", "ref_type", ")", "it", "returns", "True", "if", "isinstance", "(", "x", "ref_type", ")", "and", "raises", "a", "HasWrongType", "error", "if", "not", ".", "If", "ref_type", "is", "a", "set", "of", "types", "any", "match", "with", "one", "of", "the", "included", "types", "will", "do", "*", "providing", "a", "single", "argument", "(", "ref_type", ")", "this", "is", "a", "function", "generator", ".", "It", "returns", "a", "validation", "function", "to", "check", "that", "instance_of", "(", "x", "ref_type", ")", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/types.py#L15-L78
train
smarie/python-valid8
valid8/validation_lib/types.py
subclass_of
def subclass_of(*args): """ This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `subclass_of(c, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode typ, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if issubclass(typ, ref_type): return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type) else: # ref_type is a set match = False # test against each of the provided types for ref in ref_type: if issubclass(typ, ref): match = True break if match: return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): def subclass_of_ref(x): if issubclass(x, ref_type): return True else: raise IsWrongType(wrong_value=x, ref_type=ref_type) else: # ref_type is a set def subclass_of_ref(x): match = False # test against each of the provided types for ref in ref_type: if issubclass(x, ref): match = True break if match: return True else: raise IsWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') subclass_of_ref.__name__ = 'subclass_of_{}'.format(ref_type) return subclass_of_ref else: raise TypeError('subclass_of expected 2 (normal) or 1 (function generator) arguments, got ' + str(len(args)))
python
def subclass_of(*args): """ This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `subclass_of(c, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode typ, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if issubclass(typ, ref_type): return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type) else: # ref_type is a set match = False # test against each of the provided types for ref in ref_type: if issubclass(typ, ref): match = True break if match: return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): def subclass_of_ref(x): if issubclass(x, ref_type): return True else: raise IsWrongType(wrong_value=x, ref_type=ref_type) else: # ref_type is a set def subclass_of_ref(x): match = False # test against each of the provided types for ref in ref_type: if issubclass(x, ref): match = True break if match: return True else: raise IsWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') subclass_of_ref.__name__ = 'subclass_of_{}'.format(ref_type) return subclass_of_ref else: raise TypeError('subclass_of expected 2 (normal) or 1 (function generator) arguments, got ' + str(len(args)))
[ "def", "subclass_of", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "# Standard mode", "typ", ",", "ref_type", "=", "args", "if", "not", "isinstance", "(", "ref_type", ",", "set", ")", ":", "# ref_type is a single type", "if", "issubclass", "(", "typ", ",", "ref_type", ")", ":", "return", "True", "else", ":", "raise", "IsWrongType", "(", "wrong_value", "=", "typ", ",", "ref_type", "=", "ref_type", ")", "else", ":", "# ref_type is a set", "match", "=", "False", "# test against each of the provided types", "for", "ref", "in", "ref_type", ":", "if", "issubclass", "(", "typ", ",", "ref", ")", ":", "match", "=", "True", "break", "if", "match", ":", "return", "True", "else", ":", "raise", "IsWrongType", "(", "wrong_value", "=", "typ", ",", "ref_type", "=", "ref_type", ",", "help_msg", "=", "'Value should be a subclass of any of {ref_type}'", ")", "elif", "len", "(", "args", ")", "==", "1", ":", "# Function generator mode", "ref_type", "=", "args", "[", "0", "]", "if", "not", "isinstance", "(", "ref_type", ",", "set", ")", ":", "def", "subclass_of_ref", "(", "x", ")", ":", "if", "issubclass", "(", "x", ",", "ref_type", ")", ":", "return", "True", "else", ":", "raise", "IsWrongType", "(", "wrong_value", "=", "x", ",", "ref_type", "=", "ref_type", ")", "else", ":", "# ref_type is a set", "def", "subclass_of_ref", "(", "x", ")", ":", "match", "=", "False", "# test against each of the provided types", "for", "ref", "in", "ref_type", ":", "if", "issubclass", "(", "x", ",", "ref", ")", ":", "match", "=", "True", "break", "if", "match", ":", "return", "True", "else", ":", "raise", "IsWrongType", "(", "wrong_value", "=", "x", ",", "ref_type", "=", "ref_type", ",", "help_msg", "=", "'Value should be a subclass of any of {ref_type}'", ")", "subclass_of_ref", ".", "__name__", "=", "'subclass_of_{}'", ".", "format", "(", "ref_type", ")", "return", "subclass_of_ref", "else", ":", "raise", "TypeError", "(", "'subclass_of expected 2 (normal) or 1 (function generator) arguments, got '", "+", "str", "(", "len", "(", "args", ")", ")", ")" ]
This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `subclass_of(c, ref_type)`. :param args: :return:
[ "This", "type", "validation", "function", "can", "be", "used", "in", "two", "modes", ":", "*", "providing", "two", "arguments", "(", "c", "ref_type", ")", "it", "returns", "True", "if", "issubclass", "(", "c", "ref_type", ")", "and", "raises", "a", "IsWrongType", "error", "if", "not", ".", "If", "ref_type", "is", "a", "set", "of", "types", "any", "match", "with", "one", "of", "the", "included", "types", "will", "do", "*", "providing", "a", "single", "argument", "(", "ref_type", ")", "this", "is", "a", "function", "generator", ".", "It", "returns", "a", "validation", "function", "to", "check", "that", "subclass_of", "(", "c", "ref_type", ")", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/types.py#L92-L153
train
danijar/sets
sets/utility.py
disk_cache
def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'. """ directory = os.path.expanduser(directory) ensure_directory(directory) def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): key = (tuple(args), tuple(kwargs.items())) # Don't use self or cls for the invalidation hash. if method and key: key = key[1:] filename = '{}-{}.pickle'.format(basename, hash(key)) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): with open(filepath, 'rb') as handle: return pickle.load(handle) result = func(*args, **kwargs) with open(filepath, 'wb') as handle: pickle.dump(result, handle) return result return wrapped return wrapper
python
def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'. """ directory = os.path.expanduser(directory) ensure_directory(directory) def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): key = (tuple(args), tuple(kwargs.items())) # Don't use self or cls for the invalidation hash. if method and key: key = key[1:] filename = '{}-{}.pickle'.format(basename, hash(key)) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): with open(filepath, 'rb') as handle: return pickle.load(handle) result = func(*args, **kwargs) with open(filepath, 'wb') as handle: pickle.dump(result, handle) return result return wrapped return wrapper
[ "def", "disk_cache", "(", "basename", ",", "directory", ",", "method", "=", "False", ")", ":", "directory", "=", "os", ".", "path", ".", "expanduser", "(", "directory", ")", "ensure_directory", "(", "directory", ")", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "(", "tuple", "(", "args", ")", ",", "tuple", "(", "kwargs", ".", "items", "(", ")", ")", ")", "# Don't use self or cls for the invalidation hash.", "if", "method", "and", "key", ":", "key", "=", "key", "[", "1", ":", "]", "filename", "=", "'{}-{}.pickle'", ".", "format", "(", "basename", ",", "hash", "(", "key", ")", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "handle", ":", "return", "pickle", ".", "load", "(", "handle", ")", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "with", "open", "(", "filepath", ",", "'wb'", ")", "as", "handle", ":", "pickle", ".", "dump", "(", "result", ",", "handle", ")", "return", "result", "return", "wrapped", "return", "wrapper" ]
Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'.
[ "Function", "decorator", "for", "caching", "pickleable", "return", "values", "on", "disk", ".", "Uses", "a", "hash", "computed", "from", "the", "function", "arguments", "for", "invalidation", ".", "If", "method", "skip", "the", "first", "argument", "usually", "being", "self", "or", "cls", ".", "The", "cache", "filepath", "is", "directory", "/", "basename", "-", "hash", ".", "pickle", "." ]
2542c28f43d0af18932cb5b82f54ffb6ae557d12
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/utility.py#L23-L51
train
danijar/sets
sets/utility.py
download
def download(url, directory, filename=None): """ Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. """ if not filename: _, filename = os.path.split(url) directory = os.path.expanduser(directory) ensure_directory(directory) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): return filepath print('Download', filepath) with urlopen(url) as response, open(filepath, 'wb') as file_: shutil.copyfileobj(response, file_) return filepath
python
def download(url, directory, filename=None): """ Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. """ if not filename: _, filename = os.path.split(url) directory = os.path.expanduser(directory) ensure_directory(directory) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): return filepath print('Download', filepath) with urlopen(url) as response, open(filepath, 'wb') as file_: shutil.copyfileobj(response, file_) return filepath
[ "def", "download", "(", "url", ",", "directory", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "_", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "url", ")", "directory", "=", "os", ".", "path", ".", "expanduser", "(", "directory", ")", "ensure_directory", "(", "directory", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "filepath", ")", ":", "return", "filepath", "print", "(", "'Download'", ",", "filepath", ")", "with", "urlopen", "(", "url", ")", "as", "response", ",", "open", "(", "filepath", ",", "'wb'", ")", "as", "file_", ":", "shutil", ".", "copyfileobj", "(", "response", ",", "file_", ")", "return", "filepath" ]
Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath.
[ "Download", "a", "file", "and", "return", "its", "filename", "on", "the", "local", "file", "system", ".", "If", "the", "file", "is", "already", "there", "it", "will", "not", "be", "downloaded", "again", ".", "The", "filename", "is", "derived", "from", "the", "url", "if", "not", "provided", ".", "Return", "the", "filepath", "." ]
2542c28f43d0af18932cb5b82f54ffb6ae557d12
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/utility.py#L53-L69
train
danijar/sets
sets/utility.py
ensure_directory
def ensure_directory(directory): """ Create the directories along the provided directory path that do not exist. """ directory = os.path.expanduser(directory) try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise e
python
def ensure_directory(directory): """ Create the directories along the provided directory path that do not exist. """ directory = os.path.expanduser(directory) try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise e
[ "def", "ensure_directory", "(", "directory", ")", ":", "directory", "=", "os", ".", "path", ".", "expanduser", "(", "directory", ")", "try", ":", "os", ".", "makedirs", "(", "directory", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "e" ]
Create the directories along the provided directory path that do not exist.
[ "Create", "the", "directories", "along", "the", "provided", "directory", "path", "that", "do", "not", "exist", "." ]
2542c28f43d0af18932cb5b82f54ffb6ae557d12
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/utility.py#L71-L80
train
smarie/python-valid8
valid8/composition.py
_process_validation_function_s
def _process_validation_function_s(validation_func, # type: ValidationFuncs auto_and_wrapper=True # type: bool ): # type: (...) -> Union[Callable, List[Callable]] """ This function handles the various ways that users may enter 'validation functions', so as to output a single callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead. valid8 supports the following expressions for 'validation functions' * <ValidationFunc> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return: """ # handle the case where validation_func is not yet a list or is empty or none if validation_func is None: raise ValueError('mandatory validation_func is None') elif not isinstance(validation_func, list): # so not use list() because we do not want to convert tuples here. validation_func = [validation_func] elif len(validation_func) == 0: raise ValueError('provided validation_func list is empty') # now validation_func is a non-empty list final_list = [] for v in validation_func: # special case of a LambdaExpression: automatically convert to a function # note: we have to do it before anything else (such as .index) otherwise we may get failures v = as_function(v) if isinstance(v, tuple): # convert all the tuples to failure raisers if len(v) == 2: if isinstance(v[1], str): final_list.append(_failure_raiser(v[0], help_msg=v[1])) elif isinstance(v[1], type) and issubclass(v[1], WrappingFailure): final_list.append(_failure_raiser(v[0], failure_type=v[1])) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) elif callable(v): # use the validator directly final_list.append(v) elif isinstance(v, list): # a list is an implicit and_, make it explicit final_list.append(and_(*v)) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) # return what is required: if auto_and_wrapper: # a single callable doing the 'and' return and_(*final_list) else: # or the list (typically for use inside or_(), xor_()...) return final_list
python
def _process_validation_function_s(validation_func, # type: ValidationFuncs auto_and_wrapper=True # type: bool ): # type: (...) -> Union[Callable, List[Callable]] """ This function handles the various ways that users may enter 'validation functions', so as to output a single callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead. valid8 supports the following expressions for 'validation functions' * <ValidationFunc> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return: """ # handle the case where validation_func is not yet a list or is empty or none if validation_func is None: raise ValueError('mandatory validation_func is None') elif not isinstance(validation_func, list): # so not use list() because we do not want to convert tuples here. validation_func = [validation_func] elif len(validation_func) == 0: raise ValueError('provided validation_func list is empty') # now validation_func is a non-empty list final_list = [] for v in validation_func: # special case of a LambdaExpression: automatically convert to a function # note: we have to do it before anything else (such as .index) otherwise we may get failures v = as_function(v) if isinstance(v, tuple): # convert all the tuples to failure raisers if len(v) == 2: if isinstance(v[1], str): final_list.append(_failure_raiser(v[0], help_msg=v[1])) elif isinstance(v[1], type) and issubclass(v[1], WrappingFailure): final_list.append(_failure_raiser(v[0], failure_type=v[1])) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) elif callable(v): # use the validator directly final_list.append(v) elif isinstance(v, list): # a list is an implicit and_, make it explicit final_list.append(and_(*v)) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) # return what is required: if auto_and_wrapper: # a single callable doing the 'and' return and_(*final_list) else: # or the list (typically for use inside or_(), xor_()...) return final_list
[ "def", "_process_validation_function_s", "(", "validation_func", ",", "# type: ValidationFuncs", "auto_and_wrapper", "=", "True", "# type: bool", ")", ":", "# type: (...) -> Union[Callable, List[Callable]]", "# handle the case where validation_func is not yet a list or is empty or none", "if", "validation_func", "is", "None", ":", "raise", "ValueError", "(", "'mandatory validation_func is None'", ")", "elif", "not", "isinstance", "(", "validation_func", ",", "list", ")", ":", "# so not use list() because we do not want to convert tuples here.", "validation_func", "=", "[", "validation_func", "]", "elif", "len", "(", "validation_func", ")", "==", "0", ":", "raise", "ValueError", "(", "'provided validation_func list is empty'", ")", "# now validation_func is a non-empty list", "final_list", "=", "[", "]", "for", "v", "in", "validation_func", ":", "# special case of a LambdaExpression: automatically convert to a function", "# note: we have to do it before anything else (such as .index) otherwise we may get failures", "v", "=", "as_function", "(", "v", ")", "if", "isinstance", "(", "v", ",", "tuple", ")", ":", "# convert all the tuples to failure raisers", "if", "len", "(", "v", ")", "==", "2", ":", "if", "isinstance", "(", "v", "[", "1", "]", ",", "str", ")", ":", "final_list", ".", "append", "(", "_failure_raiser", "(", "v", "[", "0", "]", ",", "help_msg", "=", "v", "[", "1", "]", ")", ")", "elif", "isinstance", "(", "v", "[", "1", "]", ",", "type", ")", "and", "issubclass", "(", "v", "[", "1", "]", ",", "WrappingFailure", ")", ":", "final_list", ".", "append", "(", "_failure_raiser", "(", "v", "[", "0", "]", ",", "failure_type", "=", "v", "[", "1", "]", ")", ")", "else", ":", "raise", "TypeError", "(", "'base validation function(s) not compliant with the allowed syntax. Base validation'", "' function(s) can be {}. Found [{}].'", ".", "format", "(", "supported_syntax", ",", "str", "(", "v", ")", ")", ")", "else", ":", "raise", "TypeError", "(", "'base validation function(s) not compliant with the allowed syntax. Base validation'", "' function(s) can be {}. Found [{}].'", ".", "format", "(", "supported_syntax", ",", "str", "(", "v", ")", ")", ")", "elif", "callable", "(", "v", ")", ":", "# use the validator directly", "final_list", ".", "append", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "list", ")", ":", "# a list is an implicit and_, make it explicit", "final_list", ".", "append", "(", "and_", "(", "*", "v", ")", ")", "else", ":", "raise", "TypeError", "(", "'base validation function(s) not compliant with the allowed syntax. Base validation'", "' function(s) can be {}. Found [{}].'", ".", "format", "(", "supported_syntax", ",", "str", "(", "v", ")", ")", ")", "# return what is required:", "if", "auto_and_wrapper", ":", "# a single callable doing the 'and'", "return", "and_", "(", "*", "final_list", ")", "else", ":", "# or the list (typically for use inside or_(), xor_()...)", "return", "final_list" ]
This function handles the various ways that users may enter 'validation functions', so as to output a single callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead. valid8 supports the following expressions for 'validation functions' * <ValidationFunc> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return:
[ "This", "function", "handles", "the", "various", "ways", "that", "users", "may", "enter", "validation", "functions", "so", "as", "to", "output", "a", "single", "callable", "method", ".", "Setting", "auto_and_wrapper", "to", "False", "allows", "callers", "to", "get", "a", "list", "of", "callables", "instead", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L43-L125
train
smarie/python-valid8
valid8/composition.py
and_
def and_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_` is performed if you provide a list of validators to any of the entry points (`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case: no wrapper else: def and_v_(x): for validator in validation_func: try: res = validator(x) except Exception as e: # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x, cause=e) if not result_is_success(res): # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x) return True and_v_.__name__ = 'and({})'.format(get_callable_names(validation_func)) return and_v_
python
def and_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_` is performed if you provide a list of validators to any of the entry points (`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case: no wrapper else: def and_v_(x): for validator in validation_func: try: res = validator(x) except Exception as e: # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x, cause=e) if not result_is_success(res): # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x) return True and_v_.__name__ = 'and({})'.format(get_callable_names(validation_func)) return and_v_
[ "def", "and_", "(", "*", "validation_func", "# type: ValidationFuncs", ")", ":", "# type: (...) -> Callable", "validation_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ",", "auto_and_wrapper", "=", "False", ")", "if", "len", "(", "validation_func", ")", "==", "1", ":", "return", "validation_func", "[", "0", "]", "# simplification for single validator case: no wrapper", "else", ":", "def", "and_v_", "(", "x", ")", ":", "for", "validator", "in", "validation_func", ":", "try", ":", "res", "=", "validator", "(", "x", ")", "except", "Exception", "as", "e", ":", "# one validator was unhappy > raise", "raise", "AtLeastOneFailed", "(", "validation_func", ",", "x", ",", "cause", "=", "e", ")", "if", "not", "result_is_success", "(", "res", ")", ":", "# one validator was unhappy > raise", "raise", "AtLeastOneFailed", "(", "validation_func", ",", "x", ")", "return", "True", "and_v_", ".", "__name__", "=", "'and({})'", ".", "format", "(", "get_callable_names", "(", "validation_func", ")", ")", "return", "and_v_" ]
An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_` is performed if you provide a list of validators to any of the entry points (`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "An", "and", "validator", ":", "it", "returns", "True", "if", "all", "of", "the", "provided", "validators", "return", "True", "or", "raises", "a", "AtLeastOneFailed", "failure", "on", "the", "first", "False", "received", "or", "Exception", "caught", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L229-L266
train
smarie/python-valid8
valid8/composition.py
not_
def not_(validation_func, # type: ValidationFuncs catch_all=False # type: bool ): # type: (...) -> Callable """ Generates the inverse of the provided validation functions: when the validator returns `False` or raises a `Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ def not_v_(x): try: res = validation_func(x) if not result_is_success(res): # inverse the result return True except Failure: return True # caught failure: always return True except Exception as e: if not catch_all: raise e else: return True # caught exception in 'catch_all' mode: return True # if we're here that's a failure raise DidNotFail(wrapped_func=validation_func, wrong_value=x, validation_outcome=res) not_v_.__name__ = 'not({})'.format(get_callable_name(validation_func)) return not_v_
python
def not_(validation_func, # type: ValidationFuncs catch_all=False # type: bool ): # type: (...) -> Callable """ Generates the inverse of the provided validation functions: when the validator returns `False` or raises a `Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ def not_v_(x): try: res = validation_func(x) if not result_is_success(res): # inverse the result return True except Failure: return True # caught failure: always return True except Exception as e: if not catch_all: raise e else: return True # caught exception in 'catch_all' mode: return True # if we're here that's a failure raise DidNotFail(wrapped_func=validation_func, wrong_value=x, validation_outcome=res) not_v_.__name__ = 'not({})'.format(get_callable_name(validation_func)) return not_v_
[ "def", "not_", "(", "validation_func", ",", "# type: ValidationFuncs", "catch_all", "=", "False", "# type: bool", ")", ":", "# type: (...) -> Callable", "def", "not_v_", "(", "x", ")", ":", "try", ":", "res", "=", "validation_func", "(", "x", ")", "if", "not", "result_is_success", "(", "res", ")", ":", "# inverse the result", "return", "True", "except", "Failure", ":", "return", "True", "# caught failure: always return True", "except", "Exception", "as", "e", ":", "if", "not", "catch_all", ":", "raise", "e", "else", ":", "return", "True", "# caught exception in 'catch_all' mode: return True", "# if we're here that's a failure", "raise", "DidNotFail", "(", "wrapped_func", "=", "validation_func", ",", "wrong_value", "=", "x", ",", "validation_outcome", "=", "res", ")", "not_v_", ".", "__name__", "=", "'not({})'", ".", "format", "(", "get_callable_name", "(", "validation_func", ")", ")", "return", "not_v_" ]
Generates the inverse of the provided validation functions: when the validator returns `False` or raises a `Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return:
[ "Generates", "the", "inverse", "of", "the", "provided", "validation", "functions", ":", "when", "the", "validator", "returns", "False", "or", "raises", "a", "Failure", "this", "function", "returns", "True", ".", "Otherwise", "it", "raises", "a", "DidNotFail", "failure", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L274-L319
train
smarie/python-valid8
valid8/composition.py
or_
def or_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details about all validation results. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case else: def or_v_(x): for validator in validation_func: # noinspection PyBroadException try: res = validator(x) if result_is_success(res): # we can return : one validator was happy return True except Exception: # catch all silently pass # no validator accepted: gather details and raise raise AllValidatorsFailed(validation_func, x) or_v_.__name__ = 'or({})'.format(get_callable_names(validation_func)) return or_v_
python
def or_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details about all validation results. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case else: def or_v_(x): for validator in validation_func: # noinspection PyBroadException try: res = validator(x) if result_is_success(res): # we can return : one validator was happy return True except Exception: # catch all silently pass # no validator accepted: gather details and raise raise AllValidatorsFailed(validation_func, x) or_v_.__name__ = 'or({})'.format(get_callable_names(validation_func)) return or_v_
[ "def", "or_", "(", "*", "validation_func", "# type: ValidationFuncs", ")", ":", "# type: (...) -> Callable", "validation_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ",", "auto_and_wrapper", "=", "False", ")", "if", "len", "(", "validation_func", ")", "==", "1", ":", "return", "validation_func", "[", "0", "]", "# simplification for single validator case", "else", ":", "def", "or_v_", "(", "x", ")", ":", "for", "validator", "in", "validation_func", ":", "# noinspection PyBroadException", "try", ":", "res", "=", "validator", "(", "x", ")", "if", "result_is_success", "(", "res", ")", ":", "# we can return : one validator was happy", "return", "True", "except", "Exception", ":", "# catch all silently", "pass", "# no validator accepted: gather details and raise", "raise", "AllValidatorsFailed", "(", "validation_func", ",", "x", ")", "or_v_", ".", "__name__", "=", "'or({})'", ".", "format", "(", "get_callable_names", "(", "validation_func", ")", ")", "return", "or_v_" ]
An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details about all validation results. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "An", "or", "validator", ":", "returns", "True", "if", "at", "least", "one", "of", "the", "provided", "validators", "returns", "True", ".", "All", "exceptions", "will", "be", "silently", "caught", ".", "In", "case", "of", "failure", "a", "global", "AllValidatorsFailed", "failure", "will", "be", "raised", "together", "with", "details", "about", "all", "validation", "results", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L330-L367
train
smarie/python-valid8
valid8/composition.py
xor_
def xor_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised, together with details about the various validation results. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validation function case else: def xor_v_(x): ok_validators = [] for val_func in validation_func: # noinspection PyBroadException try: res = val_func(x) if result_is_success(res): ok_validators.append(val_func) except Exception: pass # return if were happy or not if len(ok_validators) == 1: # one unique validation function happy: success return True elif len(ok_validators) > 1: # several validation_func happy : fail raise XorTooManySuccess(validation_func, x) else: # no validation function happy, fail raise AllValidatorsFailed(validation_func, x) xor_v_.__name__ = 'xor({})'.format(get_callable_names(validation_func)) return xor_v_
python
def xor_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised, together with details about the various validation results. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validation function case else: def xor_v_(x): ok_validators = [] for val_func in validation_func: # noinspection PyBroadException try: res = val_func(x) if result_is_success(res): ok_validators.append(val_func) except Exception: pass # return if were happy or not if len(ok_validators) == 1: # one unique validation function happy: success return True elif len(ok_validators) > 1: # several validation_func happy : fail raise XorTooManySuccess(validation_func, x) else: # no validation function happy, fail raise AllValidatorsFailed(validation_func, x) xor_v_.__name__ = 'xor({})'.format(get_callable_names(validation_func)) return xor_v_
[ "def", "xor_", "(", "*", "validation_func", "# type: ValidationFuncs", ")", ":", "# type: (...) -> Callable", "validation_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ",", "auto_and_wrapper", "=", "False", ")", "if", "len", "(", "validation_func", ")", "==", "1", ":", "return", "validation_func", "[", "0", "]", "# simplification for single validation function case", "else", ":", "def", "xor_v_", "(", "x", ")", ":", "ok_validators", "=", "[", "]", "for", "val_func", "in", "validation_func", ":", "# noinspection PyBroadException", "try", ":", "res", "=", "val_func", "(", "x", ")", "if", "result_is_success", "(", "res", ")", ":", "ok_validators", ".", "append", "(", "val_func", ")", "except", "Exception", ":", "pass", "# return if were happy or not", "if", "len", "(", "ok_validators", ")", "==", "1", ":", "# one unique validation function happy: success", "return", "True", "elif", "len", "(", "ok_validators", ")", ">", "1", ":", "# several validation_func happy : fail", "raise", "XorTooManySuccess", "(", "validation_func", ",", "x", ")", "else", ":", "# no validation function happy, fail", "raise", "AllValidatorsFailed", "(", "validation_func", ",", "x", ")", "xor_v_", ".", "__name__", "=", "'xor({})'", ".", "format", "(", "get_callable_names", "(", "validation_func", ")", ")", "return", "xor_v_" ]
A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised, together with details about the various validation results. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "A", "xor", "validation", "function", ":", "returns", "True", "if", "exactly", "one", "of", "the", "provided", "validators", "returns", "True", ".", "All", "exceptions", "will", "be", "silently", "caught", ".", "In", "case", "of", "failure", "a", "global", "XorTooManySuccess", "or", "AllValidatorsFailed", "will", "be", "raised", "together", "with", "details", "about", "the", "various", "validation", "results", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L378-L424
train
smarie/python-valid8
valid8/composition.py
not_all
def not_all(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ An alias for not_(and_(validators)). :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ catch_all = pop_kwargs(kwargs, [('catch_all', False)]) # in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without # wrapping it) main_validator = and_(*validation_func) return not_(main_validator, catch_all=catch_all)
python
def not_all(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ An alias for not_(and_(validators)). :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ catch_all = pop_kwargs(kwargs, [('catch_all', False)]) # in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without # wrapping it) main_validator = and_(*validation_func) return not_(main_validator, catch_all=catch_all)
[ "def", "not_all", "(", "*", "validation_func", ",", "# type: ValidationFuncs", "*", "*", "kwargs", ")", ":", "# type: (...) -> Callable", "catch_all", "=", "pop_kwargs", "(", "kwargs", ",", "[", "(", "'catch_all'", ",", "False", ")", "]", ")", "# in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without", "# wrapping it)", "main_validator", "=", "and_", "(", "*", "validation_func", ")", "return", "not_", "(", "main_validator", ",", "catch_all", "=", "catch_all", ")" ]
An alias for not_(and_(validators)). :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return:
[ "An", "alias", "for", "not_", "(", "and_", "(", "validators", "))", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L436-L458
train
smarie/python-valid8
valid8/composition.py
failure_raiser
def failure_raiser(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception) :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return: """ failure_type, help_msg = pop_kwargs(kwargs, [('failure_type', None), ('help_msg', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs main_func = _process_validation_function_s(list(validation_func)) return _failure_raiser(main_func, failure_type=failure_type, help_msg=help_msg, **kw_context_args)
python
def failure_raiser(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception) :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return: """ failure_type, help_msg = pop_kwargs(kwargs, [('failure_type', None), ('help_msg', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs main_func = _process_validation_function_s(list(validation_func)) return _failure_raiser(main_func, failure_type=failure_type, help_msg=help_msg, **kw_context_args)
[ "def", "failure_raiser", "(", "*", "validation_func", ",", "# type: ValidationFuncs", "*", "*", "kwargs", ")", ":", "# type: (...) -> Callable", "failure_type", ",", "help_msg", "=", "pop_kwargs", "(", "kwargs", ",", "[", "(", "'failure_type'", ",", "None", ")", ",", "(", "'help_msg'", ",", "None", ")", "]", ",", "allow_others", "=", "True", ")", "# the rest of keyword arguments is used as context.", "kw_context_args", "=", "kwargs", "main_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ")", "return", "_failure_raiser", "(", "main_func", ",", "failure_type", "=", "failure_type", ",", "help_msg", "=", "help_msg", ",", "*", "*", "kw_context_args", ")" ]
This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception) :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return:
[ "This", "function", "is", "automatically", "used", "if", "you", "provide", "a", "tuple", "(", "<function", ">", "<msg", ">", "_or_<Failure_type", ">", ")", "to", "any", "of", "the", "methods", "in", "this", "page", "or", "to", "one", "of", "the", "valid8", "decorators", ".", "It", "transforms", "the", "provided", "<function", ">", "into", "a", "failure", "raiser", "raising", "a", "subclass", "of", "Failure", "in", "case", "of", "failure", "(", "either", "not", "returning", "True", "or", "raising", "an", "exception", ")" ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L473-L498
train
smarie/python-valid8
valid8/composition.py
pop_kwargs
def pop_kwargs(kwargs, names_with_defaults, # type: List[Tuple[str, Any]] allow_others=False ): """ Internal utility method to extract optional arguments from kwargs. :param kwargs: :param names_with_defaults: :param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end. :return: """ all_arguments = [] for name, default_ in names_with_defaults: try: val = kwargs.pop(name) except KeyError: val = default_ all_arguments.append(val) if not allow_others and len(kwargs) > 0: raise ValueError("Unsupported arguments: %s" % kwargs) if len(names_with_defaults) == 1: return all_arguments[0] else: return all_arguments
python
def pop_kwargs(kwargs, names_with_defaults, # type: List[Tuple[str, Any]] allow_others=False ): """ Internal utility method to extract optional arguments from kwargs. :param kwargs: :param names_with_defaults: :param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end. :return: """ all_arguments = [] for name, default_ in names_with_defaults: try: val = kwargs.pop(name) except KeyError: val = default_ all_arguments.append(val) if not allow_others and len(kwargs) > 0: raise ValueError("Unsupported arguments: %s" % kwargs) if len(names_with_defaults) == 1: return all_arguments[0] else: return all_arguments
[ "def", "pop_kwargs", "(", "kwargs", ",", "names_with_defaults", ",", "# type: List[Tuple[str, Any]]", "allow_others", "=", "False", ")", ":", "all_arguments", "=", "[", "]", "for", "name", ",", "default_", "in", "names_with_defaults", ":", "try", ":", "val", "=", "kwargs", ".", "pop", "(", "name", ")", "except", "KeyError", ":", "val", "=", "default_", "all_arguments", ".", "append", "(", "val", ")", "if", "not", "allow_others", "and", "len", "(", "kwargs", ")", ">", "0", ":", "raise", "ValueError", "(", "\"Unsupported arguments: %s\"", "%", "kwargs", ")", "if", "len", "(", "names_with_defaults", ")", "==", "1", ":", "return", "all_arguments", "[", "0", "]", "else", ":", "return", "all_arguments" ]
Internal utility method to extract optional arguments from kwargs. :param kwargs: :param names_with_defaults: :param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end. :return:
[ "Internal", "utility", "method", "to", "extract", "optional", "arguments", "from", "kwargs", "." ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L539-L565
train
smarie/python-valid8
valid8/composition.py
CompositionFailure.get_details
def get_details(self): """ Overrides the base method in order to give details on the various successes and failures """ # transform the dictionary of failures into a printable form need_to_print_value = True failures_for_print = OrderedDict() for validator, failure in self.failures.items(): name = get_callable_name(validator) if isinstance(failure, Exception): if isinstance(failure, WrappingFailure) or isinstance(failure, CompositionFailure): need_to_print_value = False failures_for_print[name] = '{exc_type}: {msg}'.format(exc_type=type(failure).__name__, msg=str(failure)) else: failures_for_print[name] = str(failure) if need_to_print_value: value_str = ' for value [{val}]'.format(val=self.wrong_value) else: value_str = '' # OrderedDict does not pretty print... key_values_str = [repr(key) + ': ' + repr(val) for key, val in failures_for_print.items()] failures_for_print_str = '{' + ', '.join(key_values_str) + '}' # Note: we do note cite the value in the message since it is most probably available in inner messages [{val}] msg = '{what}{possibly_value}. Successes: {success} / Failures: {fails}' \ ''.format(what=self.get_what(), possibly_value=value_str, success=self.successes, fails=failures_for_print_str) return msg
python
def get_details(self): """ Overrides the base method in order to give details on the various successes and failures """ # transform the dictionary of failures into a printable form need_to_print_value = True failures_for_print = OrderedDict() for validator, failure in self.failures.items(): name = get_callable_name(validator) if isinstance(failure, Exception): if isinstance(failure, WrappingFailure) or isinstance(failure, CompositionFailure): need_to_print_value = False failures_for_print[name] = '{exc_type}: {msg}'.format(exc_type=type(failure).__name__, msg=str(failure)) else: failures_for_print[name] = str(failure) if need_to_print_value: value_str = ' for value [{val}]'.format(val=self.wrong_value) else: value_str = '' # OrderedDict does not pretty print... key_values_str = [repr(key) + ': ' + repr(val) for key, val in failures_for_print.items()] failures_for_print_str = '{' + ', '.join(key_values_str) + '}' # Note: we do note cite the value in the message since it is most probably available in inner messages [{val}] msg = '{what}{possibly_value}. Successes: {success} / Failures: {fails}' \ ''.format(what=self.get_what(), possibly_value=value_str, success=self.successes, fails=failures_for_print_str) return msg
[ "def", "get_details", "(", "self", ")", ":", "# transform the dictionary of failures into a printable form", "need_to_print_value", "=", "True", "failures_for_print", "=", "OrderedDict", "(", ")", "for", "validator", ",", "failure", "in", "self", ".", "failures", ".", "items", "(", ")", ":", "name", "=", "get_callable_name", "(", "validator", ")", "if", "isinstance", "(", "failure", ",", "Exception", ")", ":", "if", "isinstance", "(", "failure", ",", "WrappingFailure", ")", "or", "isinstance", "(", "failure", ",", "CompositionFailure", ")", ":", "need_to_print_value", "=", "False", "failures_for_print", "[", "name", "]", "=", "'{exc_type}: {msg}'", ".", "format", "(", "exc_type", "=", "type", "(", "failure", ")", ".", "__name__", ",", "msg", "=", "str", "(", "failure", ")", ")", "else", ":", "failures_for_print", "[", "name", "]", "=", "str", "(", "failure", ")", "if", "need_to_print_value", ":", "value_str", "=", "' for value [{val}]'", ".", "format", "(", "val", "=", "self", ".", "wrong_value", ")", "else", ":", "value_str", "=", "''", "# OrderedDict does not pretty print...", "key_values_str", "=", "[", "repr", "(", "key", ")", "+", "': '", "+", "repr", "(", "val", ")", "for", "key", ",", "val", "in", "failures_for_print", ".", "items", "(", ")", "]", "failures_for_print_str", "=", "'{'", "+", "', '", ".", "join", "(", "key_values_str", ")", "+", "'}'", "# Note: we do note cite the value in the message since it is most probably available in inner messages [{val}]", "msg", "=", "'{what}{possibly_value}. Successes: {success} / Failures: {fails}'", "''", ".", "format", "(", "what", "=", "self", ".", "get_what", "(", ")", ",", "possibly_value", "=", "value_str", ",", "success", "=", "self", ".", "successes", ",", "fails", "=", "failures_for_print_str", ")", "return", "msg" ]
Overrides the base method in order to give details on the various successes and failures
[ "Overrides", "the", "base", "method", "in", "order", "to", "give", "details", "on", "the", "various", "successes", "and", "failures" ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L160-L189
train
smarie/python-valid8
valid8/composition.py
CompositionFailure.play_all_validators
def play_all_validators(self, validators, value): """ Utility method to play all the provided validators on the provided value and output the :param validators: :param value: :return: """ successes = list() failures = OrderedDict() for validator in validators: name = get_callable_name(validator) try: res = validator(value) if result_is_success(res): successes.append(name) else: failures[validator] = res except Exception as exc: failures[validator] = exc return successes, failures
python
def play_all_validators(self, validators, value): """ Utility method to play all the provided validators on the provided value and output the :param validators: :param value: :return: """ successes = list() failures = OrderedDict() for validator in validators: name = get_callable_name(validator) try: res = validator(value) if result_is_success(res): successes.append(name) else: failures[validator] = res except Exception as exc: failures[validator] = exc return successes, failures
[ "def", "play_all_validators", "(", "self", ",", "validators", ",", "value", ")", ":", "successes", "=", "list", "(", ")", "failures", "=", "OrderedDict", "(", ")", "for", "validator", "in", "validators", ":", "name", "=", "get_callable_name", "(", "validator", ")", "try", ":", "res", "=", "validator", "(", "value", ")", "if", "result_is_success", "(", "res", ")", ":", "successes", ".", "append", "(", "name", ")", "else", ":", "failures", "[", "validator", "]", "=", "res", "except", "Exception", "as", "exc", ":", "failures", "[", "validator", "]", "=", "exc", "return", "successes", ",", "failures" ]
Utility method to play all the provided validators on the provided value and output the :param validators: :param value: :return:
[ "Utility", "method", "to", "play", "all", "the", "provided", "validators", "on", "the", "provided", "value", "and", "output", "the" ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L191-L213
train
redhat-cip/dci-control-server
dci/common/signature.py
gen_secret
def gen_secret(length=64): """ Generates a secret of given length """ charset = string.ascii_letters + string.digits return ''.join(random.SystemRandom().choice(charset) for _ in range(length))
python
def gen_secret(length=64): """ Generates a secret of given length """ charset = string.ascii_letters + string.digits return ''.join(random.SystemRandom().choice(charset) for _ in range(length))
[ "def", "gen_secret", "(", "length", "=", "64", ")", ":", "charset", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "return", "''", ".", "join", "(", "random", ".", "SystemRandom", "(", ")", ".", "choice", "(", "charset", ")", "for", "_", "in", "range", "(", "length", ")", ")" ]
Generates a secret of given length
[ "Generates", "a", "secret", "of", "given", "length" ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/common/signature.py#L21-L26
train
Antidote1911/cryptoshop
cryptoshop/cryptoshop.py
encryptfile
def encryptfile(filename, passphrase, algo='srp'): """ Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp. :return: a string with "successfully encrypted" or error. """ try: if algo == "srp": header = b"Cryptoshop srp " + b_version crypto_algo = "Serpent/GCM" if algo == "aes": header = b"Cryptoshop aes " + b_version crypto_algo = "AES-256/GCM" if algo == "twf": header = b"Cryptoshop twf " + b_version crypto_algo = "Twofish/GCM" if algo != "srp" and algo != "aes" and algo != "twf": return "No valid algo. Use 'srp' 'aes' or 'twf'" outname = filename + ".cryptoshop" internal_key = botan.rng().get(internal_key_length) # Passphrase derivation... salt = botan.rng().get(__salt_size__) masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Encrypt internal key... encrypted_key = encry_decry_cascade(data=internal_key, masterkey=masterkey, bool_encry=True, assoc_data=header) with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't encrypt empty file.") with open(str(outname), 'wb') as filestreamout: filestreamout.write(header) filestreamout.write(salt) filestreamout.write(encrypted_key) finished = False # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(file_size // __chunk_size__)) while not finished: chunk = filestream.read(__chunk_size__) if len(chunk) == 0 or len(chunk) % __chunk_size__ != 0: finished = True # An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = encry_decry_chunk(chunk=chunk, key=internal_key, bool_encry=True, algo=crypto_algo, assoc_data=header) filestreamout.write(encryptedchunk) bar.update(1) return "successfully encrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
python
def encryptfile(filename, passphrase, algo='srp'): """ Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp. :return: a string with "successfully encrypted" or error. """ try: if algo == "srp": header = b"Cryptoshop srp " + b_version crypto_algo = "Serpent/GCM" if algo == "aes": header = b"Cryptoshop aes " + b_version crypto_algo = "AES-256/GCM" if algo == "twf": header = b"Cryptoshop twf " + b_version crypto_algo = "Twofish/GCM" if algo != "srp" and algo != "aes" and algo != "twf": return "No valid algo. Use 'srp' 'aes' or 'twf'" outname = filename + ".cryptoshop" internal_key = botan.rng().get(internal_key_length) # Passphrase derivation... salt = botan.rng().get(__salt_size__) masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Encrypt internal key... encrypted_key = encry_decry_cascade(data=internal_key, masterkey=masterkey, bool_encry=True, assoc_data=header) with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't encrypt empty file.") with open(str(outname), 'wb') as filestreamout: filestreamout.write(header) filestreamout.write(salt) filestreamout.write(encrypted_key) finished = False # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(file_size // __chunk_size__)) while not finished: chunk = filestream.read(__chunk_size__) if len(chunk) == 0 or len(chunk) % __chunk_size__ != 0: finished = True # An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = encry_decry_chunk(chunk=chunk, key=internal_key, bool_encry=True, algo=crypto_algo, assoc_data=header) filestreamout.write(encryptedchunk) bar.update(1) return "successfully encrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
[ "def", "encryptfile", "(", "filename", ",", "passphrase", ",", "algo", "=", "'srp'", ")", ":", "try", ":", "if", "algo", "==", "\"srp\"", ":", "header", "=", "b\"Cryptoshop srp \"", "+", "b_version", "crypto_algo", "=", "\"Serpent/GCM\"", "if", "algo", "==", "\"aes\"", ":", "header", "=", "b\"Cryptoshop aes \"", "+", "b_version", "crypto_algo", "=", "\"AES-256/GCM\"", "if", "algo", "==", "\"twf\"", ":", "header", "=", "b\"Cryptoshop twf \"", "+", "b_version", "crypto_algo", "=", "\"Twofish/GCM\"", "if", "algo", "!=", "\"srp\"", "and", "algo", "!=", "\"aes\"", "and", "algo", "!=", "\"twf\"", ":", "return", "\"No valid algo. Use 'srp' 'aes' or 'twf'\"", "outname", "=", "filename", "+", "\".cryptoshop\"", "internal_key", "=", "botan", ".", "rng", "(", ")", ".", "get", "(", "internal_key_length", ")", "# Passphrase derivation...", "salt", "=", "botan", ".", "rng", "(", ")", ".", "get", "(", "__salt_size__", ")", "masterkey", "=", "calc_derivation", "(", "passphrase", "=", "passphrase", ",", "salt", "=", "salt", ")", "# Encrypt internal key...", "encrypted_key", "=", "encry_decry_cascade", "(", "data", "=", "internal_key", ",", "masterkey", "=", "masterkey", ",", "bool_encry", "=", "True", ",", "assoc_data", "=", "header", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "filestream", ":", "file_size", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "if", "file_size", "==", "0", ":", "raise", "Exception", "(", "\"Error: You can't encrypt empty file.\"", ")", "with", "open", "(", "str", "(", "outname", ")", ",", "'wb'", ")", "as", "filestreamout", ":", "filestreamout", ".", "write", "(", "header", ")", "filestreamout", ".", "write", "(", "salt", ")", "filestreamout", ".", "write", "(", "encrypted_key", ")", "finished", "=", "False", "# the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size", "bar", "=", "tqdm", "(", "range", "(", "file_size", "//", "__chunk_size__", ")", ")", "while", "not", "finished", ":", "chunk", "=", "filestream", ".", "read", "(", "__chunk_size__", ")", "if", "len", "(", "chunk", ")", "==", "0", "or", "len", "(", "chunk", ")", "%", "__chunk_size__", "!=", "0", ":", "finished", "=", "True", "# An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation.", "encryptedchunk", "=", "encry_decry_chunk", "(", "chunk", "=", "chunk", ",", "key", "=", "internal_key", ",", "bool_encry", "=", "True", ",", "algo", "=", "crypto_algo", ",", "assoc_data", "=", "header", ")", "filestreamout", ".", "write", "(", "encryptedchunk", ")", "bar", ".", "update", "(", "1", ")", "return", "\"successfully encrypted\"", "except", "IOError", ":", "exit", "(", "\"Error: file \\\"\"", "+", "filename", "+", "\"\\\" was not found.\"", ")" ]
Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp. :return: a string with "successfully encrypted" or error.
[ "Encrypt", "a", "file", "and", "write", "it", "with", ".", "cryptoshop", "extension", ".", ":", "param", "filename", ":", "a", "string", "with", "the", "path", "to", "the", "file", "to", "encrypt", ".", ":", "param", "passphrase", ":", "a", "string", "with", "the", "user", "passphrase", ".", ":", "param", "algo", ":", "a", "string", "with", "the", "algorithm", ".", "Can", "be", "srp", "aes", "twf", ".", "Default", "is", "srp", ".", ":", "return", ":", "a", "string", "with", "successfully", "encrypted", "or", "error", "." ]
0b7ff4a6848f2733f4737606957e8042a4d6ca0b
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/cryptoshop.py#L104-L161
train
Antidote1911/cryptoshop
cryptoshop/cryptoshop.py
decryptfile
def decryptfile(filename, passphrase): """ Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension. :param filename: a string with the path to the file to decrypt. :param passphrase: a string with the user passphrase. :return: a string with "successfully decrypted" or error. """ try: outname = os.path.splitext(filename)[0].split("_")[-1] # create a string file name without extension. with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't decrypt empty file.") fileheader = filestream.read(header_length) if fileheader == b"Cryptoshop srp " + b_version: decrypt_algo = "Serpent/GCM" if fileheader == b"Cryptoshop aes " + b_version: decrypt_algo = "AES-256/GCM" if fileheader == b"Cryptoshop twf " + b_version: decrypt_algo = "Twofish/GCM" if fileheader != b"Cryptoshop srp " + b_version and fileheader != b"Cryptoshop aes " + b_version and fileheader != b"Cryptoshop twf " + b_version: raise Exception("Integrity failure: Bad header") salt = filestream.read(__salt_size__) encrypted_key = filestream.read(encrypted_key_length) # Derive the passphrase... masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Decrypt internal key... try: internal_key = encry_decry_cascade(data=encrypted_key, masterkey=masterkey, bool_encry=False, assoc_data=fileheader) except Exception as e: return e with open(str(outname), 'wb') as filestreamout: files_size = os.stat(filename).st_size # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(files_size // __chunk_size__)) while True: # Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = filestream.read(__nonce_length__ + __gcmtag_length__ + __chunk_size__) if len(encryptedchunk) == 0: break # Chunk decryption. try: original = encry_decry_chunk(chunk=encryptedchunk, key=internal_key, algo=decrypt_algo, bool_encry=False, assoc_data=fileheader) except Exception as e: return e else: filestreamout.write(original) bar.update(1) return "successfully decrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
python
def decryptfile(filename, passphrase): """ Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension. :param filename: a string with the path to the file to decrypt. :param passphrase: a string with the user passphrase. :return: a string with "successfully decrypted" or error. """ try: outname = os.path.splitext(filename)[0].split("_")[-1] # create a string file name without extension. with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't decrypt empty file.") fileheader = filestream.read(header_length) if fileheader == b"Cryptoshop srp " + b_version: decrypt_algo = "Serpent/GCM" if fileheader == b"Cryptoshop aes " + b_version: decrypt_algo = "AES-256/GCM" if fileheader == b"Cryptoshop twf " + b_version: decrypt_algo = "Twofish/GCM" if fileheader != b"Cryptoshop srp " + b_version and fileheader != b"Cryptoshop aes " + b_version and fileheader != b"Cryptoshop twf " + b_version: raise Exception("Integrity failure: Bad header") salt = filestream.read(__salt_size__) encrypted_key = filestream.read(encrypted_key_length) # Derive the passphrase... masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Decrypt internal key... try: internal_key = encry_decry_cascade(data=encrypted_key, masterkey=masterkey, bool_encry=False, assoc_data=fileheader) except Exception as e: return e with open(str(outname), 'wb') as filestreamout: files_size = os.stat(filename).st_size # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(files_size // __chunk_size__)) while True: # Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = filestream.read(__nonce_length__ + __gcmtag_length__ + __chunk_size__) if len(encryptedchunk) == 0: break # Chunk decryption. try: original = encry_decry_chunk(chunk=encryptedchunk, key=internal_key, algo=decrypt_algo, bool_encry=False, assoc_data=fileheader) except Exception as e: return e else: filestreamout.write(original) bar.update(1) return "successfully decrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
[ "def", "decryptfile", "(", "filename", ",", "passphrase", ")", ":", "try", ":", "outname", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", ".", "split", "(", "\"_\"", ")", "[", "-", "1", "]", "# create a string file name without extension.", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "filestream", ":", "file_size", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "if", "file_size", "==", "0", ":", "raise", "Exception", "(", "\"Error: You can't decrypt empty file.\"", ")", "fileheader", "=", "filestream", ".", "read", "(", "header_length", ")", "if", "fileheader", "==", "b\"Cryptoshop srp \"", "+", "b_version", ":", "decrypt_algo", "=", "\"Serpent/GCM\"", "if", "fileheader", "==", "b\"Cryptoshop aes \"", "+", "b_version", ":", "decrypt_algo", "=", "\"AES-256/GCM\"", "if", "fileheader", "==", "b\"Cryptoshop twf \"", "+", "b_version", ":", "decrypt_algo", "=", "\"Twofish/GCM\"", "if", "fileheader", "!=", "b\"Cryptoshop srp \"", "+", "b_version", "and", "fileheader", "!=", "b\"Cryptoshop aes \"", "+", "b_version", "and", "fileheader", "!=", "b\"Cryptoshop twf \"", "+", "b_version", ":", "raise", "Exception", "(", "\"Integrity failure: Bad header\"", ")", "salt", "=", "filestream", ".", "read", "(", "__salt_size__", ")", "encrypted_key", "=", "filestream", ".", "read", "(", "encrypted_key_length", ")", "# Derive the passphrase...", "masterkey", "=", "calc_derivation", "(", "passphrase", "=", "passphrase", ",", "salt", "=", "salt", ")", "# Decrypt internal key...", "try", ":", "internal_key", "=", "encry_decry_cascade", "(", "data", "=", "encrypted_key", ",", "masterkey", "=", "masterkey", ",", "bool_encry", "=", "False", ",", "assoc_data", "=", "fileheader", ")", "except", "Exception", "as", "e", ":", "return", "e", "with", "open", "(", "str", "(", "outname", ")", ",", "'wb'", ")", "as", "filestreamout", ":", "files_size", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "# the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size", "bar", "=", "tqdm", "(", "range", "(", "files_size", "//", "__chunk_size__", ")", ")", "while", "True", ":", "# Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation.", "encryptedchunk", "=", "filestream", ".", "read", "(", "__nonce_length__", "+", "__gcmtag_length__", "+", "__chunk_size__", ")", "if", "len", "(", "encryptedchunk", ")", "==", "0", ":", "break", "# Chunk decryption.", "try", ":", "original", "=", "encry_decry_chunk", "(", "chunk", "=", "encryptedchunk", ",", "key", "=", "internal_key", ",", "algo", "=", "decrypt_algo", ",", "bool_encry", "=", "False", ",", "assoc_data", "=", "fileheader", ")", "except", "Exception", "as", "e", ":", "return", "e", "else", ":", "filestreamout", ".", "write", "(", "original", ")", "bar", ".", "update", "(", "1", ")", "return", "\"successfully decrypted\"", "except", "IOError", ":", "exit", "(", "\"Error: file \\\"\"", "+", "filename", "+", "\"\\\" was not found.\"", ")" ]
Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension. :param filename: a string with the path to the file to decrypt. :param passphrase: a string with the user passphrase. :return: a string with "successfully decrypted" or error.
[ "Decrypt", "a", "file", "and", "write", "corresponding", "decrypted", "file", ".", "We", "remove", "the", ".", "cryptoshop", "extension", ".", ":", "param", "filename", ":", "a", "string", "with", "the", "path", "to", "the", "file", "to", "decrypt", ".", ":", "param", "passphrase", ":", "a", "string", "with", "the", "user", "passphrase", ".", ":", "return", ":", "a", "string", "with", "successfully", "decrypted", "or", "error", "." ]
0b7ff4a6848f2733f4737606957e8042a4d6ca0b
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/cryptoshop.py#L164-L225
train
danijar/sets
sets/process/tokenize.py
Tokenize._tokenize
def _tokenize(cls, sentence): """ Split a sentence while preserving tags. """ while True: match = cls._regex_tag.search(sentence) if not match: yield from cls._split(sentence) return chunk = sentence[:match.start()] yield from cls._split(chunk) tag = match.group(0) yield tag sentence = sentence[(len(chunk) + len(tag)):]
python
def _tokenize(cls, sentence): """ Split a sentence while preserving tags. """ while True: match = cls._regex_tag.search(sentence) if not match: yield from cls._split(sentence) return chunk = sentence[:match.start()] yield from cls._split(chunk) tag = match.group(0) yield tag sentence = sentence[(len(chunk) + len(tag)):]
[ "def", "_tokenize", "(", "cls", ",", "sentence", ")", ":", "while", "True", ":", "match", "=", "cls", ".", "_regex_tag", ".", "search", "(", "sentence", ")", "if", "not", "match", ":", "yield", "from", "cls", ".", "_split", "(", "sentence", ")", "return", "chunk", "=", "sentence", "[", ":", "match", ".", "start", "(", ")", "]", "yield", "from", "cls", ".", "_split", "(", "chunk", ")", "tag", "=", "match", ".", "group", "(", "0", ")", "yield", "tag", "sentence", "=", "sentence", "[", "(", "len", "(", "chunk", ")", "+", "len", "(", "tag", ")", ")", ":", "]" ]
Split a sentence while preserving tags.
[ "Split", "a", "sentence", "while", "preserving", "tags", "." ]
2542c28f43d0af18932cb5b82f54ffb6ae557d12
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/process/tokenize.py#L22-L35
train
mediawiki-utilities/python-mwxml
mwxml/map/map.py
map
def map(process, paths, threads=None): """ Implements a distributed stategy for processing XML files. This function constructs a set of py:mod:`multiprocessing` threads (spread over multiple cores) and uses an internal queue to aggregate outputs. To use this function, implement a `process()` function that takes two arguments -- a :class:`mwxml.Dump` and the path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ... """ paths = [mwtypes.files.normalize_path(path) for path in paths] def process_path(path): dump = Dump.from_file(mwtypes.files.reader(path)) yield from process(dump, path) yield from para.map(process_path, paths, mappers=threads)
python
def map(process, paths, threads=None): """ Implements a distributed stategy for processing XML files. This function constructs a set of py:mod:`multiprocessing` threads (spread over multiple cores) and uses an internal queue to aggregate outputs. To use this function, implement a `process()` function that takes two arguments -- a :class:`mwxml.Dump` and the path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ... """ paths = [mwtypes.files.normalize_path(path) for path in paths] def process_path(path): dump = Dump.from_file(mwtypes.files.reader(path)) yield from process(dump, path) yield from para.map(process_path, paths, mappers=threads)
[ "def", "map", "(", "process", ",", "paths", ",", "threads", "=", "None", ")", ":", "paths", "=", "[", "mwtypes", ".", "files", ".", "normalize_path", "(", "path", ")", "for", "path", "in", "paths", "]", "def", "process_path", "(", "path", ")", ":", "dump", "=", "Dump", ".", "from_file", "(", "mwtypes", ".", "files", ".", "reader", "(", "path", ")", ")", "yield", "from", "process", "(", "dump", ",", "path", ")", "yield", "from", "para", ".", "map", "(", "process_path", ",", "paths", ",", "mappers", "=", "threads", ")" ]
Implements a distributed stategy for processing XML files. This function constructs a set of py:mod:`multiprocessing` threads (spread over multiple cores) and uses an internal queue to aggregate outputs. To use this function, implement a `process()` function that takes two arguments -- a :class:`mwxml.Dump` and the path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ...
[ "Implements", "a", "distributed", "stategy", "for", "processing", "XML", "files", ".", "This", "function", "constructs", "a", "set", "of", "py", ":", "mod", ":", "multiprocessing", "threads", "(", "spread", "over", "multiple", "cores", ")", "and", "uses", "an", "internal", "queue", "to", "aggregate", "outputs", ".", "To", "use", "this", "function", "implement", "a", "process", "()", "function", "that", "takes", "two", "arguments", "--", "a", ":", "class", ":", "mwxml", ".", "Dump", "and", "the", "path", "the", "dump", "was", "loaded", "from", ".", "Anything", "that", "this", "function", "yield", "s", "will", "be", "yielded", "in", "turn", "from", "the", ":", "func", ":", "mwxml", ".", "map", "function", "." ]
6a8c18be99cd0bcee9c496e607f08bf4dfe5b510
https://github.com/mediawiki-utilities/python-mwxml/blob/6a8c18be99cd0bcee9c496e607f08bf4dfe5b510/mwxml/map/map.py#L11-L49
train
redhat-cip/dci-control-server
dci/trackers/__init__.py
Tracker.dump
def dump(self): """Return the object itself.""" return { 'title': self.title, 'issue_id': self.issue_id, 'reporter': self.reporter, 'assignee': self.assignee, 'status': self.status, 'product': self.product, 'component': self.component, 'created_at': self.created_at, 'updated_at': self.updated_at, 'closed_at': self.closed_at, 'status_code': self.status_code }
python
def dump(self): """Return the object itself.""" return { 'title': self.title, 'issue_id': self.issue_id, 'reporter': self.reporter, 'assignee': self.assignee, 'status': self.status, 'product': self.product, 'component': self.component, 'created_at': self.created_at, 'updated_at': self.updated_at, 'closed_at': self.closed_at, 'status_code': self.status_code }
[ "def", "dump", "(", "self", ")", ":", "return", "{", "'title'", ":", "self", ".", "title", ",", "'issue_id'", ":", "self", ".", "issue_id", ",", "'reporter'", ":", "self", ".", "reporter", ",", "'assignee'", ":", "self", ".", "assignee", ",", "'status'", ":", "self", ".", "status", ",", "'product'", ":", "self", ".", "product", ",", "'component'", ":", "self", ".", "component", ",", "'created_at'", ":", "self", ".", "created_at", ",", "'updated_at'", ":", "self", ".", "updated_at", ",", "'closed_at'", ":", "self", ".", "closed_at", ",", "'status_code'", ":", "self", ".", "status_code", "}" ]
Return the object itself.
[ "Return", "the", "object", "itself", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/trackers/__init__.py#L39-L54
train
smarie/python-valid8
valid8/utils_decoration.py
apply_on_each_func_args_sig
def apply_on_each_func_args_sig(func, cur_args, cur_kwargs, sig, # type: Signature func_to_apply, func_to_apply_params_dict): """ Applies func_to_apply on each argument of func according to what's received in current call (cur_args, cur_kwargs). For each argument of func named 'att' in its signature, the following method is called: `func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)` :param func: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return: """ # match the received arguments with the signature to know who is who bound_values = sig.bind(*cur_args, **cur_kwargs) # add the default values in here to get a full list apply_defaults(bound_values) for att_name, att_value in bound_values.arguments.items(): if att_name in func_to_apply_params_dict.keys(): # value = a normal value, or cur_kwargs as a whole func_to_apply(att_value, func_to_apply_params_dict[att_name], func, att_name)
python
def apply_on_each_func_args_sig(func, cur_args, cur_kwargs, sig, # type: Signature func_to_apply, func_to_apply_params_dict): """ Applies func_to_apply on each argument of func according to what's received in current call (cur_args, cur_kwargs). For each argument of func named 'att' in its signature, the following method is called: `func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)` :param func: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return: """ # match the received arguments with the signature to know who is who bound_values = sig.bind(*cur_args, **cur_kwargs) # add the default values in here to get a full list apply_defaults(bound_values) for att_name, att_value in bound_values.arguments.items(): if att_name in func_to_apply_params_dict.keys(): # value = a normal value, or cur_kwargs as a whole func_to_apply(att_value, func_to_apply_params_dict[att_name], func, att_name)
[ "def", "apply_on_each_func_args_sig", "(", "func", ",", "cur_args", ",", "cur_kwargs", ",", "sig", ",", "# type: Signature", "func_to_apply", ",", "func_to_apply_params_dict", ")", ":", "# match the received arguments with the signature to know who is who", "bound_values", "=", "sig", ".", "bind", "(", "*", "cur_args", ",", "*", "*", "cur_kwargs", ")", "# add the default values in here to get a full list", "apply_defaults", "(", "bound_values", ")", "for", "att_name", ",", "att_value", "in", "bound_values", ".", "arguments", ".", "items", "(", ")", ":", "if", "att_name", "in", "func_to_apply_params_dict", ".", "keys", "(", ")", ":", "# value = a normal value, or cur_kwargs as a whole", "func_to_apply", "(", "att_value", ",", "func_to_apply_params_dict", "[", "att_name", "]", ",", "func", ",", "att_name", ")" ]
Applies func_to_apply on each argument of func according to what's received in current call (cur_args, cur_kwargs). For each argument of func named 'att' in its signature, the following method is called: `func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)` :param func: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return:
[ "Applies", "func_to_apply", "on", "each", "argument", "of", "func", "according", "to", "what", "s", "received", "in", "current", "call", "(", "cur_args", "cur_kwargs", ")", ".", "For", "each", "argument", "of", "func", "named", "att", "in", "its", "signature", "the", "following", "method", "is", "called", ":" ]
5e15d1de11602933c5114eb9f73277ad91d97800
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/utils_decoration.py#L15-L45
train
redhat-cip/dci-control-server
dci/identity.py
Identity.is_product_owner
def is_product_owner(self, team_id): """Ensure the user is a PRODUCT_OWNER.""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.child_teams_ids
python
def is_product_owner(self, team_id): """Ensure the user is a PRODUCT_OWNER.""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.child_teams_ids
[ "def", "is_product_owner", "(", "self", ",", "team_id", ")", ":", "if", "self", ".", "is_super_admin", "(", ")", ":", "return", "True", "team_id", "=", "uuid", ".", "UUID", "(", "str", "(", "team_id", ")", ")", "return", "team_id", "in", "self", ".", "child_teams_ids" ]
Ensure the user is a PRODUCT_OWNER.
[ "Ensure", "the", "user", "is", "a", "PRODUCT_OWNER", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L71-L77
train
redhat-cip/dci-control-server
dci/identity.py
Identity.is_in_team
def is_in_team(self, team_id): """Test if user is in team""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.teams or team_id in self.child_teams_ids
python
def is_in_team(self, team_id): """Test if user is in team""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.teams or team_id in self.child_teams_ids
[ "def", "is_in_team", "(", "self", ",", "team_id", ")", ":", "if", "self", ".", "is_super_admin", "(", ")", ":", "return", "True", "team_id", "=", "uuid", ".", "UUID", "(", "str", "(", "team_id", ")", ")", "return", "team_id", "in", "self", ".", "teams", "or", "team_id", "in", "self", ".", "child_teams_ids" ]
Test if user is in team
[ "Test", "if", "user", "is", "in", "team" ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L96-L102
train
redhat-cip/dci-control-server
dci/identity.py
Identity.is_remoteci
def is_remoteci(self, team_id=None): """Ensure ther resource has the role REMOTECI.""" if team_id is None: return self._is_remoteci team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False return self.teams[team_id]['role'] == 'REMOTECI'
python
def is_remoteci(self, team_id=None): """Ensure ther resource has the role REMOTECI.""" if team_id is None: return self._is_remoteci team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False return self.teams[team_id]['role'] == 'REMOTECI'
[ "def", "is_remoteci", "(", "self", ",", "team_id", "=", "None", ")", ":", "if", "team_id", "is", "None", ":", "return", "self", ".", "_is_remoteci", "team_id", "=", "uuid", ".", "UUID", "(", "str", "(", "team_id", ")", ")", "if", "team_id", "not", "in", "self", ".", "teams_ids", ":", "return", "False", "return", "self", ".", "teams", "[", "team_id", "]", "[", "'role'", "]", "==", "'REMOTECI'" ]
Ensure ther resource has the role REMOTECI.
[ "Ensure", "ther", "resource", "has", "the", "role", "REMOTECI", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L112-L119
train
redhat-cip/dci-control-server
dci/identity.py
Identity.is_feeder
def is_feeder(self, team_id=None): """Ensure ther resource has the role FEEDER.""" if team_id is None: return self._is_feeder team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False return self.teams[team_id]['role'] == 'FEEDER'
python
def is_feeder(self, team_id=None): """Ensure ther resource has the role FEEDER.""" if team_id is None: return self._is_feeder team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False return self.teams[team_id]['role'] == 'FEEDER'
[ "def", "is_feeder", "(", "self", ",", "team_id", "=", "None", ")", ":", "if", "team_id", "is", "None", ":", "return", "self", ".", "_is_feeder", "team_id", "=", "uuid", ".", "UUID", "(", "str", "(", "team_id", ")", ")", "if", "team_id", "not", "in", "self", ".", "teams_ids", ":", "return", "False", "return", "self", ".", "teams", "[", "team_id", "]", "[", "'role'", "]", "==", "'FEEDER'" ]
Ensure ther resource has the role FEEDER.
[ "Ensure", "ther", "resource", "has", "the", "role", "FEEDER", "." ]
b416cf935ec93e4fdd5741f61a21cabecf8454d2
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L121-L128
train