signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def left_hash(msg, func="<STR_LIT>"): | if func == '<STR_LIT>':<EOL><INDENT>return as_unicode(b64e(sha256_digest(msg)[:<NUM_LIT:16>]))<EOL><DEDENT>elif func == '<STR_LIT>':<EOL><INDENT>return as_unicode(b64e(sha384_digest(msg)[:<NUM_LIT>]))<EOL><DEDENT>elif func == '<STR_LIT>':<EOL><INDENT>return as_unicode(b64e(sha512_digest(msg)[:<NUM_LIT:32>]))<EOL><DEDENT> | Calculate left hash as described in
https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
for at_hash and in
for c_hash
:param msg: The message over which the hash should be calculated
:param func: Which hash function that was used for the ID token | f13662:m0 |
def alg2keytype(alg): | if not alg or alg.lower() == "<STR_LIT:none>":<EOL><INDENT>return "<STR_LIT:none>"<EOL><DEDENT>elif alg.startswith("<STR_LIT>") or alg.startswith("<STR_LIT>"):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif alg.startswith("<STR_LIT>") or alg.startswith("<STR_LIT:A>"):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif alg.startswith("<STR_LIT>") or alg.startswith("<STR_LIT>"):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Go from algorithm name to key type.
:param alg: The algorithm name
:return: The key type | f13662:m1 |
def parse_rsa_algorithm(algorithm): | if algorithm == "<STR_LIT>":<EOL><INDENT>return hashes.SHA256(), padding.PKCS1v15()<EOL><DEDENT>elif algorithm == "<STR_LIT>":<EOL><INDENT>return hashes.SHA384(), padding.PKCS1v15()<EOL><DEDENT>elif algorithm == "<STR_LIT>":<EOL><INDENT>return hashes.SHA512(), padding.PKCS1v15()<EOL><DEDENT>elif algorithm == "<STR_LIT>":<EOL><INDENT>return (hashes.SHA256(),<EOL>padding.PSS(<EOL>mgf=padding.MGF1(hashes.SHA256()),<EOL>salt_length=padding.PSS.MAX_LENGTH))<EOL><DEDENT>elif algorithm == "<STR_LIT>":<EOL><INDENT>return (hashes.SHA384(),<EOL>padding.PSS(<EOL>mgf=padding.MGF1(hashes.SHA384()),<EOL>salt_length=padding.PSS.MAX_LENGTH))<EOL><DEDENT>elif algorithm == "<STR_LIT>":<EOL><INDENT>return (hashes.SHA512(),<EOL>padding.PSS(<EOL>mgf=padding.MGF1(hashes.SHA512()),<EOL>salt_length=padding.PSS.MAX_LENGTH))<EOL><DEDENT>else:<EOL><INDENT>raise UnsupportedAlgorithm("<STR_LIT>".format(algorithm))<EOL><DEDENT> | Parses a RSA algorithm and returns tuple (hash, padding).
:param algorithm: string, RSA algorithm as defined at
https://tools.ietf.org/html/rfc7518#section-3.1.
:raises: UnsupportedAlgorithm: if the algorithm is not supported.
:returns: (hash, padding) tuple. | f13662:m2 |
def harmonize_usage(use): | if isinstance(use, str):<EOL><INDENT>return [MAP[use]]<EOL><DEDENT>elif isinstance(use, list):<EOL><INDENT>ul = list(MAP.keys())<EOL>return list(set([MAP[u] for u in use if u in ul]))<EOL><DEDENT> | :param use:
:return: list of usage | f13664:m0 |
def rsa_init(spec): | try:<EOL><INDENT>size = spec['<STR_LIT:size>']<EOL><DEDENT>except KeyError:<EOL><INDENT>size = <NUM_LIT><EOL><DEDENT>kb = KeyBundle(keytype="<STR_LIT>")<EOL>if '<STR_LIT>' in spec:<EOL><INDENT>for use in harmonize_usage(spec["<STR_LIT>"]):<EOL><INDENT>_key = new_rsa_key(use=use, key_size=size)<EOL>kb.append(_key)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_key = new_rsa_key(key_size=size)<EOL>kb.append(_key)<EOL><DEDENT>return kb<EOL> | Initiates a :py:class:`oidcmsg.keybundle.KeyBundle` instance
containing newly minted RSA keys according to a spec.
Example of specification::
{'size':2048, 'use': ['enc', 'sig'] }
Using the spec above 2 RSA keys would be minted, one for
encryption and one for signing.
:param spec:
:return: KeyBundle | f13664:m1 |
def ec_init(spec): | kb = KeyBundle(keytype="<STR_LIT>")<EOL>if '<STR_LIT>' in spec:<EOL><INDENT>for use in spec["<STR_LIT>"]:<EOL><INDENT>eck = new_ec_key(crv=spec['<STR_LIT>'], use=use)<EOL>kb.append(eck)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>eck = new_ec_key(crv=spec['<STR_LIT>'])<EOL>kb.append(eck)<EOL><DEDENT>return kb<EOL> | Initiate a key bundle with an elliptic curve key.
:param spec: Key specifics of the form::
{"type": "EC", "crv": "P-256", "use": ["sig"]}
:return: A KeyBundle instance | f13664:m2 |
def keybundle_from_local_file(filename, typ, usage): | usage = harmonize_usage(usage)<EOL>if typ.lower() == "<STR_LIT>":<EOL><INDENT>kb = KeyBundle(source=filename, fileformat="<STR_LIT>", keyusage=usage)<EOL><DEDENT>elif typ.lower() == '<STR_LIT>':<EOL><INDENT>kb = KeyBundle(source=filename, fileformat="<STR_LIT>", keyusage=usage)<EOL><DEDENT>else:<EOL><INDENT>raise UnknownKeyType("<STR_LIT>")<EOL><DEDENT>return kb<EOL> | Create a KeyBundle based on the content in a local file
:param filename: Name of the file
:param typ: Type of content
:param usage: What the key should be used for
:return: The created KeyBundle | f13664:m3 |
def dump_jwks(kbl, target, private=False): | keys = []<EOL>for kb in kbl:<EOL><INDENT>keys.extend([k.serialize(private) for k in kb.keys() if<EOL>k.kty != '<STR_LIT>' and not k.inactive_since])<EOL><DEDENT>res = {"<STR_LIT>": keys}<EOL>try:<EOL><INDENT>f = open(target, '<STR_LIT:w>')<EOL><DEDENT>except IOError:<EOL><INDENT>(head, tail) = os.path.split(target)<EOL>os.makedirs(head)<EOL>f = open(target, '<STR_LIT:w>')<EOL><DEDENT>_txt = json.dumps(res)<EOL>f.write(_txt)<EOL>f.close()<EOL> | Write a JWK to a file. Will ignore symmetric keys !!
:param kbl: List of KeyBundles
:param target: Name of the file to which everything should be written
:param private: Should also the private parts be exported | f13664:m4 |
def build_key_bundle(key_conf, kid_template="<STR_LIT>"): | kid = <NUM_LIT:0><EOL>tot_kb = KeyBundle()<EOL>for spec in key_conf:<EOL><INDENT>typ = spec["<STR_LIT:type>"].upper()<EOL>if typ == "<STR_LIT>":<EOL><INDENT>if "<STR_LIT:key>" in spec:<EOL><INDENT>error_to_catch = (OSError, IOError,<EOL>DeSerializationNotPossible)<EOL>try:<EOL><INDENT>kb = KeyBundle(source="<STR_LIT>" % spec["<STR_LIT:key>"],<EOL>fileformat="<STR_LIT>",<EOL>keytype=typ, keyusage=spec["<STR_LIT>"])<EOL><DEDENT>except error_to_catch:<EOL><INDENT>kb = rsa_init(spec)<EOL><DEDENT>except Exception:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>kb = rsa_init(spec)<EOL><DEDENT><DEDENT>elif typ == "<STR_LIT>":<EOL><INDENT>kb = ec_init(spec)<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT>if '<STR_LIT>' in spec and len(kb) == <NUM_LIT:1>:<EOL><INDENT>ks = kb.keys()<EOL>ks[<NUM_LIT:0>].kid = spec['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>for k in kb.keys():<EOL><INDENT>if kid_template:<EOL><INDENT>k.kid = kid_template % kid<EOL>kid += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>k.add_kid()<EOL><DEDENT><DEDENT><DEDENT>tot_kb.extend(kb.keys())<EOL><DEDENT>return tot_kb<EOL> | Builds a :py:class:`oidcmsg.key_bundle.KeyBundle` instance based on a key
specification.
An example of such a specification::
keys = [
{"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]},
{"type": "EC", "crv": "P-256", "use": ["sig"], "kid": "ec.1"},
{"type": "EC", "crv": "P-256", "use": ["enc"], "kid": "ec.2"}
]
Keys in this specification are:
type
The type of key. Presently only 'rsa' and 'ec' supported.
key
A name of a file where a key can be found. Only works with PEM encoded
RSA keys
use
What the key should be used for
crv
The elliptic curve that should be used. Only applies to elliptic curve
keys :-)
kid
Key ID, can only be used with one usage type is specified. If there
are more the one usage type specified 'kid' will just be ignored.
:param key_conf: The key configuration
:param kid_template: A template by which to build the key IDs. If no
kid_template is given then the built-in function add_kid() will be used.
:return: A KeyBundle instance | f13664:m5 |
def _cmp(kd1, kd2): | if kd1 == kd2:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>elif kd1< kd2:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>elif kd1 > kd2:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT> | Compare 2 keys
:param kd1: First key
:param kd2: Second key
:return: -1,0,1 depending on whether kd1 is le,eq or gt then kd2 | f13664:m6 |
def sort_func(kd1, kd2): | _l = _cmp(kd1['<STR_LIT:type>'], kd2['<STR_LIT:type>'])<EOL>if _l:<EOL><INDENT>return _l<EOL><DEDENT>if kd1['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>_l = _cmp(kd1['<STR_LIT>'], kd2['<STR_LIT>'])<EOL>if _l:<EOL><INDENT>return _l<EOL><DEDENT><DEDENT>_l = _cmp(kd1['<STR_LIT:type>'], kd2['<STR_LIT:type>'])<EOL>if _l:<EOL><INDENT>return _l<EOL><DEDENT>_l = _cmp(kd1['<STR_LIT>'][<NUM_LIT:0>], kd2['<STR_LIT>'][<NUM_LIT:0>])<EOL>if _l:<EOL><INDENT>return _l<EOL><DEDENT>try:<EOL><INDENT>_kid1 = kd1['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>_kid1 = None<EOL><DEDENT>try:<EOL><INDENT>_kid2 = kd2['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>_kid2 = None<EOL><DEDENT>if _kid1 and _kid2:<EOL><INDENT>return _cmp(_kid1, _kid2)<EOL><DEDENT>elif _kid1:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>elif _kid2:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>return <NUM_LIT:0><EOL> | Compares 2 key descriptions
:param kd1: First key description
:param kd2: Second key description
:return: -1,0,1 depending on whether kd1 le,eq or gt then kd2 | f13664:m7 |
def order_key_defs(key_def): | _int = []<EOL>for kd in key_def:<EOL><INDENT>if len(kd['<STR_LIT>']) > <NUM_LIT:1>:<EOL><INDENT>for _use in kd['<STR_LIT>']:<EOL><INDENT>_kd = kd.copy()<EOL>_kd['<STR_LIT>'] = _use<EOL>_int.append(_kd)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_int.append(kd)<EOL><DEDENT><DEDENT>_int.sort(key=cmp_to_key(sort_func))<EOL>return _int<EOL> | Sort a set of key definitions. A key definition that defines more then
one usage type are splitted into as many definitions as the number of
usage types specified. One key definition per usage type.
:param key_def: A set of key definitions
:return: The set of definitions as a sorted list | f13664:m8 |
def key_diff(key_bundle, key_defs): | keys = key_bundle.get()<EOL>diff = {}<EOL>key_defs = order_key_defs(key_defs)[:]<EOL>used = []<EOL>for key in keys:<EOL><INDENT>match = False<EOL>for kd in key_defs:<EOL><INDENT>if key.use not in kd['<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>if key.kty != kd['<STR_LIT:type>']:<EOL><INDENT>continue<EOL><DEDENT>if key.kty == '<STR_LIT>':<EOL><INDENT>if key.crv != kd['<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>try:<EOL><INDENT>_kid = kd['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if key.kid != _kid:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>match = True<EOL>used.append(kd)<EOL>key_defs.remove(kd)<EOL>break<EOL><DEDENT>if not match:<EOL><INDENT>try:<EOL><INDENT>diff['<STR_LIT>'].append(key)<EOL><DEDENT>except KeyError:<EOL><INDENT>diff['<STR_LIT>'] = [key]<EOL><DEDENT><DEDENT><DEDENT>if key_defs:<EOL><INDENT>_kb = build_key_bundle(key_defs)<EOL>diff['<STR_LIT>'] = _kb.keys()<EOL><DEDENT>return diff<EOL> | Creates a difference dictionary with keys that should added and keys that
should be deleted from a Key Bundle to get it updated to a state that
mirrors What is in the key_defs specification.
:param key_bundle: The original KeyBundle
:param key_defs: A set of key definitions
:return: A dictionary with possible keys 'add' and 'del'. The values
for the keys are lists of :py:class:`cryptojwt.jwk.JWK` instances | f13664:m9 |
def update_key_bundle(key_bundle, diff): | try:<EOL><INDENT>_add = diff['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>key_bundle.extend(_add)<EOL><DEDENT>try:<EOL><INDENT>_del = diff['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>_now = time.time()<EOL>for k in _del:<EOL><INDENT>k.inactive_since = _now<EOL><DEDENT><DEDENT> | Apply a diff specification to a KeyBundle.
The keys that are to be added are added.
The keys that should be deleted are marked as inactive.
:param key_bundle: The original KeyBundle
:param diff: The difference specification
:return: An updated key_bundle | f13664:m10 |
def key_rollover(kb): | key_spec = []<EOL>for key in kb.get():<EOL><INDENT>_spec = {'<STR_LIT:type>': key.kty, '<STR_LIT>':[key.use]}<EOL>if key.kty == '<STR_LIT>':<EOL><INDENT>_spec['<STR_LIT>'] = key.crv<EOL><DEDENT>key_spec.append(_spec)<EOL><DEDENT>diff = {'<STR_LIT>': kb.get()}<EOL>_kb = build_key_bundle(key_spec)<EOL>diff['<STR_LIT>'] = _kb.keys()<EOL>update_key_bundle(kb, diff)<EOL>return kb<EOL> | A nifty function that lets you do a key rollover that encompasses creating
a completely new set of keys. One new per every old one. With the same
specifications as the old one.
All the old ones are marked as inactive.
:param kb:
:return: | f13664:m11 |
def __init__(self, keys=None, source="<STR_LIT>", cache_time=<NUM_LIT>, verify_ssl=True,<EOL>fileformat="<STR_LIT>", keytype="<STR_LIT>", keyusage=None, kid='<STR_LIT>',<EOL>httpc=None): | self._keys = []<EOL>self.remote = False<EOL>self.cache_time = cache_time<EOL>self.time_out = <NUM_LIT:0><EOL>self.etag = "<STR_LIT>"<EOL>self.source = None<EOL>self.fileformat = fileformat.lower()<EOL>self.keytype = keytype<EOL>self.keyusage = keyusage<EOL>self.imp_jwks = None<EOL>self.last_updated = <NUM_LIT:0><EOL>if httpc:<EOL><INDENT>self.httpc = httpc<EOL>self.verify_ssl = None<EOL><DEDENT>else:<EOL><INDENT>self.httpc = requests.request<EOL>self.verify_ssl = verify_ssl<EOL><DEDENT>if keys:<EOL><INDENT>self.source = None<EOL>if isinstance(keys, dict):<EOL><INDENT>if '<STR_LIT>' in keys:<EOL><INDENT>self.do_keys(keys['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>self.do_keys([keys])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.do_keys(keys)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if source.startswith("<STR_LIT>"):<EOL><INDENT>self.source = source[<NUM_LIT:7>:]<EOL><DEDENT>elif source.startswith("<STR_LIT>") or source.startswith("<STR_LIT>"):<EOL><INDENT>self.source = source<EOL>self.remote = True<EOL><DEDENT>elif source == "<STR_LIT>":<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>if fileformat.lower() in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if os.path.isfile(source):<EOL><INDENT>self.source = source<EOL><DEDENT>else:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT><DEDENT>if not self.remote: <EOL><INDENT>if self.fileformat in ['<STR_LIT>', "<STR_LIT>"]:<EOL><INDENT>self.do_local_jwk(self.source)<EOL><DEDENT>elif self.fileformat == "<STR_LIT>": <EOL><INDENT>self.do_local_der(self.source, self.keytype, self.keyusage,<EOL>kid)<EOL><DEDENT><DEDENT><DEDENT> | Contains a set of keys that have a common origin.
The sources can be serveral:
- A dictionary provided at the initialization, see keys below.
- A list of dictionaries provided at initialization
- A file containing one of: JWKS, DER encoded key
- A URL pointing to a webpages from which an JWKS can be downloaded
:param keys: A dictionary or a list of dictionaries
with the keys ["kty", "key", "alg", "use", "kid"]
:param source: Where the key set can be fetch from
:param verify_ssl: Verify the SSL cert used by the server
:param fileformat: For a local file either "jwks" or "der"
:param keytype: Iff local file and 'der' format what kind of key it is.
presently only 'rsa' is supported.
:param keyusage: What the key loaded from file should be used for.
Only applicable for DER files
:param httpc: A HTTP client function | f13664:c0:m0 |
def do_keys(self, keys): | for inst in keys:<EOL><INDENT>typ = inst["<STR_LIT>"]<EOL>try:<EOL><INDENT>_usage = harmonize_usage(inst['<STR_LIT>'])<EOL><DEDENT>except KeyError:<EOL><INDENT>_usage = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>del inst['<STR_LIT>']<EOL><DEDENT>flag = <NUM_LIT:0><EOL>for _use in _usage:<EOL><INDENT>for _typ in [typ, typ.lower(), typ.upper()]:<EOL><INDENT>try:<EOL><INDENT>_key = K2C[_typ](use=_use, **inst)<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT>except JWKException as err:<EOL><INDENT>logger.warning('<STR_LIT>'.format(err))<EOL><DEDENT>else:<EOL><INDENT>if _key not in self._keys:<EOL><INDENT>self._keys.append(_key)<EOL><DEDENT>flag = <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT><DEDENT>if not flag:<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>'.format(typ))<EOL><DEDENT><DEDENT> | Go from JWK description to binary keys
:param keys:
:return: | f13664:c0:m1 |
def do_local_jwk(self, filename): | _info = json.loads(open(filename).read())<EOL>if '<STR_LIT>' in _info:<EOL><INDENT>self.do_keys(_info["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>self.do_keys([_info])<EOL><DEDENT>self.last_updated = time.time()<EOL> | Load a JWKS from a local file
:param filename: | f13664:c0:m2 |
def do_local_der(self, filename, keytype, keyusage=None, kid='<STR_LIT>'): | _bkey = import_private_rsa_key_from_file(filename)<EOL>if keytype.lower() != '<STR_LIT>':<EOL><INDENT>raise NotImplemented('<STR_LIT>')<EOL><DEDENT>if not keyusage:<EOL><INDENT>keyusage = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>keyusage = harmonize_usage(keyusage)<EOL><DEDENT>for use in keyusage:<EOL><INDENT>_key = RSAKey().load_key(_bkey)<EOL>_key.use = use<EOL>if kid:<EOL><INDENT>_key.kid = kid<EOL><DEDENT>self._keys.append(_key)<EOL><DEDENT>self.last_updated = time.time()<EOL> | Load a DER encoded file amd create a key from it.
:param filename:
:param keytype: Presently only 'rsa' supported
:param keyusage: encryption ('enc') or signing ('sig') or both | f13664:c0:m3 |
def do_remote(self): | if self.verify_ssl:<EOL><INDENT>args = {"<STR_LIT>": self.verify_ssl}<EOL><DEDENT>else:<EOL><INDENT>args = {}<EOL><DEDENT>try:<EOL><INDENT>logging.debug('<STR_LIT>'.format(self.source))<EOL>r = self.httpc('<STR_LIT:GET>', self.source, **args)<EOL><DEDENT>except Exception as err:<EOL><INDENT>logger.error(err)<EOL>raise UpdateFailed(<EOL>REMOTE_FAILED.format(self.source, str(err)))<EOL><DEDENT>if r.status_code == <NUM_LIT:200>: <EOL><INDENT>self.time_out = time.time() + self.cache_time<EOL>self.imp_jwks = self._parse_remote_response(r)<EOL>if not isinstance(self.imp_jwks,<EOL>dict) or "<STR_LIT>" not in self.imp_jwks:<EOL><INDENT>raise UpdateFailed(MALFORMED.format(self.source))<EOL><DEDENT>logger.debug("<STR_LIT>" % (r.text, self.source))<EOL>try:<EOL><INDENT>self.do_keys(self.imp_jwks["<STR_LIT>"])<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.error("<STR_LIT>")<EOL>raise UpdateFailed(MALFORMED.format(self.source))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise UpdateFailed(<EOL>REMOTE_FAILED.format(self.source, r.status_code))<EOL><DEDENT>self.last_updated = time.time()<EOL>return True<EOL> | Load a JWKS from a webpage
:return: True or False if load was successful | f13664:c0:m4 |
def _parse_remote_response(self, response): | <EOL>try:<EOL><INDENT>if response.headers["<STR_LIT:Content-Type>"] != '<STR_LIT:application/json>':<EOL><INDENT>logger.warning('<STR_LIT>'.format(<EOL>response.headers["<STR_LIT:Content-Type>"]))<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>logger.debug("<STR_LIT>" % (response.text, self.source))<EOL>try:<EOL><INDENT>return json.loads(response.text)<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT> | Parse JWKS from the HTTP response.
Should be overriden by subclasses for adding support of e.g. signed
JWKS.
:param response: HTTP response from the 'jwks_uri' endpoint
:return: response parsed as JSON | f13664:c0:m5 |
def update(self): | res = True <EOL>if self.source:<EOL><INDENT>_keys = self._keys <EOL>self._keys = []<EOL>try:<EOL><INDENT>if self.remote is False:<EOL><INDENT>if self.fileformat in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>self.do_local_jwk(self.source)<EOL><DEDENT>elif self.fileformat == "<STR_LIT>":<EOL><INDENT>self.do_local_der(self.source, self.keytype,<EOL>self.keyusage)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>res = self.do_remote()<EOL><DEDENT><DEDENT>except Exception as err:<EOL><INDENT>logger.error('<STR_LIT>'.format(err))<EOL>self._keys = _keys <EOL>return False<EOL><DEDENT>now = time.time()<EOL>for _key in _keys:<EOL><INDENT>if _key not in self._keys:<EOL><INDENT>if not _key.inactive_since: <EOL><INDENT>_key.inactive_since = now<EOL><DEDENT>self._keys.append(_key)<EOL><DEDENT><DEDENT><DEDENT>return res<EOL> | Reload the keys if necessary
This is a forced update, will happen even if cache time has not elapsed.
Replaced keys will be marked as inactive and not removed. | f13664:c0:m7 |
def get(self, typ="<STR_LIT>", only_active=True): | self._uptodate()<EOL>_typs = [typ.lower(), typ.upper()]<EOL>if typ:<EOL><INDENT>_keys = [k for k in self._keys if k.kty in _typs]<EOL><DEDENT>else:<EOL><INDENT>_keys = self._keys<EOL><DEDENT>if only_active:<EOL><INDENT>return [k for k in _keys if not k.inactive_since]<EOL><DEDENT>else:<EOL><INDENT>return _keys<EOL><DEDENT> | Return a list of keys. Either all keys or only keys of a specific type
:param typ: Type of key (rsa, ec, oct, ..)
:return: If typ is undefined all the keys as a dictionary
otherwise the appropriate keys in a list | f13664:c0:m8 |
def keys(self): | self._uptodate()<EOL>return self._keys<EOL> | Return all keys after having updated them
:return: List of all keys | f13664:c0:m9 |
def remove_keys_by_type(self, typ): | _typs = [typ.lower(), typ.upper()]<EOL>self._keys = [k for k in self._keys if not k.kty in _typs]<EOL> | Remove keys that are of a specific type.
:param typ: Type of key (rsa, ec, oct, ..) | f13664:c0:m11 |
def jwks(self, private=False): | self._uptodate()<EOL>keys = list()<EOL>for k in self._keys:<EOL><INDENT>if private:<EOL><INDENT>key = k.serialize(private)<EOL><DEDENT>else:<EOL><INDENT>key = k.serialize()<EOL>for k, v in key.items():<EOL><INDENT>key[k] = as_unicode(v)<EOL><DEDENT><DEDENT>keys.append(key)<EOL><DEDENT>return json.dumps({"<STR_LIT>": keys})<EOL> | Create a JWKS as a JSON document
:param private: Whether private key information should be included.
:return: A JWKS JSON representation of the keys in this bundle | f13664:c0:m13 |
def append(self, key): | self._keys.append(key)<EOL> | Add a key to list of keys in this bundle
:param key: Key to be added | f13664:c0:m14 |
def remove(self, key): | try:<EOL><INDENT>self._keys.remove(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT> | Remove a specific key from this bundle
:param key: The key that should be removed | f13664:c0:m16 |
def __len__(self): | return len(self._keys)<EOL> | The number of keys
:return: The number of keys | f13664:c0:m17 |
def get_key_with_kid(self, kid): | for key in self._keys:<EOL><INDENT>if key.kid == kid:<EOL><INDENT>return key<EOL><DEDENT><DEDENT>self.update()<EOL>for key in self._keys:<EOL><INDENT>if key.kid == kid:<EOL><INDENT>return key<EOL><DEDENT><DEDENT>return None<EOL> | Return the key that has a specific key ID (kid)
:param kid: The Key ID
:return: The key or None | f13664:c0:m18 |
def kids(self): | self._uptodate()<EOL>return [key.kid for key in self._keys if key.kid != "<STR_LIT>"]<EOL> | Return a list of key IDs. Note that this list may be shorter then
the list of keys. The reason might be that there are some keys with
no key ID.
:return: A list of all the key IDs that exists in this bundle | f13664:c0:m19 |
def mark_as_inactive(self, kid): | k = self.get_key_with_kid(kid)<EOL>k.inactive_since = time.time()<EOL> | Mark a specific key as inactive based on the keys KeyID
:param kid: The Key Identifier | f13664:c0:m20 |
def remove_outdated(self, after, when=<NUM_LIT:0>): | if when:<EOL><INDENT>now = when<EOL><DEDENT>else:<EOL><INDENT>now = time.time()<EOL><DEDENT>if not isinstance(after, float):<EOL><INDENT>try:<EOL><INDENT>after = float(after)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>_kl = []<EOL>for k in self._keys:<EOL><INDENT>if k.inactive_since and k.inactive_since + after < now:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>_kl.append(k)<EOL><DEDENT><DEDENT>self._keys = _kl<EOL> | Remove keys that should not be available any more.
Outdated means that the key was marked as inactive at a time
that was longer ago then what is given in 'after'.
:param after: The length of time the key will remain in the KeyBundle
before it should be removed.
:param when: To make it easier to test | f13664:c0:m21 |
def copy(self): | kb = KeyBundle()<EOL>kb._keys = self._keys[:]<EOL>kb.cache_time = self.cache_time<EOL>kb.verify_ssl = self.verify_ssl<EOL>if self.source:<EOL><INDENT>kb.source = self.source<EOL>kb.fileformat = self.fileformat<EOL>kb.keytype = self.keytype<EOL>kb.keyusage = self.keyusage<EOL>kb.remote = self.remote<EOL><DEDENT>return kb<EOL> | Make deep copy of this KeyBundle
:return: The copy | f13664:c0:m23 |
def get_all_published_ships_basic(db_connection): | if not hasattr(get_all_published_ships_basic, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_all_published_ships_basic._results = results<EOL><DEDENT>return get_all_published_ships_basic._results<EOL> | Gets a list of all published ships and their basic information.
:return: Each result has a tuple of (typeID, typeName, groupID, groupName, categoryID, and categoryName).
:rtype: list | f13676:m0 |
def get_dogma_attribute_for_type(db_connection, type_id, dogma_attribute): | sql = '<STR_LIT>'.format(type_id, dogma_attribute)<EOL>results = execute_sql(sql, db_connection, fetch='<STR_LIT>')<EOL>if results is not None:<EOL><INDENT>results = results[<NUM_LIT:0>] <EOL><DEDENT>return results<EOL> | :param type_id:
:param dogma_attribute:
:return:
:rtype: | f13676:m1 |
def get_ships_that_have_variations(db_connection): | if not hasattr(get_ships_that_have_variations, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_ships_that_have_variations._results = results<EOL><DEDENT>return get_ships_that_have_variations._results<EOL> | Gets a list of all published ship type IDs that have at least 3 variations.
:return:
:rtype: list | f13676:m2 |
def get_type_variations(db_connection, type_id): | sql = '<STR_LIT>'.format(type_id)<EOL>results = execute_sql(sql, db_connection)<EOL>return results<EOL> | :param type_id:
:param dogma_attribute:
:return:
:rtype: | f13676:m3 |
def execute_sql(sql, db_connection, fetch='<STR_LIT:all>'): | cursor = db_connection.cursor()<EOL>cursor.execute(sql)<EOL>if fetch == '<STR_LIT:all>':<EOL><INDENT>results = [x for x in cursor.fetchall()]<EOL><DEDENT>elif fetch == '<STR_LIT>':<EOL><INDENT>results = cursor.fetchone()<EOL><DEDENT>else:<EOL><INDENT>results = None<EOL><DEDENT>cursor.close()<EOL>return results<EOL> | :param sql:
:param db_connection:
:param fetch: A string of either 'all' or 'one'.
:return: | f13678:m0 |
def get_stored_procs(db_connection): | sql = "<STR_LIT>"<EOL>procs = execute_sql(sql, db_connection)<EOL>return [x[<NUM_LIT:1>] for x in procs]<EOL> | :param db_connection:
:return: | f13678:m1 |
def drop_proc(proc_name, db_connection): | sql = "<STR_LIT>".format(proc_name)<EOL>execute_sql(sql, db_connection)<EOL> | :param proc_name:
:param db_connection:
:return: | f13678:m2 |
def update_sql_stored_procs(db_connection): | procs_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '<STR_LIT>')<EOL>existing_procs = get_stored_procs(db_connection)<EOL>for proc_file_name in os.listdir(procs_dir_path):<EOL><INDENT>_log.info('<STR_LIT>'.format(proc_file_name))<EOL>proc_file_path = os.path.join(procs_dir_path, proc_file_name)<EOL>proc_name = proc_file_name.split('<STR_LIT:.>')[<NUM_LIT:1>]<EOL>if proc_name in existing_procs:<EOL><INDENT>drop_proc(proc_name, db_connection)<EOL><DEDENT>with open(proc_file_path, '<STR_LIT:r>') as sql_file:<EOL><INDENT>sql = "<STR_LIT:U+0020>".join(sql_file.readlines())<EOL>execute_sql(sql, db_connection, fetch=None)<EOL><DEDENT><DEDENT> | :param db_connection:
:return: | f13678:m3 |
def load_tables_from_files(db_connection): | _log.info('<STR_LIT>')<EOL>sde_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '<STR_LIT>')<EOL>for sde_file_name in os.listdir(sde_dir_path):<EOL><INDENT>_log.info('<STR_LIT>'.format(sde_file_name))<EOL>sde_file_path = os.path.join(sde_dir_path, sde_file_name)<EOL>with open(sde_file_path, '<STR_LIT:r>') as sde_file:<EOL><INDENT>sql = sde_file.read()<EOL>execute_sql(sql, db_connection)<EOL><DEDENT><DEDENT>_log.info('<STR_LIT>')<EOL> | Looks in the current working directory for all required tables. | f13678:m4 |
def get_connection(connection_details=None): | if connection_details is None:<EOL><INDENT>connection_details = get_default_connection_details()<EOL><DEDENT>return MySQLdb.connect(<EOL>connection_details['<STR_LIT:host>'],<EOL>connection_details['<STR_LIT:user>'],<EOL>connection_details['<STR_LIT:password>'],<EOL>connection_details['<STR_LIT>']<EOL>)<EOL> | Creates a connection to the MySQL DB. | f13678:m5 |
def get_default_connection_details(): | return {<EOL>'<STR_LIT:host>': os.environ.get('<STR_LIT>', '<STR_LIT:127.0.0.1>'),<EOL>'<STR_LIT:user>': os.environ.get('<STR_LIT>', '<STR_LIT>'),<EOL>'<STR_LIT:password>': os.environ.get('<STR_LIT>', '<STR_LIT>'),<EOL>'<STR_LIT>': os.environ.get('<STR_LIT>', '<STR_LIT>'),<EOL>}<EOL> | Gets the connection details based on environment vars or Thanatos default settings.
:return: Returns a dictionary of connection details.
:rtype: dict | f13678:m6 |
def get_all_regions(db_connection): | if not hasattr(get_all_regions, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_all_regions._results = results<EOL><DEDENT>return get_all_regions._results<EOL> | Gets a list of all regions.
:return: A list of all regions. Results have regionID and regionName.
:rtype: list | f13679:m0 |
def get_all_not_wh_regions(db_connection): | if not hasattr(get_all_not_wh_regions, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_all_not_wh_regions._results = results<EOL><DEDENT>return get_all_not_wh_regions._results<EOL> | Gets a list of all regions that are not WH regions.
:return: A list of all regions not including wormhole regions. Results have regionID and regionName.
:rtype: list | f13679:m1 |
def get_all_regions_connected_to_region(db_connection, region_id): | sql = '<STR_LIT>'.format(region_id)<EOL>results = execute_sql(sql, db_connection)<EOL>return results<EOL> | Gets a list of all regions connected to the region ID passed in.
:param region_id: Region ID to find all regions connected to.
:type region_id: int
:return: A list of all regions connected to the specified region ID. Results have regionID and regionName.
:rtype: list | f13679:m2 |
@abstractmethod<EOL><INDENT>def ask(self):<DEDENT> | pass<EOL> | ask is called whenever attempting to get a question.
:return: A dictionary of answer, question, and other details.
:rtype: dict | f13682:c0:m1 |
def format_question(self, correct_answer, possible_wrong_answers, question, add_images_to_question=False): | <EOL>wrong_answers = random.sample(possible_wrong_answers, <NUM_LIT:2>)<EOL>choices = [x for x in wrong_answers]<EOL>choices.append(correct_answer)<EOL>random.shuffle(choices)<EOL>question = {<EOL>'<STR_LIT>': correct_answer[<NUM_LIT:0>],<EOL>'<STR_LIT>': question,<EOL>'<STR_LIT>': self.convert_choices_to_dict(choices)<EOL>}<EOL>if add_images_to_question is True:<EOL><INDENT>question['<STR_LIT>'] = get_type_links(correct_answer[<NUM_LIT:0>])<EOL><DEDENT>return question<EOL> | Takes a set of values and converts it to the standard format
expected as a return from self.ask().
:param correct_answer: A tuple of the answer key and text to be shown.
:type correct_answer: tuple
:param possible_wrong_answers: A list of tuples, each tuple being being
(id, display_name).
:type possible_wrong_answers: list
:param question: A string to be set as the question that is asked.
:type question: string
:return: A dict that matches what is expected as the return value for self.ask()
:rtype: dict | f13682:c0:m2 |
@staticmethod<EOL><INDENT>def convert_choices_to_dict(choices):<DEDENT> | formatted_choices = []<EOL>for x in choices:<EOL><INDENT>formatted_choices.append({<EOL>'<STR_LIT:value>': x[<NUM_LIT:0>],<EOL>'<STR_LIT:text>': x[<NUM_LIT:1>],<EOL>})<EOL><DEDENT>return formatted_choices<EOL> | Takes a list of tuples and converts it to a list of dictionaries of
where each dictionary has a value and text key. This is the expected format
of question choices to be returned by self.ask()
:param convert_choices_to_dict:
:type convert_choices_to_dict: list
:return:
:rtype: | f13682:c0:m3 |
def remove_regions_with_no_gates(regions): | list_of_gateless_regions = [<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>]<EOL>for gateless_region in list_of_gateless_regions:<EOL><INDENT>if gateless_region in regions:<EOL><INDENT>regions.remove(gateless_region)<EOL><DEDENT><DEDENT>return regions<EOL> | Removes all Jove regions from a list of regions.
:param regions: A list of tuples (regionID, regionName)
:type regions: list
:return: A list of regions minus those in jove space
:rtype: list | f13686:m0 |
def get_all_question_details(): | categories = {}<EOL>subclasses = get_question_subclasses()<EOL>for subclass in subclasses:<EOL><INDENT>if subclass.category is not None and subclass.sub_category is not None:<EOL><INDENT>name = subclass.__name__.lower()<EOL>category = subclass.category['<STR_LIT:name>'].lower()<EOL>sub_category = subclass.sub_category['<STR_LIT:name>'].lower()<EOL>if category not in categories:<EOL><INDENT>categories[category] = subclass.category<EOL>categories[category]['<STR_LIT>'] = {}<EOL><DEDENT>if sub_category not in categories[category]['<STR_LIT>']:<EOL><INDENT>categories[category]['<STR_LIT>'][sub_category] = subclass.sub_category<EOL>categories[category]['<STR_LIT>'][sub_category]['<STR_LIT>'] = {}<EOL><DEDENT>categories[category]['<STR_LIT>'][sub_category]['<STR_LIT>'][name] = {<EOL>'<STR_LIT:name>': subclass.name,<EOL>'<STR_LIT:description>': subclass.description,<EOL>'<STR_LIT>': subclass.random_weight,<EOL>'<STR_LIT>': subclass.question,<EOL>}<EOL><DEDENT><DEDENT>return categories<EOL> | :return: A dictionary of sets representing the categories and their sub categories.
:rtype: dict | f13687:m0 |
def get_rate_from_db(currency: str) -> Decimal: | from .models import ConversionRate<EOL>try:<EOL><INDENT>rate = ConversionRate.objects.get_rate(currency)<EOL><DEDENT>except ConversionRate.DoesNotExist: <EOL><INDENT>raise ValueError('<STR_LIT>' % (currency, ))<EOL><DEDENT>return rate.rate<EOL> | Fetch currency conversion rate from the database | f13700:m0 |
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal: | reverse_rate = False<EOL>if to_currency == BASE_CURRENCY:<EOL><INDENT>rate_currency = from_currency<EOL>reverse_rate = True<EOL><DEDENT>else:<EOL><INDENT>rate_currency = to_currency<EOL><DEDENT>rate = get_rate_from_db(rate_currency)<EOL>if reverse_rate:<EOL><INDENT>conversion_rate = Decimal(<NUM_LIT:1>) / rate<EOL><DEDENT>else:<EOL><INDENT>conversion_rate = rate<EOL><DEDENT>return conversion_rate<EOL> | Get conversion rate to use in exchange | f13700:m1 |
def exchange_currency(<EOL>base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T: | if base.currency == to_currency:<EOL><INDENT>return base<EOL><DEDENT>if base.currency != BASE_CURRENCY and to_currency != BASE_CURRENCY:<EOL><INDENT>base = exchange_currency(base, BASE_CURRENCY)<EOL><DEDENT>if conversion_rate is None:<EOL><INDENT>conversion_rate = get_conversion_rate(base.currency, to_currency)<EOL><DEDENT>if isinstance(base, Money):<EOL><INDENT>return Money(base.amount * conversion_rate, currency=to_currency)<EOL><DEDENT>if isinstance(base, MoneyRange):<EOL><INDENT>return MoneyRange(<EOL>exchange_currency(<EOL>base.start, to_currency, conversion_rate=conversion_rate),<EOL>exchange_currency(<EOL>base.stop, to_currency, conversion_rate=conversion_rate))<EOL><DEDENT>if isinstance(base, TaxedMoney):<EOL><INDENT>return TaxedMoney(<EOL>exchange_currency(<EOL>base.net, to_currency, conversion_rate=conversion_rate),<EOL>exchange_currency(<EOL>base.gross, to_currency, conversion_rate=conversion_rate))<EOL><DEDENT>if isinstance(base, TaxedMoneyRange):<EOL><INDENT>return TaxedMoneyRange(<EOL>exchange_currency(<EOL>base.start, to_currency, conversion_rate=conversion_rate),<EOL>exchange_currency(<EOL>base.stop, to_currency, conversion_rate=conversion_rate))<EOL><DEDENT>raise TypeError('<STR_LIT>' % (base,))<EOL> | Exchanges Money, TaxedMoney and their ranges to the specified currency.
get_rate parameter is a callable taking single argument (target currency)
that returns proper conversion rate | f13700:m2 |
def save(self, *args, **kwargs): | self.full_clean()<EOL>super(ConversionRate, self).save(*args, **kwargs)<EOL> | Save the model instance but only on successful validation. | f13703:c1:m0 |
def get_keywords(): | <EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full}<EOL>return keywords<EOL> | Get the keywords needed to look up the version information. | f13705:m0 |
def get_config(): | <EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT:v>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL> | Create, populate and return the VersioneerConfig() object. | f13705:m1 |
def register_vcs_handler(vcs, method): | def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL> | Decorator to mark a method as the handler for a particular VCS. | f13705:m2 |
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): | assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL><DEDENT>return None<EOL><DEDENT>return stdout<EOL> | Call the given command(s). | f13705:m3 |
def versions_from_parentdir(parentdir_prefix, root, verbose): | dirname = os.path.basename(root)<EOL>if not dirname.startswith(parentdir_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % (root, dirname, parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None}<EOL> | Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes
both the project name and a version string. | f13705:m4 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs): | <EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL> | Extract version information from the given file. | f13705:m5 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose): | if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs-tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None<EOL>}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>"}<EOL> | Get version information from git keywords. | f13705:m6 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): | if not os.path.exists(os.path.join(root, "<STR_LIT>")):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>describe_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>] <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out) <EOL><DEDENT>return pieces<EOL> | Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree. | f13705:m7 |
def plus_or_dot(pieces): | if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL> | Return a + if we don't already have one, else return a . | f13705:m8 |
def render_pep440(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL> | Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] | f13705:m9 |
def render_pep440_pre(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL> | TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE | f13705:m10 |
def render_pep440_post(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL> | TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0] | f13705:m11 |
def render_pep440_old(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL> | TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0] | f13705:m12 |
def render_git_describe(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL> | TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | f13705:m13 |
def render_git_describe_long(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL> | TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | f13705:m14 |
def render(pieces, style): | if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"]}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None}<EOL> | Render the given version pieces into the requested style. | f13705:m15 |
def get_versions(): | <EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>"}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>"}<EOL> | Get version information or return default if unable to do so. | f13705:m16 |
def spinner(beep=False, disable=False, force=False): | return Spinner(beep, disable, force)<EOL> | This function creates a context manager that is used to display a
spinner on stdout as long as the context has not exited.
The spinner is created only if stdout is not redirected, or if the spinner
is forced using the `force` parameter.
Parameters
----------
beep : bool
Beep when spinner finishes.
disable : bool
Hide spinner.
force : bool
Force creation of spinner even when stdout is redirected.
Example
-------
with spinner():
do_something()
do_something_else() | f13706:m0 |
def option2tuple(opt): | if isinstance(opt[<NUM_LIT:0>], int):<EOL><INDENT>tup = opt[<NUM_LIT:1>], opt[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>tup = opt[<NUM_LIT:0>], opt[<NUM_LIT:1>:]<EOL><DEDENT>return tup<EOL> | Return a tuple of option, taking possible presence of level into account | f13708:m0 |
def opt_func(options, check_mandatory=True): | <EOL>def validate_arguments(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrap(*args, **kwargs):<EOL><INDENT>if args:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'.format(func, len(args)))<EOL><DEDENT>keys = set(kwargs.keys())<EOL>missing = options.mandatory_keys - keys<EOL>if missing and check_mandatory:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(func, '<STR_LIT:U+002CU+0020>'.join(missing)))<EOL><DEDENT>arguments = options._default_dict()<EOL>unknown = keys - set(arguments.keys())<EOL>if unknown:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(func, '<STR_LIT:U+002CU+0020>'.join(unknown)))<EOL><DEDENT>arguments.update(**kwargs)<EOL>return func(**arguments)<EOL><DEDENT>return wrap<EOL><DEDENT>return validate_arguments<EOL> | Restore argument checks for functions that takes options dicts as arguments
Functions that take the option dictionary produced by :meth:`Options.parse`
as `kwargs` loose the argument checking usually performed by the python
interpretor. They also loose the ability to take default values for
their keyword arguments. Such function is basically unusable without the
full dictionary produced by the option parser.
This is a decorator that restores argument checking and default values
assignment on the basis of an :class:`Options` instance.
options = Options([
(0, "-f", "input", str, 1, None, MULTI, "Input file"),
(0, "-o", "output", str, 1, None, MA, "Output file"),
(0, "-p", "topology", str, 1, None, 0, "Optional topology"),
])
@opt_func(options)
def process_things(**arguments):
# Do something
return
# The function can be called with the arguments
# from the argument parser
arguments = options.parse()
process_things(**arguments)
# It can be called with only part of the arguments,
# the other arguments will be set to their default as defined by
# the Options instance
process_things(output='output.gro')
# If the function is called with an unknown argument, the decorator
# raises a TypeError
process_things(unknown=None)
# Likewise, if the function is called without the mandatory arguments,
# the decorator raises a TypeError
process_things(topology='topology.top')
# The check for mandatory arguments can be deactivated
@opt_func(options, check_mandatory=False)
def process_things(**arguments):
# Do things
return
Note that the decorator cannot be used on functions that accept Other
arguments than the one defined in the :class:`Options` instance. Also, the
arguments have to be given as keyword arguments. Positional arguments
will cause the decorator to raise a `TypeError`. | f13708:m1 |
def __init__(self, options, args=None): | self.options = options<EOL>self._optiondict = dict([option2tuple(i) for i in options if not type(i) == str])<EOL>for opt in self._optiondict.values():<EOL><INDENT>setattr(self,opt[<NUM_LIT:0>],([] if not opt[<NUM_LIT:3>] else [opt[<NUM_LIT:3>]]) if (opt[<NUM_LIT:4>] & MULTI) else opt[<NUM_LIT:3>])<EOL><DEDENT>if args:<EOL><INDENT>self.parse(args)<EOL><DEDENT> | Set up options object. | f13708:c4:m0 |
def _default_dict(self): | options = {}<EOL>for attr, _, _, default, multi, _ in self._optiondict.values():<EOL><INDENT>if multi and default is None:<EOL><INDENT>options[attr] = []<EOL><DEDENT>else:<EOL><INDENT>options[attr] = default<EOL><DEDENT><DEDENT>return options<EOL> | Return a dictionary with the default for each option. | f13708:c4:m1 |
def __str__(self): | return self.help(args=self.args)<EOL> | Make a string from the option list.
This method defines how the object looks like when converted to string. | f13708:c4:m4 |
def help(self, args=None, userlevel=<NUM_LIT:9>): | out = [main.__file__+"<STR_LIT:\n>"]<EOL>if args is not None:<EOL><INDENT>parsed = self.parse(args, ignore_help=True)<EOL><DEDENT>else:<EOL><INDENT>parsed = self._default_dict()<EOL><DEDENT>for thing in self.options:<EOL><INDENT>if type(thing) == str:<EOL><INDENT>out.append("<STR_LIT:U+0020>"+thing)<EOL><DEDENT>elif thing[<NUM_LIT:0>] <= userlevel:<EOL><INDENT>out.append("<STR_LIT>" % (thing[<NUM_LIT:1>], thing[-<NUM_LIT:1>], str(parsed[thing[<NUM_LIT:2>]])))<EOL><DEDENT><DEDENT>return "<STR_LIT:\n>".join(out)+"<STR_LIT:\n>"<EOL> | Make a string from the option list | f13708:c4:m5 |
def parse(self, args, ignore_help=False): | options = self._default_dict()<EOL>seen = set()<EOL>args = copy.copy(args)<EOL>while args:<EOL><INDENT>opt = args.pop(<NUM_LIT:0>)<EOL>seen.add(opt)<EOL>if opt in ("<STR_LIT>","<STR_LIT>"):<EOL><INDENT>if ignore_help:<EOL><INDENT>continue<EOL><DEDENT>raise SimoptHelp<EOL><DEDENT>if not opt in self._optiondict:<EOL><INDENT>raise Usage("<STR_LIT>"%opt)<EOL><DEDENT>attr, typ, num, default, flags, description = self._optiondict[opt]<EOL>if num > len(args):<EOL><INDENT>raise Usage("<STR_LIT>"%(opt,num))<EOL><DEDENT>if num:<EOL><INDENT>a = args.pop(<NUM_LIT:0>)<EOL>try:<EOL><INDENT>val = [typ(a) for i in range(num)]<EOL><DEDENT>except ValueError:<EOL><INDENT>raise Usage("<STR_LIT>"%(opt,repr(a)))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>val = [True]<EOL><DEDENT>if typ == bool:<EOL><INDENT>options[attr] = True<EOL><DEDENT>elif flags & MULTI:<EOL><INDENT>options[attr] = options.get(attr, list())<EOL>options[attr].append(val[<NUM_LIT:0>] if num == <NUM_LIT:1> else tuple(val))<EOL><DEDENT>else:<EOL><INDENT>options[attr] = val[<NUM_LIT:0>] if num == <NUM_LIT:1> else tuple(val)<EOL><DEDENT><DEDENT>missing = self.mandatory_arguments - seen<EOL>if not ignore_help and missing:<EOL><INDENT>raise MissingMandatoryError(missing)<EOL><DEDENT>return options<EOL> | Parse the (command-line) arguments. | f13708:c4:m6 |
def nif_nie_validation(doi, number_by_letter, special_cases): | doi = doi.upper()<EOL>if doi in special_cases:<EOL><INDENT>return False<EOL><DEDENT>table = '<STR_LIT>'<EOL>if len(doi) == <NUM_LIT:9>:<EOL><INDENT>control = doi[<NUM_LIT:8>]<EOL>numbers = number_by_letter.get(doi[<NUM_LIT:0>], doi[<NUM_LIT:0>]) + doi[<NUM_LIT:1>:<NUM_LIT:8>]<EOL>return numbers.isdigit() and control == table[int(numbers) % <NUM_LIT>]<EOL><DEDENT>return False<EOL> | Validate if the doi is a NIF or a NIE.
:param doi: DOI to validate.
:return: boolean if it's valid. | f13724:m0 |
def is_cif(doi): | doi = doi.upper()<EOL>if len(doi) != <NUM_LIT:9>:<EOL><INDENT>return False<EOL><DEDENT>table = '<STR_LIT>'<EOL>first_chr = doi[<NUM_LIT:0>]<EOL>doi_body = doi[<NUM_LIT:1>:<NUM_LIT:8>]<EOL>control = doi[<NUM_LIT:8>]<EOL>if not doi_body.isdigit():<EOL><INDENT>return False<EOL><DEDENT>odd_result = sum(int(x) for x in '<STR_LIT>'.join(str(int(x) * <NUM_LIT:2>) for x in doi_body[<NUM_LIT:0>::<NUM_LIT:2>]))<EOL>even_result = sum(map(int, doi_body[<NUM_LIT:1>::<NUM_LIT:2>]))<EOL>res = (<NUM_LIT:10> - (even_result + odd_result) % <NUM_LIT:10>) % <NUM_LIT:10><EOL>if first_chr in '<STR_LIT>': <EOL><INDENT>return str(res) == control<EOL><DEDENT>elif first_chr in '<STR_LIT>': <EOL><INDENT>return table[res] == control<EOL><DEDENT>elif first_chr not in '<STR_LIT>':<EOL><INDENT>return False<EOL><DEDENT>return control == str(res) or control == table[res]<EOL> | Validate if the doi is a CIF.
:param doi: DOI to validate.
:return: boolean if it's valid. | f13724:m1 |
def is_nif(doi): | number_by_letter = {'<STR_LIT:L>': '<STR_LIT:0>', '<STR_LIT:M>': '<STR_LIT:0>', '<STR_LIT>': '<STR_LIT:0>'}<EOL>special_cases = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>return nif_nie_validation(doi, number_by_letter, special_cases)<EOL> | Validate if the doi is a NIF.
:param doi: DOI to validate.
:return: boolean if it's valid. | f13724:m2 |
def is_nie(doi): | number_by_letter = {'<STR_LIT:X>': '<STR_LIT:0>', '<STR_LIT:Y>': '<STR_LIT:1>', '<STR_LIT>': '<STR_LIT:2>'}<EOL>special_cases = ['<STR_LIT>']<EOL>if not doi or doi[<NUM_LIT:0>] not in number_by_letter.keys():<EOL><INDENT>return False<EOL><DEDENT>return nif_nie_validation(doi, number_by_letter, special_cases)<EOL> | Validate if the doi is a NIE.
:param doi: DOI to validate.
:return: boolean if it's valid. | f13724:m3 |
def __init__(self, generator): | self.generator = generator<EOL>self.max_name_len = <NUM_LIT:0><EOL>self.already_generated = []<EOL> | :param generator: a localized Generator with providers filled,
for which to write the documentation
:type generator: faker.Generator() | f13736:c0:m0 |
def execute_from_command_line(argv=None): | if sys.stdout.encoding is None:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>file=sys.stderr)<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>command = Command(argv)<EOL>command.execute()<EOL> | A simple method that runs a Command. | f13738:m2 |
def execute(self): | <EOL>default_locale = os.environ.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>if default_locale not in AVAILABLE_LOCALES:<EOL><INDENT>default_locale = DEFAULT_LOCALE<EOL><DEDENT>epilog = | Given the command-line arguments, this creates a parser appropriate
to that command, and runs it. | f13738:c0:m1 |
def slugify(value, allow_dots=False, allow_unicode=False): | if allow_dots:<EOL><INDENT>pattern = _re_pattern_allow_dots<EOL><DEDENT>else:<EOL><INDENT>pattern = _re_pattern<EOL><DEDENT>value = six.text_type(value)<EOL>if allow_unicode:<EOL><INDENT>value = unicodedata.normalize('<STR_LIT>', value)<EOL>value = pattern.sub('<STR_LIT>', value).strip().lower()<EOL>return _re_spaces.sub('<STR_LIT:->', value)<EOL><DEDENT>value = unicodedata.normalize('<STR_LIT>', value).encode(<EOL>'<STR_LIT:ascii>', '<STR_LIT:ignore>').decode('<STR_LIT:ascii>')<EOL>value = pattern.sub('<STR_LIT>', value).strip().lower()<EOL>return _re_spaces.sub('<STR_LIT:->', value)<EOL> | Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace. Modified to optionally allow dots.
Adapted from Django 1.9 | f13740:m0 |
def new_date(d): | return date(d.year, d.month, d.day)<EOL> | Generate a safe date from a datetime.date object. | f13744:m0 |
def new_datetime(d): | kw = [d.year, d.month, d.day]<EOL>if isinstance(d, real_datetime):<EOL><INDENT>kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])<EOL><DEDENT>return datetime(*kw)<EOL> | Generate a safe datetime from a datetime.date or datetime.datetime object. | f13744:m1 |
def add_dicts(*args): | counters = [Counter(arg) for arg in args]<EOL>return dict(reduce(operator.add, counters))<EOL> | Adds two or more dicts together. Common keys will have their values added.
For example::
>>> t1 = {'a':1, 'b':2}
>>> t2 = {'b':1, 'c':3}
>>> t3 = {'d':4}
>>> add_dicts(t1, t2, t3)
{'a': 1, 'c': 3, 'b': 3, 'd': 4} | f13746:m0 |
def get_providers(self): | return self.providers<EOL> | Returns added providers. | f13748:c0:m3 |
def seed_instance(self, seed=None): | if self.__random == random:<EOL><INDENT>self.__random = random_module.Random()<EOL><DEDENT>self.__random.seed(seed)<EOL>return self<EOL> | Calls random.seed | f13748:c0:m6 |
def format(self, formatter, *args, **kwargs): | <EOL>return self.get_formatter(formatter)(*args, **kwargs)<EOL> | This is a secure way to make a fake from another Provider. | f13748:c0:m8 |
def set_formatter(self, name, method): | setattr(self, name, method)<EOL> | This method adds a provider method to generator.
Override this method to add some decoration or logging stuff. | f13748:c0:m10 |
def parse(self, text): | return _re_token.sub(self.__format_token, text)<EOL> | Replaces tokens (like '{{ tokenName }}' or '{{tokenName}}')
with the result from the token method call. | f13748:c0:m11 |
def remove_accents(value): | search = '<STR_LIT>'<EOL>replace = '<STR_LIT>'<EOL>def replace_accented_character(match):<EOL><INDENT>matched = match.group(<NUM_LIT:0>)<EOL>if matched in search:<EOL><INDENT>return replace[search.find(matched)]<EOL><DEDENT>return matched<EOL><DEDENT>return re.sub(r'<STR_LIT>'.format(search), replace_accented_character, value)<EOL> | Remove accents from characters in the given string. | f13758:m0 |
def latinize(value): | def replace_double_character(match):<EOL><INDENT>search = ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>').split()<EOL>replace = ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>').split()<EOL>matched = match.group(<NUM_LIT:0>)<EOL>if matched in search:<EOL><INDENT>return replace[search.index(matched)]<EOL><DEDENT>return matched<EOL><DEDENT>search = '<STR_LIT>'<EOL>replace = '<STR_LIT>'<EOL>def replace_greek_character(match):<EOL><INDENT>matched = list(match.group(<NUM_LIT:0>))<EOL>value = map(lambda l: replace[search.find(l)], matched)<EOL>return '<STR_LIT>'.join(value)<EOL><DEDENT>return re.sub(r'<STR_LIT>'.format(search),<EOL>replace_greek_character, re.sub(<EOL>r'<STR_LIT>',<EOL>replace_double_character,<EOL>remove_accents(value)))<EOL> | Converts (transliterates) greek letters to latin equivalents. | f13758:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.