code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
warnings.warn("/oauth/ro will be deprecated in future releases", DeprecationWarning) return self.post( 'https://{}/oauth/ro'.format(self.domain), data={ 'client_id': client_id, 'username': username, 'password': password, ...
def login(self, client_id, username, password, connection, id_token=None, grant_type='password', device=None, scope='openid')
Login using username and password Given the user credentials and the connection specified, it will do the authentication on the provider and return a dict with the access_token and id_token. This endpoint only works for database connections, passwordless connections, Active Directory/LD...
2.400555
2.531396
0.948313
body = { 'client_id': client_id, 'email': email, 'password': password, 'connection': connection, 'username': username, 'user_metadata': user_metadata } return self.post( 'https://{}/dbconnections/signup...
def signup(self, client_id, email, password, connection, username=None, user_metadata=None)
Signup using email and password. Args: client_id (str): ID of the application to use. email (str): The user's email address. password (str): The user's desired password. connection (str): The name of the database connection where this user should be create...
2.242429
2.306466
0.972236
return self.post( 'https://{}/dbconnections/change_password'.format(self.domain), data={ 'client_id': client_id, 'email': email, 'password': password, 'connection': connection, }, headers={'...
def change_password(self, client_id, email, connection, password=None)
Asks to change a password for a given user.
2.694785
2.916484
0.923984
no_setup_requires_arguments = ( '-h', '--help', '-n', '--dry-run', '-q', '--quiet', '-v', '--verbose', '-V', '--version', '--author', '--author-email', '--classifiers', '--contact', '--contact-email', '--description', ...
def keywords_with_side_effects(argv)
Get a dictionary with setup keywords that (can) have side effects. :param argv: A list of strings with command line arguments. :returns: A dictionary with keyword arguments for the ``setup()`` function. This setup.py script uses the setuptools 'setup_requires' feature because this is required by the c...
2.968305
2.940276
1.009533
hkey = k[:_inbytes(self.keysize)] ekey = k[_inbytes(self.keysize):] # encrypt iv = _randombits(self.blocksize) cipher = Cipher(algorithms.AES(ekey), modes.CBC(iv), backend=self.backend) encryptor = cipher.encryptor() padder = PKCS...
def encrypt(self, k, a, m)
Encrypt according to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authentication Data :param m: Plaintext Returns a dictionary with the computed data.
2.831542
3.167868
0.893832
hkey = k[:_inbytes(self.keysize)] dkey = k[_inbytes(self.keysize):] # verify mac if not constant_time.bytes_eq(t, self._mac(hkey, a, iv, e)): raise InvalidSignature('Failed to verify MAC') # decrypt cipher = Cipher(algorithms.AES(dkey), modes.CBC(iv...
def decrypt(self, k, a, iv, e, t)
Decrypt according to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication Tag Returns plaintext or raises an error
2.828671
3.058453
0.92487
iv = _randombits(96) cipher = Cipher(algorithms.AES(k), modes.GCM(iv), backend=self.backend) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(a) e = encryptor.update(m) + encryptor.finalize() return (iv, e, encryptor....
def encrypt(self, k, a, m)
Encrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authentication Data :param m: Plaintext Returns a dictionary with the computed data.
2.860318
3.319065
0.861784
cipher = Cipher(algorithms.AES(k), modes.GCM(iv, t), backend=self.backend) decryptor = cipher.decryptor() decryptor.authenticate_additional_data(a) return decryptor.update(e) + decryptor.finalize()
def decrypt(self, k, a, iv, e, t)
Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication Tag Returns plaintext or raises an erro...
2.051314
2.404383
0.853156
obj = cls() try: jkey = json_decode(key) except Exception as e: # pylint: disable=broad-except raise InvalidJWKValue(e) obj.import_key(**jkey) return obj
def from_json(cls, key)
Creates a RFC 7517 JWK from the standard JSON format. :param key: The RFC 7517 representation of a JWK.
4.802056
4.786366
1.003278
if private_key is True: # Use _export_all for backwards compatibility, as this # function allows to export symmetrict keys too return self._export_all() else: return self.export_public()
def export(self, private_key=True)
Exports the key in the standard JSON format. Exports the key regardless of type, if private_key is False and the key is_symmetric an exceptionis raised. :param private_key(bool): Whether to export the private key. Defaults to True.
10.64411
9.082932
1.17188
if self.is_symmetric: return False reg = JWKValuesRegistry[self._params['kty']] for value in reg: if reg[value].public and value in self._key: return True
def has_public(self)
Whether this JWK has an asymmetric Public key.
13.555452
8.692871
1.559376
k = self._key if self._params['kty'] not in ['EC', 'OKP']: raise InvalidJWKType('Not an EC or OKP key') if arg and k['crv'] != arg: raise InvalidJWKValue('Curve requested is "%s", but ' 'key curve is "%s"' % (arg, k['crv'])) ...
def get_curve(self, arg)
Gets the Elliptic Curve associated with the key. :param arg: an optional curve name :raises InvalidJWKType: the key is not an EC or OKP key. :raises InvalidJWKValue: if the curve names is invalid.
4.265827
3.168746
1.346219
validops = self._params.get('key_ops', list(JWKOperationsRegistry.keys())) if validops is not list: validops = [validops] if operation is None: if self._params['kty'] == 'oct': return self._key['k'] ...
def get_op_key(self, operation=None, arg=None)
Get the key object associated to the requested opration. For example the public RSA key for the 'verify' operation or the private EC key for the 'decrypt' operation. :param operation: The requested operation. The valid set of operations is availble in the :data:`JWKOperationsR...
2.686903
2.336835
1.149804
try: key = serialization.load_pem_private_key( data, password=password, backend=default_backend()) except ValueError as e: if password is not None: raise e try: key = serialization.load_pem_public_key( ...
def import_from_pem(self, data, password=None)
Imports a key from data loaded from a PEM file. The key may be encrypted with a password. Private keys (PKCS#8 format), public keys, and X509 certificate's public keys can be imported with this interface. :param data(bytes): The data contained in a PEM file. :param password(byte...
2.171796
2.286235
0.949944
e = serialization.Encoding.PEM if private_key: if not self.has_private: raise InvalidJWKType("No private key available") f = serialization.PrivateFormat.PKCS8 if password is None: a = serialization.NoEncryption() el...
def export_to_pem(self, private_key=False, password=False)
Exports keys to a data buffer suitable to be stored as a PEM file. Either the public or the private key can be exported to a PEM file. For private keys the PKCS#8 format is used. If a password is provided the best encryption method available as determined by the cryptography module is us...
2.328697
2.388658
0.974897
obj = cls() obj.import_from_pem(data, password) return obj
def from_pem(cls, data, password=None)
Creates a key from PKCS#8 formatted data loaded from a PEM file. See the function `import_from_pem` for details. :param data(bytes): The data contained in a PEM file. :param password(bytes): An optional password to unwrap the key.
4.569929
5.687638
0.803484
t = {'kty': self._params['kty']} for name, val in iteritems(JWKValuesRegistry[t['kty']]): if val.required: t[name] = self._key[name] digest = hashes.Hash(hashalg, backend=default_backend()) digest.update(bytes(json_encode(t).encode('utf8'))) ...
def thumbprint(self, hashalg=hashes.SHA256())
Returns the key thumbprint as specified by RFC 7638. :param hashalg: A hash function (defaults to SHA256)
4.661511
4.824299
0.966257
if not isinstance(elem, JWK): raise TypeError('Only JWK objects are valid elements') set.add(self, elem)
def add(self, elem)
Adds a JWK object to the set :param elem: the JWK object to add. :raises TypeError: if the object is not a JWK.
7.603588
6.387132
1.190454
exp_dict = dict() for k, v in iteritems(self): if k == 'keys': keys = list() for jwk in v: keys.append(json_decode(jwk.export(private_keys))) v = keys exp_dict[k] = v return json_encode(exp_dict)
def export(self, private_keys=True)
Exports a RFC 7517 keyset using the standard JSON format :param private_key(bool): Whether to export private keys. Defaults to True.
3.486623
3.718165
0.937727
try: jwkset = json_decode(keyset) except Exception: # pylint: disable=broad-except raise InvalidJWKValue() if 'keys' not in jwkset: raise InvalidJWKValue() for k, v in iteritems(jwkset): if k == 'keys': for jwk i...
def import_keyset(self, keyset)
Imports a RFC 7517 keyset using the standard JSON format. :param keyset: The RFC 7517 representation of a JOSE Keyset.
2.7898
2.934964
0.95054
if self.plaintext is None: raise ValueError('Missing plaintext') if not isinstance(self.plaintext, bytes): raise ValueError("Plaintext must be 'bytes'") if isinstance(header, dict): header = json_encode(header) jh = self._get_jose_header(hea...
def add_recipient(self, key, header=None)
Encrypt the plaintext with the given key. :param key: A JWK key or password of appropriate type for the 'alg' provided in the JOSE Headers. :param header: A JSON string representing the per-recipient header. :raises ValueError: if the plaintext is missing or not of type bytes. ...
2.770923
2.675777
1.035558
if 'ciphertext' not in self.objects: raise InvalidJWEOperation("No available ciphertext") if compact: for invalid in 'aad', 'unprotected': if invalid in self.objects: raise InvalidJWEOperation( "Can't use comp...
def serialize(self, compact=False)
Serializes the object into a JWE token. :param compact(boolean): if True generates the compact representation, otherwise generates a standard JSON format. :raises InvalidJWEOperation: if the object cannot serialized with the compact representation and `compact` is True. :rais...
2.501411
2.448091
1.02178
if 'ciphertext' not in self.objects: raise InvalidJWEOperation("No available ciphertext") self.decryptlog = list() if 'recipients' in self.objects: for rec in self.objects['recipients']: try: self._decrypt(key, rec) ...
def decrypt(self, key)
Decrypt a JWE token. :param key: The (:class:`jwcrypto.jwk.JWK`) decryption key. :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key or a password string (optional). :raises InvalidJWEOperation: if the key is not a JWK object. :raises InvalidJWEData: if the ciphertext can...
3.621127
3.236636
1.118793
self.objects = dict() self.plaintext = None self.cek = None o = dict() try: try: djwe = json_decode(raw_jwe) o['iv'] = base64url_decode(djwe['iv']) o['ciphertext'] = base64url_decode(djwe['ciphertext']) ...
def deserialize(self, raw_jwe, key=None)
Deserialize a JWE token. NOTE: Destroys any current status and tries to import the raw JWE provided. :param raw_jwe: a 'raw' JWE token (JSON Encoded or Compact notation) string. :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key or a password string (optional). ...
1.727251
1.724397
1.001655
payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) signature = self.engine.sign(self.key, sigin) return {'protected': self.protected, 'payload': payload, 'signature': base64url_encode(signature)}
def sign(self)
Generates a signature
4.445624
4.181938
1.063054
try: payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) self.engine.verify(self.key, sigin, signature) except Exception as e: # pylint: disable=broad-except raise InvalidJWSSignature('Verification failed', repr...
def verify(self, signature)
Verifies a signature :raises InvalidJWSSignature: if the verification fails.
5.577739
4.838322
1.152825
self.verifylog = list() self.objects['valid'] = False obj = self.objects if 'signature' in obj: try: self._verify(alg, key, obj['payload'], obj['signature'], obj.g...
def verify(self, key, alg=None)
Verifies a JWS token. :param key: The (:class:`jwcrypto.jwk.JWK`) verification key. :param alg: The signing algorithm (optional). usually the algorithm is known as it is provided with the JOSE Headers of the token. :raises InvalidJWSSignature: if the verification fails.
2.940171
2.795123
1.051893
self.objects = dict() o = dict() try: try: djws = json_decode(raw_jws) if 'signatures' in djws: o['signatures'] = list() for s in djws['signatures']: os = self._deserialize_signat...
def deserialize(self, raw_jws, key=None, alg=None)
Deserialize a JWS token. NOTE: Destroys any current status and tries to import the raw JWS provided. :param raw_jws: a 'raw' JWS token (JSON Encoded or Compact notation) string. :param key: A (:class:`jwcrypto.jwk.JWK`) verification key (optional). If a key is provide...
2.35972
2.383301
0.990106
if not self.objects.get('payload', None): raise InvalidJWSObject('Missing Payload') b64 = True p = dict() if protected: if isinstance(protected, dict): p = protected protected = json_encode(p) else: ...
def add_signature(self, key, alg=None, protected=None, header=None)
Adds a new signature to the object. :param key: A (:class:`jwcrypto.jwk.JWK`) key of appropriate for the "alg" provided. :param alg: An optional algorithm name. If already provided as an element of the protected or unprotected header it can be safely omitted. :param p...
2.483904
2.420238
1.026306
if compact: if 'signatures' in self.objects: raise InvalidJWSOperation("Can't use compact encoding with " "multiple signatures") if 'signature' not in self.objects: raise InvalidJWSSignature("No available ...
def serialize(self, compact=False)
Serializes the object into a JWS token. :param compact(boolean): if True generates the compact representation, otherwise generates a standard JSON format. :raises InvalidJWSOperation: if the object cannot serialized with the compact representation and `compat` is True. :raise...
1.93893
1.825569
1.062096
t = JWS(self.claims) t.add_signature(key, protected=self.header) self.token = t
def make_signed_token(self, key)
Signs the payload. Creates a JWS token with the header as the JWS protected header and the claims as the payload. See (:class:`jwcrypto.jws.JWS`) for details on the exceptions that may be reaised. :param key: A (:class:`jwcrypto.jwk.JWK`) key.
7.634037
6.975766
1.094366
t = JWE(self.claims, self.header) t.add_recipient(key) self.token = t
def make_encrypted_token(self, key)
Encrypts the payload. Creates a JWE token with the header as the JWE protected header and the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for details on the exceptions that may be reaised. :param key: A (:class:`jwcrypto.jwk.JWK`) key.
8.200864
7.28502
1.125716
c = jwt.count('.') if c == 2: self.token = JWS() elif c == 4: self.token = JWE() else: raise ValueError("Token format unrecognized") # Apply algs restrictions if any, before performing any operation if self._algs: ...
def deserialize(self, jwt, key=None)
Deserialize a JWT token. NOTE: Destroys any current status and tries to import the raw token provided. :param jwt: a 'raw' JWT token. :param key: A (:class:`jwcrypto.jwk.JWK`) verification or decryption key, or a (:class:`jwcrypto.jwk.JWKSet`) that contains a key inde...
3.200133
3.134585
1.020911
iter_valid = copy.copy(self.iter_valid) losses, lbl_trues, lbl_preds = [], [], [] vizs = [] dataset = iter_valid.dataset desc = 'valid [iteration=%08d]' % self.iteration for batch in tqdm.tqdm(iter_valid, desc=desc, total=len(dataset), ...
def validate(self, n_viz=9)
Validate current model using validation dataset. Parameters ---------- n_viz: int Number fo visualization. Returns ------- log: dict Log values.
2.596512
2.633215
0.986062
self.stamp_start = time.time() for iteration, batch in tqdm.tqdm(enumerate(self.iter_train), desc='train', total=self.max_iter, ncols=80): self.epoch = self.iter_train.epoch self.iteratio...
def train(self)
Train the network using the training dataset. Parameters ---------- None Returns ------- None
2.958436
2.998869
0.986517
if src.shape[:2] == dst_shape[:2]: return src centerized = np.zeros(dst_shape, dtype=src.dtype) if margin_color: centerized[:, :] = margin_color pad_vertical, pad_horizontal = 0, 0 h, w = src.shape[:2] dst_h, dst_w = dst_shape[:2] if h < dst_h: pad_vertical = (ds...
def centerize(src, dst_shape, margin_color=None)
Centerize image for specified image size @param src: image to centerize @param dst_shape: image shape (height, width) or (height, width, channel)
1.679561
1.773497
0.947033
y_num, x_num = tile_shape one_width = imgs[0].shape[1] one_height = imgs[0].shape[0] if concatenated_image is None: if len(imgs[0].shape) == 3: n_channels = imgs[0].shape[2] assert all(im.shape[2] == n_channels for im in imgs) concatenated_image = np.zero...
def _tile_images(imgs, tile_shape, concatenated_image)
Concatenate images whose sizes are same. @param imgs: image list which should be concatenated @param tile_shape: shape for which images should be concatenated @param concatenated_image: returned image. if it is None, new image will be created.
1.638103
1.670523
0.980593
def resize(*args, **kwargs): # anti_aliasing arg cannot be passed to skimage<0.14 # use LooseVersion to allow 0.14dev. if LooseVersion(skimage.__version__) < LooseVersion('0.14'): kwargs.pop('anti_aliasing', None) return skimage.transform.resize(*args, **kwargs) ...
def get_tile_image(imgs, tile_shape=None, result_img=None, margin_color=None)
Concatenate images whose sizes are different. @param imgs: image list which should be concatenated @param tile_shape: shape for which images should be concatenated @param result_img: numpy array to put result image
2.337143
2.328938
1.003523
img = kwargs.pop('img', None) lbl_true = kwargs.pop('lbl_true', None) lbl_pred = kwargs.pop('lbl_pred', None) n_class = kwargs.pop('n_class', None) label_names = kwargs.pop('label_names', None) if kwargs: raise RuntimeError( 'Unexpected keys in kwargs: {}'.format(kwargs....
def visualize_segmentation(**kwargs)
Visualize segmentation. Parameters ---------- img: ndarray Input image to predict label. lbl_true: ndarray Ground truth of the label. lbl_pred: ndarray Label predicted. n_class: int Number of classes. label_names: dict or list Names of each label valu...
1.72553
1.66237
1.037994
factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] filter = (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1] - center) / factor) return filter
def _get_upsampling_filter(size)
Make a 2D bilinear kernel suitable for upsampling
1.390924
1.323959
1.050579
if output_format is None: file_name, file_ext = path.splitext(output_path) output_format = file_ext[len(extsep):].lower() self.LOG.debug("Output format is not explicitly set, determined format is {0}.".format(output_format)) if not dry_run: if ou...
def create(self, output_path, dry_run=False, output_format=None, compresslevel=None)
Create the archive at output_file_path. Type of the archive is determined either by extension of output_file_path or by output_format. Supported formats are: gz, zip, bz2, xz, tar, tgz, txz @param output_path: Output file path. @type output_path: str @param dry_run: Determines...
2.044438
2.075337
0.985111
next(self._check_attr_gens[repo_abspath]) attrs = self._check_attr_gens[repo_abspath].send(repo_file_path) return attrs['export-ignore'] == 'set'
def is_file_excluded(self, repo_abspath, repo_file_path)
Checks whether file at a given path is excluded. @param repo_abspath: Absolute path to the git repository. @type repo_abspath: str @param repo_file_path: Path to a file relative to repo_abspath. @type repo_file_path: str @return: True if file should be excluded. Otherwise Fals...
9.142146
10.661208
0.857515
for file_path in self.extra: archiver(path.abspath(file_path), path.join(self.prefix, file_path)) for file_path in self.walk_git_files(): archiver(path.join(self.main_repo_abspath, file_path), path.join(self.prefix, file_path))
def archive_all_files(self, archiver)
Archive all files using archiver. @param archiver: Callable that accepts 2 arguments: abspath to file on the system and relative path within archive. @type archiver: Callable
4.06413
4.1071
0.989538
repo_abspath = path.join(self.main_repo_abspath, repo_path) assert repo_abspath not in self._check_attr_gens self._check_attr_gens[repo_abspath] = self.check_attr(repo_abspath, ['export-ignore']) try: repo_file_paths = self.run_git_shell( 'git ls-fil...
def walk_git_files(self, repo_path='')
An iterator method that yields a file path relative to main_repo_abspath for each file that should be included in the archive. Skips those that match the exclusion patterns found in any discovered .gitattributes files along the way. Recurs into submodules as well. @param repo_p...
2.232218
2.157279
1.034738
def make_process(): env = dict(environ, GIT_FLUSH='1') cmd = 'git check-attr --stdin -z {0}'.format(' '.join(attrs)) return Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, cwd=repo_abspath, env=env) def read_attrs(process, repo_file_path): proces...
def check_attr(self, repo_abspath, attrs)
Generator that returns attributes for given paths relative to repo_abspath. >>> g = GitArchiver.check_attr('repo_path', ['export-ignore']) >>> next(g) >>> attrs = g.send('relative_path') >>> print(attrs['export-ignore']) @param repo_abspath: Absolute path to a git repository. ...
2.367434
2.344548
1.009761
p = Popen(cmd, shell=True, stdout=PIPE, cwd=cwd) output, _ = p.communicate() output = cls.decode_git_output(output) if p.returncode: if sys.version_info > (2, 6): raise CalledProcessError(returncode=p.returncode, cmd=cmd, output=output) e...
def run_git_shell(cls, cmd, cwd=None)
Runs git shell command, reads output and decodes it into unicode string. @param cmd: Command to be executed. @type cmd: str @type cwd: str @param cwd: Working directory. @rtype: str @return: Output of the command. @raise CalledProcessError: Raises exception i...
2.153832
2.222888
0.968934
try: output = cls.run_git_shell('git version') except CalledProcessError: cls.LOG.warning("Unable to get Git version.") return None try: version = output.split()[2] except IndexError: cls.LOG.warning("Unable to parse G...
def get_git_version(cls)
Return version of git current shell points to. If version cannot be parsed None is returned. @rtype: tuple or None
2.408863
2.346238
1.026692
'''Base function for one time http requests. Args: method (str): The http method to use. For example 'GET' uri (str): The url of the resource. Example: 'https://example.com/stuff' kwargs: Any number of arguments supported, found here: http://asks.rtfd.io/en/lates...
async def request(method, uri, **kwargs)
Base function for one time http requests. Args: method (str): The http method to use. For example 'GET' uri (str): The url of the resource. Example: 'https://example.com/stuff' kwargs: Any number of arguments supported, found here: http://asks.rtfd.io/en/latest/overv...
5.027074
1.920265
2.617906
parts = uri.split('%') for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 and h.isalnum(): try: c = chr(int(h, 16)) except ValueError: raise ValueError("Invalid percent-escape sequence: '%s'" % h) if c in UNRE...
def unquote_unreserved(uri)
Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str
2.1639
2.11253
1.024317
safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_p...
def requote_uri(uri)
Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str
4.589056
4.676187
0.981367
''' Takes care of the i/o side of the request once it's been built, and calls a couple of cleanup functions to check for redirects / store cookies and the likes. Args: h11_request (h11.Request): A h11.Request object h11_body (h11.Data): A h11.Data object,...
async def _request_io(self, h11_request, h11_body, h11_connection)
Takes care of the i/o side of the request once it's been built, and calls a couple of cleanup functions to check for redirects / store cookies and the likes. Args: h11_request (h11.Request): A h11.Request object h11_body (h11.Data): A h11.Data object, representing the re...
6.145422
2.808915
2.187828
''' Constructs the actual request URL with accompanying query if any. Returns: None: But does modify self.path, which contains the final request path sent to the server. ''' if not self.path: self.path = '/' if self.uri_parameter...
def _build_path(self)
Constructs the actual request URL with accompanying query if any. Returns: None: But does modify self.path, which contains the final request path sent to the server.
3.619014
2.329011
1.553885
''' Calls the _check_redirect method of the supplied response object in order to determine if the http status code indicates a redirect. Returns: Response: May or may not be the result of recursive calls due to redirects! Notes: If it does re...
async def _redirect(self, response_obj)
Calls the _check_redirect method of the supplied response object in order to determine if the http status code indicates a redirect. Returns: Response: May or may not be the result of recursive calls due to redirects! Notes: If it does redirect, it calls the...
4.612394
2.792785
1.651539
''' On 'Connection: close' headers we've to create a new connection. This reaches in to the parent session and pulls a switcheroo, dunking the current connection and requesting a new one. ''' self.sock._active = False self.sock = await self.session._grab_connectio...
async def _get_new_sock(self)
On 'Connection: close' headers we've to create a new connection. This reaches in to the parent session and pulls a switcheroo, dunking the current connection and requesting a new one.
16.938375
2.598813
6.517736
''' Takes user supplied data / files and forms it / them appropriately, returning the contents type, len, and the request body its self. Returns: The str mime type for the Content-Type header. The len of the body. The body as a str. ''...
async def _formulate_body(self)
Takes user supplied data / files and forms it / them appropriately, returning the contents type, len, and the request body its self. Returns: The str mime type for the Content-Type header. The len of the body. The body as a str.
3.394696
2.037191
1.666361
''' Turns python dicts in to valid body-queries or queries for use directly in the request url. Unlike the stdlib quote() and it's variations, this also works on iterables like lists which are normally not valid. The use of lists in this manner is not a great idea unless ...
def _dict_to_query(data, params=True, base_query=False)
Turns python dicts in to valid body-queries or queries for use directly in the request url. Unlike the stdlib quote() and it's variations, this also works on iterables like lists which are normally not valid. The use of lists in this manner is not a great idea unless the server supports...
4.660281
1.896441
2.457383
''' Forms multipart requests from a dict with name, path k/vs. Name does not have to be the actual file name. Args: files_dict (dict): A dict of `filename:filepath`s, to be sent as multipart files. Returns: multip_pkg (str): The strings repre...
async def _multipart(self, files_dict)
Forms multipart requests from a dict with name, path k/vs. Name does not have to be the actual file name. Args: files_dict (dict): A dict of `filename:filepath`s, to be sent as multipart files. Returns: multip_pkg (str): The strings representation of the con...
3.621479
2.262479
1.600669
''' Instantiates the parser which manages incoming data, first getting the headers, storing cookies, and then parsing the response's body, if any. This function also instances the Response class in which the response status line, headers, cookies, and body is stored. ...
async def _catch_response(self, h11_connection)
Instantiates the parser which manages incoming data, first getting the headers, storing cookies, and then parsing the response's body, if any. This function also instances the Response class in which the response status line, headers, cookies, and body is stored. It should be n...
3.623669
2.256892
1.605601
''' Takes a package and body, combines then, then shoots 'em off in to the ether. Args: package (list of str): The header package. body (str): The str representation of the body. ''' await self.sock.send_all(h11_connection.send(request_bytes)) ...
async def _send(self, request_bytes, body_bytes, h11_connection)
Takes a package and body, combines then, then shoots 'em off in to the ether. Args: package (list of str): The header package. body (str): The str representation of the body.
4.960176
1.733603
2.861196
''' If the user supplied auth does rely on a response (is a PostResponseAuth object) then we call the auth's __call__ returning a dict to update the request's headers with, as long as there is an appropriate 401'd response object to calculate auth details from. ''...
async def _auth_handler_post_get_auth(self)
If the user supplied auth does rely on a response (is a PostResponseAuth object) then we call the auth's __call__ returning a dict to update the request's headers with, as long as there is an appropriate 401'd response object to calculate auth details from.
7.733469
2.369389
3.263909
''' The other half of _auth_handler_post_check_retry (what a mouthful). If auth has not yet been attempted and the most recent response object is a 401, we store that response object and retry the request in exactly the same manner as before except with the correct auth. ...
async def _auth_handler_post_check_retry(self, response_obj)
The other half of _auth_handler_post_check_retry (what a mouthful). If auth has not yet been attempted and the most recent response object is a 401, we store that response object and retry the request in exactly the same manner as before except with the correct auth. If it fails a secon...
5.772559
2.190066
2.635793
''' Checks to see if the new location is 1. The same top level domain 2. As or more secure than the current connection type Returns: True (bool): If the current top level domain is the same and the connection type is equally or more secure. ...
async def _location_auth_protect(self, location)
Checks to see if the new location is 1. The same top level domain 2. As or more secure than the current connection type Returns: True (bool): If the current top level domain is the same and the connection type is equally or more secure. False ...
3.902331
2.220527
1.75739
''' A callback func to be supplied if the user wants to do something directly with the response body's stream. ''' # pylint: disable=not-callable while True: next_event = await self._recv_event(h11_connection) if isinstance(next_event, h11.Data): ...
async def _body_callback(self, h11_connection)
A callback func to be supplied if the user wants to do something directly with the response body's stream.
5.468048
2.622687
2.084903
''' Creates a normal async socket, returns it. Args: location (tuple(str, int)): A tuple of net location (eg '127.0.0.1' or 'example.org') and port (eg 80 or 25000). ''' sock = await connect_tcp(location[0], location[1], bind_host=self.source_address) ...
async def _open_connection_http(self, location)
Creates a normal async socket, returns it. Args: location (tuple(str, int)): A tuple of net location (eg '127.0.0.1' or 'example.org') and port (eg 80 or 25000).
7.955544
2.436662
3.264935
''' Creates an async SSL socket, returns it. Args: location (tuple(str, int)): A tuple of net location (eg '127.0.0.1' or 'example.org') and port (eg 80 or 25000). ''' sock = await connect_tcp(location[0], location[1], ...
async def _open_connection_https(self, location)
Creates an async SSL socket, returns it. Args: location (tuple(str, int)): A tuple of net location (eg '127.0.0.1' or 'example.org') and port (eg 80 or 25000).
6.670624
2.731613
2.442009
''' Simple enough stuff to figure out where we should connect, and creates the appropriate connection. ''' scheme, host, path, parameters, query, fragment = urlparse( host_loc) if parameters or query or fragment: raise ValueError('Supplied info bey...
async def _connect(self, host_loc)
Simple enough stuff to figure out where we should connect, and creates the appropriate connection.
7.072578
4.471385
1.581742
if isinstance(e, (RemoteProtocolError, AssertionError)): await sock.close() raise BadHttpResponse('Invalid HTTP response from server.') from e if isinstance(e, Exception): await sock.close() raise e
async def _handle_exception(self, e, sock)
Given an exception, we want to handle it appropriately. Some exceptions we prefer to shadow with an asks exception, and some we want to raise directly. In all cases we clean up the underlying socket.
6.626234
6.256636
1.059073
''' The connection pool handler. Returns a connection to the caller. If there are no connections ready, and as many connections checked out as there are available total, we yield control to the event loop. If there is a connection ready or space to create a new one, we ...
async def _grab_connection(self, url)
The connection pool handler. Returns a connection to the caller. If there are no connections ready, and as many connections checked out as there are available total, we yield control to the event loop. If there is a connection ready or space to create a new one, we pop/create it...
8.599785
1.804423
4.765948
''' If the response's body is valid json, we load it as a python dict and return it. ''' body = self._decompress(self.encoding) return _json.loads(body, **kwargs)
def json(self, **kwargs)
If the response's body is valid json, we load it as a python dict and return it.
8.143477
3.67439
2.21628
''' Raise BadStatus if one occurred. ''' if 400 <= self.status_code < 500: raise BadStatus('{} Client Error: {} for url: {}'.format(self.status_code, self.reason_phrase, self.url), self.status_code) elif 500 <= self.status_code < 600: raise BadStatus('{} S...
def raise_for_status(self)
Raise BadStatus if one occurred.
2.081643
1.732742
1.201358
cookie_pie = [] try: for cookie in response.headers['set-cookie']: cookie_jar = {} name_val, *rest = cookie.split(';') name, value = name_val.split('=', 1) cookie_jar['name'] = name.strip() cookie_jar['value'] = value for item ...
def parse_cookies(response, host)
Sticks cookies to a response.
2.640919
2.613609
1.010449
''' takes all the images coming from the redactor editor and stores it in the database and returns all the files ''' upurl = '' if request.FILES.get("upload"): f = request.FILES.get("upload") obj = Image_File.objects.create(upload=f, is_image=True) obj.save() thum...
def upload_photos(request)
takes all the images coming from the redactor editor and stores it in the database and returns all the files
3.112222
2.638504
1.179541
''' returns all the images from the data base ''' imgs = [] for obj in Image_File.objects.filter(is_image=True).order_by("-date_created"): upurl = "/" + obj.upload.url thumburl = "" if obj.thumbnail: thumburl = "/" + obj.thumbnail.url imgs.append({'src': upurl, 't...
def recent_photos(request)
returns all the images from the data base
4.276783
3.865848
1.106299
error = request.args.get('error') state = request.args.get('state') if error: return render_template('login_error.html', error=error) else: code = request.args.get('code') client = Client() access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CL...
def logged_in()
Method called by Strava (redirect) that includes parameters. - state - code - error
2.465686
2.380681
1.035706
if self.units: # Note that we don't want to cast to type in this case! if not isinstance(v, Quantity): v = self.units(v) elif not isinstance(v, self.type): v = self.type(v) return v
def unmarshal(self, v)
Convert the value from parsed JSON structure to native python representation. By default this will leave the value as-is since the JSON parsing routines typically convert to native types. The exception may be date strings or other more complex types, where subclasses will override this behavior...
4.682058
4.953691
0.945165
if not isinstance(v, date): # 2012-12-13 v = datetime.strptime(v, "%Y-%m-%d").date() return v
def unmarshal(self, v)
Convert a date in "2012-12-13" format to a :class:`datetime.date` object.
3.495254
2.286607
1.528577
if not isinstance(v, datetime): if isinstance(v, six.integer_types): v = arrow.get(v) else: try: # Most dates are in this format 2012-12-13T03:43:19Z v = datetime.strptime(v, "%Y-%m-%dT%H:%M:%SZ") ...
def unmarshal(self, v)
Convert a timestamp in "2012-12-13T03:43:19Z" format to a `datetime.datetime` object.
3.617261
2.916704
1.240188
return "{lat},{lon}".format(lat=v.lat, lon=v.lon) if v else None
def marshal(self, v)
Turn this value into format for wire (JSON). :param v: The lat/lon. :type v: LatLon :return: Serialized format. :rtype: str
6.471543
4.795624
1.349469
if not isinstance(v, tzinfo): # (GMT-08:00) America/Los_Angeles tzname = v.split(' ', 1)[1] v = pytz.timezone(tzname) return v
def unmarshal(self, v)
Convert a timestamp in format "(GMT-08:00) America/Los_Angeles" to a `pytz.timestamp` object.
4.026596
2.918782
1.379547
if not isinstance(v, timedelta): v = timedelta(seconds=v) return v
def unmarshal(self, v)
Convert the value from parsed JSON structure to native python representation. By default this will leave the value as-is since the JSON parsing routines typically convert to native types. The exception may be date strings or other more complex types, where subclasses will override this behavior...
4.508466
6.933887
0.650208
if v: orig = [i for i in self.choices if self.choices[i] == v] if len(orig) == 1: return orig[0] elif len(orig) == 0: # No such choice raise NotImplementedError("No such reverse choice {0} for field {1}.".format(v, self...
def marshal(self, v)
Turn this value into API format. Do a reverse dictionary lookup on choices to find the original value. If there are no keys or too many keys for now we raise a NotImplementedError as marshal is not used anywhere currently. In the future we will want to fail gracefully.
4.184234
3.367084
1.242688
try: return self.choices[v] except KeyError: self.log.warning("No such choice {0} for field {1}.".format(v, self)) # Just return the value from the API return v
def unmarshal(self, v)
Convert the value from Strava API format to useful python representation. If the value does not appear in the choices attribute we log an error rather than raising an exception as this may be caused by a change to the API upstream so we want to fail gracefully.
5.544923
4.259021
1.301924
#self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value)) if not isinstance(value, self.type): o = self.type() if bind_client is not None and hasattr(o.__class__, 'bind_client'): o.bind_client = bind_client if isinstance(value, dict): ...
def unmarshal(self, value, bind_client=None)
Cast the specified value to the entity type.
2.36779
2.277408
1.039686
if values is not None: return [super(EntityCollection, self).marshal(v) for v in values]
def marshal(self, values)
Turn a list of entities into a list of dictionaries. :param values: The entities to serialize. :type values: List[stravalib.model.BaseEntity] :return: List of dictionaries of attributes :rtype: List[Dict[str, Any]]
5.62053
5.663761
0.992367
if values is not None: return [super(EntityCollection, self).unmarshal(v, bind_client=bind_client) for v in values]
def unmarshal(self, values, bind_client=None)
Cast the list.
3.731094
3.141307
1.187752
return self.protocol.authorization_url(client_id=client_id, redirect_uri=redirect_uri, approval_prompt=approval_prompt, scope=scope, state=state)
def authorization_url(self, client_id, redirect_uri, approval_prompt='auto', scope=None, state=None)
Get the URL needed to authorize your application to access a Strava user's information. :param client_id: The numeric developer client id. :type client_id: int :param redirect_uri: The URL that Strava will redirect to after successful (or failed) authorization. :type redirect_uri: str ...
2.034898
2.765749
0.735749
return self.protocol.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=code)
def exchange_code_for_token(self, client_id, client_secret, code)
Exchange the temporary authorization code (returned with redirect from strava authorization URL) for a temporary access token and a refresh token (used to obtain the next access token later on). :param client_id: The numeric developer client id. :type client_id: int :param client_secre...
2.833885
3.466931
0.817405
return self.protocol.refresh_access_token(client_id=client_id, client_secret=client_secret, refresh_token=refresh_token)
def refresh_access_token(self, client_id, client_secret, refresh_token)
Exchange the temporary authorization code (returned with redirect from strava authorization URL) for a temporary access token and a refresh token (used to obtain the next access token later on). :param client_id: The numeric developer client id. :type client_id: int :param client_secre...
2.69734
3.119871
0.864568
if isinstance(activity_datetime, str): activity_datetime = arrow.get(activity_datetime).datetime assert isinstance(activity_datetime, datetime) if activity_datetime.tzinfo: activity_datetime = activity_datetime.astimezone(pytz.utc) return calendar.timegm...
def _utc_datetime_to_epoch(self, activity_datetime)
Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be considered to be UTC). :return: Epoch timestamp. :rtype: in...
2.128711
2.238888
0.950789
if before: before = self._utc_datetime_to_epoch(before) if after: after = self._utc_datetime_to_epoch(after) params = dict(before=before, after=after) result_fetcher = functools.partial(self.protocol.get, '/at...
def get_activities(self, before=None, after=None, limit=None)
Get activities for authenticated user sorted by newest first. http://strava.github.io/api/v3/activities/ :param before: Result will start with activities whose start date is before specified date. (UTC) :type before: datetime.datetime or str or None :param afte...
4.013159
3.346936
1.199054
if athlete_id is None: raw = self.protocol.get('/athlete') else: raise NotImplementedError("The /athletes/{id} endpoint was removed by Strava. " "See https://developers.strava.com/docs/january-2018-update/") # raw = sel...
def get_athlete(self, athlete_id=None)
Gets the specified athlete; if athlete_id is None then retrieves a detail-level representation of currently authenticated athlete; otherwise summary-level representation returned of athlete. http://strava.github.io/api/v3/athlete/#get-details http://strava.github.io/api/v3/athlete/#get...
4.792219
4.492564
1.0667
if athlete_id is None: result_fetcher = functools.partial(self.protocol.get, '/athlete/friends') else: raise NotImplementedError("The /athletes/{id}/friends endpoint was removed by Strava. " "See https://developers.strava.com/docs/j...
def get_athlete_friends(self, athlete_id=None, limit=None)
Gets friends for current (or specified) athlete. http://strava.github.io/api/v3/follow/#friends :param: athlete_id :type: athlete_id: int :param limit: Maximum number of athletes to return (default unlimited). :type limit: int :return: An iterator of :class:`stravalib...
4.249773
3.803138
1.117438
params = {'city': city, 'state': state, 'country': country, 'sex': sex} params = {k: v for (k, v) in params.items() if v is not None} if weight is not None: params['weight'] = float(weight) raw_athlete = self.pro...
def update_athlete(self, city=None, state=None, country=None, sex=None, weight=None)
Updates the properties of the authorized athlete. http://strava.github.io/api/v3/athlete/#update :param city: City the athlete lives in :param state: State the athlete lives in :param country: Country the athlete lives in :param sex: Sex of the athlete :param weight: We...
2.833462
3.039382
0.932249
result_fetcher = functools.partial(self.protocol.get, '/athletes/{id}/koms', id=athlete_id) return BatchedResultsIterator(entity=model.SegmentEffort, bind_client=self, ...
def get_athlete_koms(self, athlete_id, limit=None)
Gets Q/KOMs/CRs for specified athlete. KOMs are returned as `stravalib.model.SegmentEffort` objects. http://strava.github.io/api/v3/athlete/#koms :param athlete_id: The ID of the athlete. :type athlete_id: int :param limit: Maximum number of KOM segment efforts to return (def...
7.696207
5.345566
1.439737
if athlete_id is None: athlete_id = self.get_athlete().id raw = self.protocol.get('/athletes/{id}/stats', id=athlete_id) # TODO: Better error handling - this will return a 401 if this athlete # is not the authenticated athlete. return model.AthleteSta...
def get_athlete_stats(self, athlete_id=None)
Returns Statistics for the athlete. athlete_id must be the id of the authenticated athlete or left blank. If it is left blank two requests will be made - first to get the authenticated athlete's id and second to get the Stats. http://strava.github.io/api/v3/athlete/#stats :retu...
4.591566
4.327211
1.061091
club_structs = self.protocol.get('/athlete/clubs') return [model.Club.deserialize(raw, bind_client=self) for raw in club_structs]
def get_athlete_clubs(self)
List the clubs for the currently authenticated athlete. http://strava.github.io/api/v3/clubs/#get-athletes :return: A list of :class:`stravalib.model.Club` :rtype: :py:class:`list`
10.388772
10.995307
0.944837
raw = self.protocol.get("/clubs/{id}", id=club_id) return model.Club.deserialize(raw, bind_client=self)
def get_club(self, club_id)
Return a specific club object. http://strava.github.io/api/v3/clubs/#get-details :param club_id: The ID of the club to fetch. :type club_id: int :rtype: :class:`stravalib.model.Club`
9.976069
9.68963
1.029561
result_fetcher = functools.partial(self.protocol.get, '/clubs/{id}/members', id=club_id) return BatchedResultsIterator(entity=model.Athlete, bind_client=self, result_fetc...
def get_club_members(self, club_id, limit=None)
Gets the member objects for specified club ID. http://strava.github.io/api/v3/clubs/#get-members :param club_id: The numeric ID for the club. :type club_id: int :param limit: Maximum number of athletes to return. (default unlimited) :type limit: int :return: An iterat...
8.407222
6.389548
1.315777
result_fetcher = functools.partial(self.protocol.get, '/clubs/{id}/activities', id=club_id) return BatchedResultsIterator(entity=model.Activity, bind_client=self, result_...
def get_club_activities(self, club_id, limit=None)
Gets the activities associated with specified club. http://strava.github.io/api/v3/clubs/#get-activities :param club_id: The numeric ID for the club. :type club_id: int :param limit: Maximum number of activities to return. (default unlimited) :type limit: int :return:...
7.996587
6.731323
1.187967
raw = self.protocol.get('/activities/{id}', id=activity_id, include_all_efforts=include_all_efforts) return model.Activity.deserialize(raw, bind_client=self)
def get_activity(self, activity_id, include_all_efforts=False)
Gets specified activity. Will be detail-level if owned by authenticated user; otherwise summary-level. http://strava.github.io/api/v3/activities/#get-details :param activity_id: The ID of activity to fetch. :type activity_id: int :param inclue_all_efforts: Whether to include ...
4.852388
5.015071
0.967561