repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
latchset/jwcrypto | jwcrypto/jwt.py | JWT.deserialize | 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 indexed by the 'kid' header.
"""
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:
self.token.allowed_algs = self._algs
self.deserializelog = list()
# now deserialize and also decrypt/verify (or raise) if we
# have a key
if key is None:
self.token.deserialize(jwt, None)
elif isinstance(key, JWK):
self.token.deserialize(jwt, key)
self.deserializelog.append("Success")
elif isinstance(key, JWKSet):
self.token.deserialize(jwt, None)
if 'kid' in self.token.jose_header:
kid_key = key.get_key(self.token.jose_header['kid'])
if not kid_key:
raise JWTMissingKey('Key ID %s not in key set'
% self.token.jose_header['kid'])
self.token.deserialize(jwt, kid_key)
else:
for k in key:
try:
self.token.deserialize(jwt, k)
self.deserializelog.append("Success")
break
except Exception as e: # pylint: disable=broad-except
keyid = k.key_id
if keyid is None:
keyid = k.thumbprint()
self.deserializelog.append('Key [%s] failed: [%s]' % (
keyid, repr(e)))
continue
if "Success" not in self.deserializelog:
raise JWTMissingKey('No working key found in key set')
else:
raise ValueError("Unrecognized Key Type")
if key is not None:
self.header = self.token.jose_header
self.claims = self.token.payload.decode('utf-8')
self._check_provided_claims() | python | 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 indexed by the 'kid' header.
"""
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:
self.token.allowed_algs = self._algs
self.deserializelog = list()
# now deserialize and also decrypt/verify (or raise) if we
# have a key
if key is None:
self.token.deserialize(jwt, None)
elif isinstance(key, JWK):
self.token.deserialize(jwt, key)
self.deserializelog.append("Success")
elif isinstance(key, JWKSet):
self.token.deserialize(jwt, None)
if 'kid' in self.token.jose_header:
kid_key = key.get_key(self.token.jose_header['kid'])
if not kid_key:
raise JWTMissingKey('Key ID %s not in key set'
% self.token.jose_header['kid'])
self.token.deserialize(jwt, kid_key)
else:
for k in key:
try:
self.token.deserialize(jwt, k)
self.deserializelog.append("Success")
break
except Exception as e: # pylint: disable=broad-except
keyid = k.key_id
if keyid is None:
keyid = k.thumbprint()
self.deserializelog.append('Key [%s] failed: [%s]' % (
keyid, repr(e)))
continue
if "Success" not in self.deserializelog:
raise JWTMissingKey('No working key found in key set')
else:
raise ValueError("Unrecognized Key Type")
if key is not None:
self.header = self.token.jose_header
self.claims = self.token.payload.decode('utf-8')
self._check_provided_claims() | [
"def",
"deserialize",
"(",
"self",
",",
"jwt",
",",
"key",
"=",
"None",
")",
":",
"c",
"=",
"jwt",
".",
"count",
"(",
"'.'",
")",
"if",
"c",
"==",
"2",
":",
"self",
".",
"token",
"=",
"JWS",
"(",
")",
"elif",
"c",
"==",
"4",
":",
"self",
".... | 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 indexed by the 'kid' header. | [
"Deserialize",
"a",
"JWT",
"token",
"."
] | 961df898dc08f63fe3d900f2002618740bc66b4a | https://github.com/latchset/jwcrypto/blob/961df898dc08f63fe3d900f2002618740bc66b4a/jwcrypto/jwt.py#L444-L504 | train | 202,900 |
wkentaro/fcn | fcn/trainer.py | Trainer.validate | def validate(self, n_viz=9):
"""Validate current model using validation dataset.
Parameters
----------
n_viz: int
Number fo visualization.
Returns
-------
log: dict
Log values.
"""
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),
ncols=80, leave=False):
img, lbl_true = zip(*batch)
batch = map(datasets.transform_lsvrc2012_vgg16, batch)
with chainer.no_backprop_mode(), \
chainer.using_config('train', False):
in_vars = utils.batch_to_vars(batch, device=self.device)
loss = self.model(*in_vars)
losses.append(float(loss.data))
score = self.model.score
lbl_pred = chainer.functions.argmax(score, axis=1)
lbl_pred = chainer.cuda.to_cpu(lbl_pred.data)
for im, lt, lp in zip(img, lbl_true, lbl_pred):
lbl_trues.append(lt)
lbl_preds.append(lp)
if len(vizs) < n_viz:
viz = utils.visualize_segmentation(
lbl_pred=lp, lbl_true=lt,
img=im, n_class=self.model.n_class)
vizs.append(viz)
# save visualization
out_viz = osp.join(self.out, 'visualizations_valid',
'iter%08d.jpg' % self.iteration)
if not osp.exists(osp.dirname(out_viz)):
os.makedirs(osp.dirname(out_viz))
viz = utils.get_tile_image(vizs)
skimage.io.imsave(out_viz, viz)
# generate log
acc = utils.label_accuracy_score(
lbl_trues, lbl_preds, self.model.n_class)
self._write_log(**{
'epoch': self.epoch,
'iteration': self.iteration,
'elapsed_time': time.time() - self.stamp_start,
'valid/loss': np.mean(losses),
'valid/acc': acc[0],
'valid/acc_cls': acc[1],
'valid/mean_iu': acc[2],
'valid/fwavacc': acc[3],
})
self._save_model() | python | def validate(self, n_viz=9):
"""Validate current model using validation dataset.
Parameters
----------
n_viz: int
Number fo visualization.
Returns
-------
log: dict
Log values.
"""
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),
ncols=80, leave=False):
img, lbl_true = zip(*batch)
batch = map(datasets.transform_lsvrc2012_vgg16, batch)
with chainer.no_backprop_mode(), \
chainer.using_config('train', False):
in_vars = utils.batch_to_vars(batch, device=self.device)
loss = self.model(*in_vars)
losses.append(float(loss.data))
score = self.model.score
lbl_pred = chainer.functions.argmax(score, axis=1)
lbl_pred = chainer.cuda.to_cpu(lbl_pred.data)
for im, lt, lp in zip(img, lbl_true, lbl_pred):
lbl_trues.append(lt)
lbl_preds.append(lp)
if len(vizs) < n_viz:
viz = utils.visualize_segmentation(
lbl_pred=lp, lbl_true=lt,
img=im, n_class=self.model.n_class)
vizs.append(viz)
# save visualization
out_viz = osp.join(self.out, 'visualizations_valid',
'iter%08d.jpg' % self.iteration)
if not osp.exists(osp.dirname(out_viz)):
os.makedirs(osp.dirname(out_viz))
viz = utils.get_tile_image(vizs)
skimage.io.imsave(out_viz, viz)
# generate log
acc = utils.label_accuracy_score(
lbl_trues, lbl_preds, self.model.n_class)
self._write_log(**{
'epoch': self.epoch,
'iteration': self.iteration,
'elapsed_time': time.time() - self.stamp_start,
'valid/loss': np.mean(losses),
'valid/acc': acc[0],
'valid/acc_cls': acc[1],
'valid/mean_iu': acc[2],
'valid/fwavacc': acc[3],
})
self._save_model() | [
"def",
"validate",
"(",
"self",
",",
"n_viz",
"=",
"9",
")",
":",
"iter_valid",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"iter_valid",
")",
"losses",
",",
"lbl_trues",
",",
"lbl_preds",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"vizs",
"=",... | Validate current model using validation dataset.
Parameters
----------
n_viz: int
Number fo visualization.
Returns
-------
log: dict
Log values. | [
"Validate",
"current",
"model",
"using",
"validation",
"dataset",
"."
] | a29e167b67b11418a06566ad1ddbbc6949575e05 | https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/trainer.py#L91-L149 | train | 202,901 |
wkentaro/fcn | fcn/trainer.py | Trainer.train | def train(self):
"""Train the network using the training dataset.
Parameters
----------
None
Returns
-------
None
"""
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.iteration = iteration
############
# validate #
############
if self.interval_validate and \
self.iteration % self.interval_validate == 0:
self.validate()
#########
# train #
#########
batch = map(datasets.transform_lsvrc2012_vgg16, batch)
in_vars = utils.batch_to_vars(batch, device=self.device)
self.model.zerograds()
loss = self.model(*in_vars)
if loss is not None:
loss.backward()
self.optimizer.update()
lbl_true = zip(*batch)[1]
lbl_pred = chainer.functions.argmax(self.model.score, axis=1)
lbl_pred = chainer.cuda.to_cpu(lbl_pred.data)
acc = utils.label_accuracy_score(
lbl_true, lbl_pred, self.model.n_class)
self._write_log(**{
'epoch': self.epoch,
'iteration': self.iteration,
'elapsed_time': time.time() - self.stamp_start,
'train/loss': float(loss.data),
'train/acc': acc[0],
'train/acc_cls': acc[1],
'train/mean_iu': acc[2],
'train/fwavacc': acc[3],
})
if iteration >= self.max_iter:
self._save_model()
break | python | def train(self):
"""Train the network using the training dataset.
Parameters
----------
None
Returns
-------
None
"""
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.iteration = iteration
############
# validate #
############
if self.interval_validate and \
self.iteration % self.interval_validate == 0:
self.validate()
#########
# train #
#########
batch = map(datasets.transform_lsvrc2012_vgg16, batch)
in_vars = utils.batch_to_vars(batch, device=self.device)
self.model.zerograds()
loss = self.model(*in_vars)
if loss is not None:
loss.backward()
self.optimizer.update()
lbl_true = zip(*batch)[1]
lbl_pred = chainer.functions.argmax(self.model.score, axis=1)
lbl_pred = chainer.cuda.to_cpu(lbl_pred.data)
acc = utils.label_accuracy_score(
lbl_true, lbl_pred, self.model.n_class)
self._write_log(**{
'epoch': self.epoch,
'iteration': self.iteration,
'elapsed_time': time.time() - self.stamp_start,
'train/loss': float(loss.data),
'train/acc': acc[0],
'train/acc_cls': acc[1],
'train/mean_iu': acc[2],
'train/fwavacc': acc[3],
})
if iteration >= self.max_iter:
self._save_model()
break | [
"def",
"train",
"(",
"self",
")",
":",
"self",
".",
"stamp_start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"iteration",
",",
"batch",
"in",
"tqdm",
".",
"tqdm",
"(",
"enumerate",
"(",
"self",
".",
"iter_train",
")",
",",
"desc",
"=",
"'train'",
... | Train the network using the training dataset.
Parameters
----------
None
Returns
-------
None | [
"Train",
"the",
"network",
"using",
"the",
"training",
"dataset",
"."
] | a29e167b67b11418a06566ad1ddbbc6949575e05 | https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/trainer.py#L166-L223 | train | 202,902 |
wkentaro/fcn | fcn/utils.py | centerize | 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)
"""
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 = (dst_h - h) // 2
if w < dst_w:
pad_horizontal = (dst_w - w) // 2
centerized[pad_vertical:pad_vertical + h,
pad_horizontal:pad_horizontal + w] = src
return centerized | python | 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)
"""
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 = (dst_h - h) // 2
if w < dst_w:
pad_horizontal = (dst_w - w) // 2
centerized[pad_vertical:pad_vertical + h,
pad_horizontal:pad_horizontal + w] = src
return centerized | [
"def",
"centerize",
"(",
"src",
",",
"dst_shape",
",",
"margin_color",
"=",
"None",
")",
":",
"if",
"src",
".",
"shape",
"[",
":",
"2",
"]",
"==",
"dst_shape",
"[",
":",
"2",
"]",
":",
"return",
"src",
"centerized",
"=",
"np",
".",
"zeros",
"(",
... | Centerize image for specified image size
@param src: image to centerize
@param dst_shape: image shape (height, width) or (height, width, channel) | [
"Centerize",
"image",
"for",
"specified",
"image",
"size"
] | a29e167b67b11418a06566ad1ddbbc6949575e05 | https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/utils.py#L141-L161 | train | 202,903 |
wkentaro/fcn | fcn/utils.py | _tile_images | 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.
"""
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.zeros(
(one_height * y_num, one_width * x_num, n_channels),
dtype=np.uint8,
)
else:
concatenated_image = np.zeros(
(one_height * y_num, one_width * x_num), dtype=np.uint8)
for y in six.moves.range(y_num):
for x in six.moves.range(x_num):
i = x + y * x_num
if i >= len(imgs):
pass
else:
concatenated_image[y * one_height:(y + 1) * one_height,
x * one_width:(x + 1) * one_width] = imgs[i]
return concatenated_image | python | 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.
"""
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.zeros(
(one_height * y_num, one_width * x_num, n_channels),
dtype=np.uint8,
)
else:
concatenated_image = np.zeros(
(one_height * y_num, one_width * x_num), dtype=np.uint8)
for y in six.moves.range(y_num):
for x in six.moves.range(x_num):
i = x + y * x_num
if i >= len(imgs):
pass
else:
concatenated_image[y * one_height:(y + 1) * one_height,
x * one_width:(x + 1) * one_width] = imgs[i]
return concatenated_image | [
"def",
"_tile_images",
"(",
"imgs",
",",
"tile_shape",
",",
"concatenated_image",
")",
":",
"y_num",
",",
"x_num",
"=",
"tile_shape",
"one_width",
"=",
"imgs",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
"one_height",
"=",
"imgs",
"[",
"0",
"]",
".",
... | 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. | [
"Concatenate",
"images",
"whose",
"sizes",
"are",
"same",
"."
] | a29e167b67b11418a06566ad1ddbbc6949575e05 | https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/utils.py#L164-L194 | train | 202,904 |
wkentaro/fcn | fcn/utils.py | get_tile_image | 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
"""
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_shape(img_num):
x_num = 0
y_num = int(math.sqrt(img_num))
while x_num * y_num < img_num:
x_num += 1
return y_num, x_num
if tile_shape is None:
tile_shape = get_tile_shape(len(imgs))
# get max tile size to which each image should be resized
max_height, max_width = np.inf, np.inf
for img in imgs:
max_height = min([max_height, img.shape[0]])
max_width = min([max_width, img.shape[1]])
# resize and concatenate images
for i, img in enumerate(imgs):
h, w = img.shape[:2]
dtype = img.dtype
h_scale, w_scale = max_height / h, max_width / w
scale = min([h_scale, w_scale])
h, w = int(scale * h), int(scale * w)
img = resize(
image=img,
output_shape=(h, w),
mode='reflect',
preserve_range=True,
anti_aliasing=True,
).astype(dtype)
if len(img.shape) == 3:
img = centerize(img, (max_height, max_width, 3), margin_color)
else:
img = centerize(img, (max_height, max_width), margin_color)
imgs[i] = img
return _tile_images(imgs, tile_shape, result_img) | python | 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
"""
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_shape(img_num):
x_num = 0
y_num = int(math.sqrt(img_num))
while x_num * y_num < img_num:
x_num += 1
return y_num, x_num
if tile_shape is None:
tile_shape = get_tile_shape(len(imgs))
# get max tile size to which each image should be resized
max_height, max_width = np.inf, np.inf
for img in imgs:
max_height = min([max_height, img.shape[0]])
max_width = min([max_width, img.shape[1]])
# resize and concatenate images
for i, img in enumerate(imgs):
h, w = img.shape[:2]
dtype = img.dtype
h_scale, w_scale = max_height / h, max_width / w
scale = min([h_scale, w_scale])
h, w = int(scale * h), int(scale * w)
img = resize(
image=img,
output_shape=(h, w),
mode='reflect',
preserve_range=True,
anti_aliasing=True,
).astype(dtype)
if len(img.shape) == 3:
img = centerize(img, (max_height, max_width, 3), margin_color)
else:
img = centerize(img, (max_height, max_width), margin_color)
imgs[i] = img
return _tile_images(imgs, tile_shape, result_img) | [
"def",
"get_tile_image",
"(",
"imgs",
",",
"tile_shape",
"=",
"None",
",",
"result_img",
"=",
"None",
",",
"margin_color",
"=",
"None",
")",
":",
"def",
"resize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# anti_aliasing arg cannot be passed to s... | 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 | [
"Concatenate",
"images",
"whose",
"sizes",
"are",
"different",
"."
] | a29e167b67b11418a06566ad1ddbbc6949575e05 | https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/utils.py#L197-L246 | train | 202,905 |
wkentaro/fcn | fcn/utils.py | visualize_segmentation | 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 value.
Key or index is label_value and value is its name.
Returns
-------
img_array: ndarray
Visualized image.
"""
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.keys()))
if lbl_true is None and lbl_pred is None:
raise ValueError('lbl_true or lbl_pred must be not None.')
lbl_true = copy.deepcopy(lbl_true)
lbl_pred = copy.deepcopy(lbl_pred)
mask_unlabeled = None
viz_unlabeled = None
if lbl_true is not None:
mask_unlabeled = lbl_true == -1
lbl_true[mask_unlabeled] = 0
viz_unlabeled = (
np.random.random((lbl_true.shape[0], lbl_true.shape[1], 3)) * 255
).astype(np.uint8)
if lbl_pred is not None:
lbl_pred[mask_unlabeled] = 0
vizs = []
if lbl_true is not None:
viz_trues = [
img,
label2rgb(lbl_true, label_names=label_names, n_labels=n_class),
label2rgb(lbl_true, img, label_names=label_names,
n_labels=n_class),
]
viz_trues[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
viz_trues[2][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
vizs.append(get_tile_image(viz_trues, (1, 3)))
if lbl_pred is not None:
viz_preds = [
img,
label2rgb(lbl_pred, label_names=label_names, n_labels=n_class),
label2rgb(lbl_pred, img, label_names=label_names,
n_labels=n_class),
]
if mask_unlabeled is not None and viz_unlabeled is not None:
viz_preds[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
viz_preds[2][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
vizs.append(get_tile_image(viz_preds, (1, 3)))
if len(vizs) == 1:
return vizs[0]
elif len(vizs) == 2:
return get_tile_image(vizs, (2, 1))
else:
raise RuntimeError | python | 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 value.
Key or index is label_value and value is its name.
Returns
-------
img_array: ndarray
Visualized image.
"""
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.keys()))
if lbl_true is None and lbl_pred is None:
raise ValueError('lbl_true or lbl_pred must be not None.')
lbl_true = copy.deepcopy(lbl_true)
lbl_pred = copy.deepcopy(lbl_pred)
mask_unlabeled = None
viz_unlabeled = None
if lbl_true is not None:
mask_unlabeled = lbl_true == -1
lbl_true[mask_unlabeled] = 0
viz_unlabeled = (
np.random.random((lbl_true.shape[0], lbl_true.shape[1], 3)) * 255
).astype(np.uint8)
if lbl_pred is not None:
lbl_pred[mask_unlabeled] = 0
vizs = []
if lbl_true is not None:
viz_trues = [
img,
label2rgb(lbl_true, label_names=label_names, n_labels=n_class),
label2rgb(lbl_true, img, label_names=label_names,
n_labels=n_class),
]
viz_trues[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
viz_trues[2][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
vizs.append(get_tile_image(viz_trues, (1, 3)))
if lbl_pred is not None:
viz_preds = [
img,
label2rgb(lbl_pred, label_names=label_names, n_labels=n_class),
label2rgb(lbl_pred, img, label_names=label_names,
n_labels=n_class),
]
if mask_unlabeled is not None and viz_unlabeled is not None:
viz_preds[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
viz_preds[2][mask_unlabeled] = viz_unlabeled[mask_unlabeled]
vizs.append(get_tile_image(viz_preds, (1, 3)))
if len(vizs) == 1:
return vizs[0]
elif len(vizs) == 2:
return get_tile_image(vizs, (2, 1))
else:
raise RuntimeError | [
"def",
"visualize_segmentation",
"(",
"*",
"*",
"kwargs",
")",
":",
"img",
"=",
"kwargs",
".",
"pop",
"(",
"'img'",
",",
"None",
")",
"lbl_true",
"=",
"kwargs",
".",
"pop",
"(",
"'lbl_true'",
",",
"None",
")",
"lbl_pred",
"=",
"kwargs",
".",
"pop",
"... | 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 value.
Key or index is label_value and value is its name.
Returns
-------
img_array: ndarray
Visualized image. | [
"Visualize",
"segmentation",
"."
] | a29e167b67b11418a06566ad1ddbbc6949575e05 | https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/utils.py#L318-L396 | train | 202,906 |
Kentzo/git-archive-all | git_archive_all.py | GitArchiver.create | 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 whether create should do nothing but print what it would archive.
@type dry_run: bool
@param output_format: Determines format of the output archive. If None, format is determined from extension
of output_file_path.
@type output_format: str
"""
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 output_format in self.ZIPFILE_FORMATS:
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
if compresslevel is not None:
if sys.version_info > (3, 7):
archive = ZipFile(path.abspath(output_path), 'w', compresslevel=compresslevel)
else:
raise ValueError("Compression level for zip archives requires Python 3.7+")
else:
archive = ZipFile(path.abspath(output_path), 'w')
def add_file(file_path, arcname):
if not path.islink(file_path):
archive.write(file_path, arcname, ZIP_DEFLATED)
else:
i = ZipInfo(arcname)
i.create_system = 3
i.external_attr = 0xA1ED0000
archive.writestr(i, readlink(file_path))
elif output_format in self.TARFILE_FORMATS:
import tarfile
mode = self.TARFILE_FORMATS[output_format]
if compresslevel is not None:
try:
archive = tarfile.open(path.abspath(output_path), mode, compresslevel=compresslevel)
except TypeError:
raise ValueError("{0} cannot be compressed".format(output_format))
else:
archive = tarfile.open(path.abspath(output_path), mode)
def add_file(file_path, arcname):
archive.add(file_path, arcname)
else:
raise ValueError("unknown format: {0}".format(output_format))
def archiver(file_path, arcname):
self.LOG.debug("{0} => {1}".format(file_path, arcname))
add_file(file_path, arcname)
else:
archive = None
def archiver(file_path, arcname):
self.LOG.info("{0} => {1}".format(file_path, arcname))
self.archive_all_files(archiver)
if archive is not None:
archive.close() | python | 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 whether create should do nothing but print what it would archive.
@type dry_run: bool
@param output_format: Determines format of the output archive. If None, format is determined from extension
of output_file_path.
@type output_format: str
"""
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 output_format in self.ZIPFILE_FORMATS:
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
if compresslevel is not None:
if sys.version_info > (3, 7):
archive = ZipFile(path.abspath(output_path), 'w', compresslevel=compresslevel)
else:
raise ValueError("Compression level for zip archives requires Python 3.7+")
else:
archive = ZipFile(path.abspath(output_path), 'w')
def add_file(file_path, arcname):
if not path.islink(file_path):
archive.write(file_path, arcname, ZIP_DEFLATED)
else:
i = ZipInfo(arcname)
i.create_system = 3
i.external_attr = 0xA1ED0000
archive.writestr(i, readlink(file_path))
elif output_format in self.TARFILE_FORMATS:
import tarfile
mode = self.TARFILE_FORMATS[output_format]
if compresslevel is not None:
try:
archive = tarfile.open(path.abspath(output_path), mode, compresslevel=compresslevel)
except TypeError:
raise ValueError("{0} cannot be compressed".format(output_format))
else:
archive = tarfile.open(path.abspath(output_path), mode)
def add_file(file_path, arcname):
archive.add(file_path, arcname)
else:
raise ValueError("unknown format: {0}".format(output_format))
def archiver(file_path, arcname):
self.LOG.debug("{0} => {1}".format(file_path, arcname))
add_file(file_path, arcname)
else:
archive = None
def archiver(file_path, arcname):
self.LOG.info("{0} => {1}".format(file_path, arcname))
self.archive_all_files(archiver)
if archive is not None:
archive.close() | [
"def",
"create",
"(",
"self",
",",
"output_path",
",",
"dry_run",
"=",
"False",
",",
"output_format",
"=",
"None",
",",
"compresslevel",
"=",
"None",
")",
":",
"if",
"output_format",
"is",
"None",
":",
"file_name",
",",
"file_ext",
"=",
"path",
".",
"spl... | 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 whether create should do nothing but print what it would archive.
@type dry_run: bool
@param output_format: Determines format of the output archive. If None, format is determined from extension
of output_file_path.
@type output_format: str | [
"Create",
"the",
"archive",
"at",
"output_file_path",
"."
] | fed1f48f1287c84220be08d63181a2816bde7a64 | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L137-L209 | train | 202,907 |
Kentzo/git-archive-all | git_archive_all.py | GitArchiver.is_file_excluded | 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 False.
@rtype: bool
"""
next(self._check_attr_gens[repo_abspath])
attrs = self._check_attr_gens[repo_abspath].send(repo_file_path)
return attrs['export-ignore'] == 'set' | python | 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 False.
@rtype: bool
"""
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",
")",
":",
"next",
"(",
"self",
".",
"_check_attr_gens",
"[",
"repo_abspath",
"]",
")",
"attrs",
"=",
"self",
".",
"_check_attr_gens",
"[",
"repo_abspath",
"]",
".",
"send",
"... | 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 False.
@rtype: bool | [
"Checks",
"whether",
"file",
"at",
"a",
"given",
"path",
"is",
"excluded",
"."
] | fed1f48f1287c84220be08d63181a2816bde7a64 | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L211-L226 | train | 202,908 |
Kentzo/git-archive-all | git_archive_all.py | GitArchiver.archive_all_files | 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
"""
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)) | python | 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
"""
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",
")",
":",
"for",
"file_path",
"in",
"self",
".",
"extra",
":",
"archiver",
"(",
"path",
".",
"abspath",
"(",
"file_path",
")",
",",
"path",
".",
"join",
"(",
"self",
".",
"prefix",
",",
"file_pa... | 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 | [
"Archive",
"all",
"files",
"using",
"archiver",
"."
] | fed1f48f1287c84220be08d63181a2816bde7a64 | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L228-L240 | train | 202,909 |
Kentzo/git-archive-all | git_archive_all.py | GitArchiver.walk_git_files | 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_path: Path to the git submodule repository relative to main_repo_abspath.
@type repo_path: str
@return: Iterator to traverse files under git control relative to main_repo_abspath.
@rtype: Iterable
"""
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-files -z --cached --full-name --no-empty-directory',
repo_abspath
).split('\0')[:-1]
for repo_file_path in repo_file_paths:
repo_file_abspath = path.join(repo_abspath, repo_file_path) # absolute file path
main_repo_file_path = path.join(repo_path, repo_file_path) # relative to main_repo_abspath
# Only list symlinks and files.
if not path.islink(repo_file_abspath) and path.isdir(repo_file_abspath):
continue
if self.is_file_excluded(repo_abspath, repo_file_path):
continue
yield main_repo_file_path
if self.force_sub:
self.run_git_shell('git submodule init', repo_abspath)
self.run_git_shell('git submodule update', repo_abspath)
try:
repo_gitmodules_abspath = path.join(repo_abspath, ".gitmodules")
with open(repo_gitmodules_abspath) as f:
lines = f.readlines()
for l in lines:
m = re.match("^\\s*path\\s*=\\s*(.*)\\s*$", l)
if m:
repo_submodule_path = m.group(1) # relative to repo_path
main_repo_submodule_path = path.join(repo_path, repo_submodule_path) # relative to main_repo_abspath
if self.is_file_excluded(repo_abspath, repo_submodule_path):
continue
for main_repo_submodule_file_path in self.walk_git_files(main_repo_submodule_path):
repo_submodule_file_path = path.relpath(main_repo_submodule_file_path, repo_path) # relative to repo_path
if self.is_file_excluded(repo_abspath, repo_submodule_file_path):
continue
yield main_repo_submodule_file_path
except IOError:
pass
finally:
self._check_attr_gens[repo_abspath].close()
del self._check_attr_gens[repo_abspath] | python | 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_path: Path to the git submodule repository relative to main_repo_abspath.
@type repo_path: str
@return: Iterator to traverse files under git control relative to main_repo_abspath.
@rtype: Iterable
"""
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-files -z --cached --full-name --no-empty-directory',
repo_abspath
).split('\0')[:-1]
for repo_file_path in repo_file_paths:
repo_file_abspath = path.join(repo_abspath, repo_file_path) # absolute file path
main_repo_file_path = path.join(repo_path, repo_file_path) # relative to main_repo_abspath
# Only list symlinks and files.
if not path.islink(repo_file_abspath) and path.isdir(repo_file_abspath):
continue
if self.is_file_excluded(repo_abspath, repo_file_path):
continue
yield main_repo_file_path
if self.force_sub:
self.run_git_shell('git submodule init', repo_abspath)
self.run_git_shell('git submodule update', repo_abspath)
try:
repo_gitmodules_abspath = path.join(repo_abspath, ".gitmodules")
with open(repo_gitmodules_abspath) as f:
lines = f.readlines()
for l in lines:
m = re.match("^\\s*path\\s*=\\s*(.*)\\s*$", l)
if m:
repo_submodule_path = m.group(1) # relative to repo_path
main_repo_submodule_path = path.join(repo_path, repo_submodule_path) # relative to main_repo_abspath
if self.is_file_excluded(repo_abspath, repo_submodule_path):
continue
for main_repo_submodule_file_path in self.walk_git_files(main_repo_submodule_path):
repo_submodule_file_path = path.relpath(main_repo_submodule_file_path, repo_path) # relative to repo_path
if self.is_file_excluded(repo_abspath, repo_submodule_file_path):
continue
yield main_repo_submodule_file_path
except IOError:
pass
finally:
self._check_attr_gens[repo_abspath].close()
del self._check_attr_gens[repo_abspath] | [
"def",
"walk_git_files",
"(",
"self",
",",
"repo_path",
"=",
"''",
")",
":",
"repo_abspath",
"=",
"path",
".",
"join",
"(",
"self",
".",
"main_repo_abspath",
",",
"repo_path",
")",
"assert",
"repo_abspath",
"not",
"in",
"self",
".",
"_check_attr_gens",
"self... | 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_path: Path to the git submodule repository relative to main_repo_abspath.
@type repo_path: str
@return: Iterator to traverse files under git control relative to main_repo_abspath.
@rtype: Iterable | [
"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",... | fed1f48f1287c84220be08d63181a2816bde7a64 | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L242-L310 | train | 202,910 |
Kentzo/git-archive-all | git_archive_all.py | GitArchiver.check_attr | 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.
@type repo_abspath: str
@param attrs: Attributes to check.
@type attrs: [str]
@rtype: generator
"""
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):
process.stdin.write(repo_file_path.encode('utf-8') + b'\0')
process.stdin.flush()
# For every attribute check-attr will output: <path> NUL <attribute> NUL <info> NUL
path, attr, info = b'', b'', b''
nuls_count = 0
nuls_expected = 3 * len(attrs)
while nuls_count != nuls_expected:
b = process.stdout.read(1)
if b == b'' and process.poll() is not None:
raise RuntimeError("check-attr exited prematurely")
elif b == b'\0':
nuls_count += 1
if nuls_count % 3 == 0:
yield map(self.decode_git_output, (path, attr, info))
path, attr, info = b'', b'', b''
elif nuls_count % 3 == 0:
path += b
elif nuls_count % 3 == 1:
attr += b
elif nuls_count % 3 == 2:
info += b
def read_attrs_old(process, repo_file_path):
"""
Compatibility with versions 1.8.5 and below that do not recognize -z for output.
"""
process.stdin.write(repo_file_path.encode('utf-8') + b'\0')
process.stdin.flush()
# For every attribute check-attr will output: <path>: <attribute>: <info>\n
# where <path> is c-quoted
path, attr, info = b'', b'', b''
lines_count = 0
lines_expected = len(attrs)
while lines_count != lines_expected:
line = process.stdout.readline()
info_start = line.rfind(b': ')
if info_start == -1:
raise RuntimeError("unexpected output of check-attr: {0}".format(line))
attr_start = line.rfind(b': ', 0, info_start)
if attr_start == -1:
raise RuntimeError("unexpected output of check-attr: {0}".format(line))
info = line[info_start + 2:len(line) - 1] # trim leading ": " and trailing \n
attr = line[attr_start + 2:info_start] # trim leading ": "
path = line[:attr_start]
yield map(self.decode_git_output, (path, attr, info))
lines_count += 1
if not attrs:
return
process = make_process()
try:
while True:
repo_file_path = yield
repo_file_attrs = {}
if self.git_version is None or self.git_version > (1, 8, 5):
reader = read_attrs
else:
reader = read_attrs_old
for path, attr, value in reader(process, repo_file_path):
repo_file_attrs[attr] = value
yield repo_file_attrs
finally:
process.stdin.close()
process.wait() | python | 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.
@type repo_abspath: str
@param attrs: Attributes to check.
@type attrs: [str]
@rtype: generator
"""
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):
process.stdin.write(repo_file_path.encode('utf-8') + b'\0')
process.stdin.flush()
# For every attribute check-attr will output: <path> NUL <attribute> NUL <info> NUL
path, attr, info = b'', b'', b''
nuls_count = 0
nuls_expected = 3 * len(attrs)
while nuls_count != nuls_expected:
b = process.stdout.read(1)
if b == b'' and process.poll() is not None:
raise RuntimeError("check-attr exited prematurely")
elif b == b'\0':
nuls_count += 1
if nuls_count % 3 == 0:
yield map(self.decode_git_output, (path, attr, info))
path, attr, info = b'', b'', b''
elif nuls_count % 3 == 0:
path += b
elif nuls_count % 3 == 1:
attr += b
elif nuls_count % 3 == 2:
info += b
def read_attrs_old(process, repo_file_path):
"""
Compatibility with versions 1.8.5 and below that do not recognize -z for output.
"""
process.stdin.write(repo_file_path.encode('utf-8') + b'\0')
process.stdin.flush()
# For every attribute check-attr will output: <path>: <attribute>: <info>\n
# where <path> is c-quoted
path, attr, info = b'', b'', b''
lines_count = 0
lines_expected = len(attrs)
while lines_count != lines_expected:
line = process.stdout.readline()
info_start = line.rfind(b': ')
if info_start == -1:
raise RuntimeError("unexpected output of check-attr: {0}".format(line))
attr_start = line.rfind(b': ', 0, info_start)
if attr_start == -1:
raise RuntimeError("unexpected output of check-attr: {0}".format(line))
info = line[info_start + 2:len(line) - 1] # trim leading ": " and trailing \n
attr = line[attr_start + 2:info_start] # trim leading ": "
path = line[:attr_start]
yield map(self.decode_git_output, (path, attr, info))
lines_count += 1
if not attrs:
return
process = make_process()
try:
while True:
repo_file_path = yield
repo_file_attrs = {}
if self.git_version is None or self.git_version > (1, 8, 5):
reader = read_attrs
else:
reader = read_attrs_old
for path, attr, value in reader(process, repo_file_path):
repo_file_attrs[attr] = value
yield repo_file_attrs
finally:
process.stdin.close()
process.wait() | [
"def",
"check_attr",
"(",
"self",
",",
"repo_abspath",
",",
"attrs",
")",
":",
"def",
"make_process",
"(",
")",
":",
"env",
"=",
"dict",
"(",
"environ",
",",
"GIT_FLUSH",
"=",
"'1'",
")",
"cmd",
"=",
"'git check-attr --stdin -z {0}'",
".",
"format",
"(",
... | 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.
@type repo_abspath: str
@param attrs: Attributes to check.
@type attrs: [str]
@rtype: generator | [
"Generator",
"that",
"returns",
"attributes",
"for",
"given",
"paths",
"relative",
"to",
"repo_abspath",
"."
] | fed1f48f1287c84220be08d63181a2816bde7a64 | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L312-L414 | train | 202,911 |
Kentzo/git-archive-all | git_archive_all.py | GitArchiver.run_git_shell | 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 if return code of the command is non-zero.
"""
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)
else:
raise CalledProcessError(returncode=p.returncode, cmd=cmd)
return output | python | 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 if return code of the command is non-zero.
"""
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)
else:
raise CalledProcessError(returncode=p.returncode, cmd=cmd)
return output | [
"def",
"run_git_shell",
"(",
"cls",
",",
"cmd",
",",
"cwd",
"=",
"None",
")",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
",",
"cwd",
"=",
"cwd",
")",
"output",
",",
"_",
"=",
"p",
".",
"communicat... | 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 if return code of the command is non-zero. | [
"Runs",
"git",
"shell",
"command",
"reads",
"output",
"and",
"decodes",
"it",
"into",
"unicode",
"string",
"."
] | fed1f48f1287c84220be08d63181a2816bde7a64 | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L428-L453 | train | 202,912 |
Kentzo/git-archive-all | git_archive_all.py | GitArchiver.get_git_version | 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
"""
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 Git version \"%s\".", output)
return None
try:
return tuple(int(v) for v in version.split('.'))
except ValueError:
cls.LOG.warning("Unable to parse Git version \"%s\".", version)
return None | python | 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
"""
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 Git version \"%s\".", output)
return None
try:
return tuple(int(v) for v in version.split('.'))
except ValueError:
cls.LOG.warning("Unable to parse Git version \"%s\".", version)
return None | [
"def",
"get_git_version",
"(",
"cls",
")",
":",
"try",
":",
"output",
"=",
"cls",
".",
"run_git_shell",
"(",
"'git version'",
")",
"except",
"CalledProcessError",
":",
"cls",
".",
"LOG",
".",
"warning",
"(",
"\"Unable to get Git version.\"",
")",
"return",
"No... | Return version of git current shell points to.
If version cannot be parsed None is returned.
@rtype: tuple or None | [
"Return",
"version",
"of",
"git",
"current",
"shell",
"points",
"to",
"."
] | fed1f48f1287c84220be08d63181a2816bde7a64 | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L456-L480 | train | 202,913 |
theelous3/asks | asks/base_funcs.py | request | 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/overview-of-funcs-and-args.html
Returns:
Response (asks.Response): The Response object.
'''
c_interact = kwargs.pop('persist_cookies', None)
ssl_context = kwargs.pop('ssl_context', None)
async with Session(persist_cookies=c_interact, ssl_context=ssl_context) as s:
r = await s.request(method, url=uri, **kwargs)
return r | python | 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/overview-of-funcs-and-args.html
Returns:
Response (asks.Response): The Response object.
'''
c_interact = kwargs.pop('persist_cookies', None)
ssl_context = kwargs.pop('ssl_context', None)
async with Session(persist_cookies=c_interact, ssl_context=ssl_context) as s:
r = await s.request(method, url=uri, **kwargs)
return r | [
"async",
"def",
"request",
"(",
"method",
",",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"c_interact",
"=",
"kwargs",
".",
"pop",
"(",
"'persist_cookies'",
",",
"None",
")",
"ssl_context",
"=",
"kwargs",
".",
"pop",
"(",
"'ssl_context'",
",",
"None",
"... | 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/overview-of-funcs-and-args.html
Returns:
Response (asks.Response): The Response object. | [
"Base",
"function",
"for",
"one",
"time",
"http",
"requests",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/base_funcs.py#L14-L31 | train | 202,914 |
theelous3/asks | asks/request_object.py | RequestProcessor.make_request | async def make_request(self, redirect=False):
'''
Acts as the central hub for preparing requests to be sent, and
returning them upon completion. Generally just pokes through
self's attribs and makes decisions about what to do.
Returns:
sock: The socket to be returned to the calling session's
pool.
Response: The response object, after any redirects. If there were
redirects, the redirect responses will be stored in the final
response object's `.history`.
'''
h11_connection = h11.Connection(our_role=h11.CLIENT)
(self.scheme,
self.host,
self.path,
self.uri_parameters,
self.query,
_) = urlparse(self.uri)
if not redirect:
self.initial_scheme = self.scheme
self.initial_netloc = self.host
# leave default the host on 80 / 443
# otherwise use the base host with :port appended.
host = (self.host if (self.port == '80' or
self.port == '443')
else self.host.split(':')[0] + ':' + self.port)
# default header construction
asks_headers = c_i_dict([('Host', host),
('Connection', 'keep-alive'),
('Accept-Encoding', 'gzip, deflate'),
('Accept', '*/*'),
('Content-Length', '0'),
('User-Agent', 'python-asks/2.2.2')
])
# check for a CookieTracker object, and if it's there inject
# the relevant cookies in to the (next) request.
# What the fuck is this shit.
if self.persist_cookies is not None:
self.cookies.update(
self.persist_cookies.get_additional_cookies(
self.host, self.path))
# formulate path / query and intended extra querys for use in uri
self._build_path()
# handle building the request body, if any
body = ''
if any((self.data, self.files, self.json is not None)):
content_type, content_len, body = await self._formulate_body()
asks_headers['Content-Type'] = content_type
asks_headers['Content-Length'] = content_len
# add custom headers, if any
# note that custom headers take precedence
if self.headers is not None:
asks_headers.update(self.headers)
# add auth
if self.auth is not None:
asks_headers.update(await self._auth_handler_pre())
asks_headers.update(await self._auth_handler_post_get_auth())
# add cookies
if self.cookies:
cookie_str = ''
for k, v in self.cookies.items():
cookie_str += '{}={}; '.format(k, v)
asks_headers['Cookie'] = cookie_str[:-1]
# Construct h11 body object, if any body.
if body:
if not isinstance(body, bytes):
body = bytes(body, self.encoding)
asks_headers['Content-Length'] = str(len(body))
req_body = h11.Data(data=body)
else:
req_body = None
# Construct h11 request object.
req = h11.Request(method=self.method,
target=self.path,
headers=asks_headers.items())
# call i/o handling func
response_obj = await self._request_io(req, req_body, h11_connection)
# check to see if the final socket object is suitable to be returned
# to the calling session's connection pool.
# We don't want to return sockets that are of a difference schema or
# different top level domain, as they are less likely to be useful.
if redirect:
if not (self.scheme == self.initial_scheme and
self.host == self.initial_netloc):
self.sock._active = False
if self.streaming:
return None, response_obj
return self.sock, response_obj | python | async def make_request(self, redirect=False):
'''
Acts as the central hub for preparing requests to be sent, and
returning them upon completion. Generally just pokes through
self's attribs and makes decisions about what to do.
Returns:
sock: The socket to be returned to the calling session's
pool.
Response: The response object, after any redirects. If there were
redirects, the redirect responses will be stored in the final
response object's `.history`.
'''
h11_connection = h11.Connection(our_role=h11.CLIENT)
(self.scheme,
self.host,
self.path,
self.uri_parameters,
self.query,
_) = urlparse(self.uri)
if not redirect:
self.initial_scheme = self.scheme
self.initial_netloc = self.host
# leave default the host on 80 / 443
# otherwise use the base host with :port appended.
host = (self.host if (self.port == '80' or
self.port == '443')
else self.host.split(':')[0] + ':' + self.port)
# default header construction
asks_headers = c_i_dict([('Host', host),
('Connection', 'keep-alive'),
('Accept-Encoding', 'gzip, deflate'),
('Accept', '*/*'),
('Content-Length', '0'),
('User-Agent', 'python-asks/2.2.2')
])
# check for a CookieTracker object, and if it's there inject
# the relevant cookies in to the (next) request.
# What the fuck is this shit.
if self.persist_cookies is not None:
self.cookies.update(
self.persist_cookies.get_additional_cookies(
self.host, self.path))
# formulate path / query and intended extra querys for use in uri
self._build_path()
# handle building the request body, if any
body = ''
if any((self.data, self.files, self.json is not None)):
content_type, content_len, body = await self._formulate_body()
asks_headers['Content-Type'] = content_type
asks_headers['Content-Length'] = content_len
# add custom headers, if any
# note that custom headers take precedence
if self.headers is not None:
asks_headers.update(self.headers)
# add auth
if self.auth is not None:
asks_headers.update(await self._auth_handler_pre())
asks_headers.update(await self._auth_handler_post_get_auth())
# add cookies
if self.cookies:
cookie_str = ''
for k, v in self.cookies.items():
cookie_str += '{}={}; '.format(k, v)
asks_headers['Cookie'] = cookie_str[:-1]
# Construct h11 body object, if any body.
if body:
if not isinstance(body, bytes):
body = bytes(body, self.encoding)
asks_headers['Content-Length'] = str(len(body))
req_body = h11.Data(data=body)
else:
req_body = None
# Construct h11 request object.
req = h11.Request(method=self.method,
target=self.path,
headers=asks_headers.items())
# call i/o handling func
response_obj = await self._request_io(req, req_body, h11_connection)
# check to see if the final socket object is suitable to be returned
# to the calling session's connection pool.
# We don't want to return sockets that are of a difference schema or
# different top level domain, as they are less likely to be useful.
if redirect:
if not (self.scheme == self.initial_scheme and
self.host == self.initial_netloc):
self.sock._active = False
if self.streaming:
return None, response_obj
return self.sock, response_obj | [
"async",
"def",
"make_request",
"(",
"self",
",",
"redirect",
"=",
"False",
")",
":",
"h11_connection",
"=",
"h11",
".",
"Connection",
"(",
"our_role",
"=",
"h11",
".",
"CLIENT",
")",
"(",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
... | Acts as the central hub for preparing requests to be sent, and
returning them upon completion. Generally just pokes through
self's attribs and makes decisions about what to do.
Returns:
sock: The socket to be returned to the calling session's
pool.
Response: The response object, after any redirects. If there were
redirects, the redirect responses will be stored in the final
response object's `.history`. | [
"Acts",
"as",
"the",
"central",
"hub",
"for",
"preparing",
"requests",
"to",
"be",
"sent",
"and",
"returning",
"them",
"upon",
"completion",
".",
"Generally",
"just",
"pokes",
"through",
"self",
"s",
"attribs",
"and",
"makes",
"decisions",
"about",
"what",
"... | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L126-L230 | train | 202,915 |
theelous3/asks | asks/request_object.py | RequestProcessor._build_path | 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.
'''
if not self.path:
self.path = '/'
if self.uri_parameters:
self.path = self.path + ';' + requote_uri(self.uri_parameters)
if self.query:
self.path = (self.path + '?' + self.query)
if self.params:
try:
if self.query:
self.path = self.path + self._dict_to_query(
self.params, base_query=True)
else:
self.path = self.path + self._dict_to_query(self.params)
except AttributeError:
self.path = self.path + '?' + self.params
self.path = requote_uri(self.path)
self.req_url = urlunparse(
(self.scheme, self.host, (self.path or ''), '', '', '')) | python | 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.
'''
if not self.path:
self.path = '/'
if self.uri_parameters:
self.path = self.path + ';' + requote_uri(self.uri_parameters)
if self.query:
self.path = (self.path + '?' + self.query)
if self.params:
try:
if self.query:
self.path = self.path + self._dict_to_query(
self.params, base_query=True)
else:
self.path = self.path + self._dict_to_query(self.params)
except AttributeError:
self.path = self.path + '?' + self.params
self.path = requote_uri(self.path)
self.req_url = urlunparse(
(self.scheme, self.host, (self.path or ''), '', '', '')) | [
"def",
"_build_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"path",
":",
"self",
".",
"path",
"=",
"'/'",
"if",
"self",
".",
"uri_parameters",
":",
"self",
".",
"path",
"=",
"self",
".",
"path",
"+",
"';'",
"+",
"requote_uri",
"(",
"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. | [
"Constructs",
"the",
"actual",
"request",
"URL",
"with",
"accompanying",
"query",
"if",
"any",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L278-L309 | train | 202,916 |
theelous3/asks | asks/request_object.py | RequestProcessor._catch_response | 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 noted that in order to remain preformant, if the user
wishes to do any file IO it should use async files or risk long wait
times and risk connection issues server-side when using callbacks.
If a callback is used, the response's body will be None.
Returns:
The most recent response object.
'''
response = await self._recv_event(h11_connection)
resp_data = {'encoding': self.encoding,
'method': self.method,
'status_code': response.status_code,
'reason_phrase': str(response.reason, 'utf-8'),
'http_version': str(response.http_version, 'utf-8'),
'headers': c_i_dict(
[(str(name, 'utf-8'), str(value, 'utf-8'))
for name, value in response.headers]),
'body': b'',
'url': self.req_url
}
for header in response.headers:
if header[0] == b'set-cookie':
try:
resp_data['headers']['set-cookie'].append(str(header[1],
'utf-8'))
except (KeyError, AttributeError):
resp_data['headers']['set-cookie'] = [str(header[1],
'utf-8')]
# check whether we should receive body according to RFC 7230
# https://tools.ietf.org/html/rfc7230#section-3.3.3
get_body = False
try:
if int(resp_data['headers']['content-length']) > 0:
get_body = True
except KeyError:
try:
if 'chunked' in resp_data['headers']['transfer-encoding'].lower():
get_body = True
except KeyError:
if resp_data['headers'].get('connection', '').lower() == 'close':
get_body = True
if get_body:
if self.callback is not None:
endof = await self._body_callback(h11_connection)
elif self.stream:
if not ((self.scheme == self.initial_scheme and
self.host == self.initial_netloc) or
resp_data['headers']['connection'].lower() == 'close'):
self.sock._active = False
resp_data['body'] = StreamBody(
h11_connection,
self.sock,
resp_data['headers'].get('content-encoding', None),
resp_data['encoding'])
self.streaming = True
else:
while True:
data = await self._recv_event(h11_connection)
if isinstance(data, h11.Data):
resp_data['body'] += data.data
elif isinstance(data, h11.EndOfMessage):
break
else:
endof = await self._recv_event(h11_connection)
assert isinstance(endof, h11.EndOfMessage)
if self.streaming:
return StreamResponse(**resp_data)
return Response(**resp_data) | python | 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 noted that in order to remain preformant, if the user
wishes to do any file IO it should use async files or risk long wait
times and risk connection issues server-side when using callbacks.
If a callback is used, the response's body will be None.
Returns:
The most recent response object.
'''
response = await self._recv_event(h11_connection)
resp_data = {'encoding': self.encoding,
'method': self.method,
'status_code': response.status_code,
'reason_phrase': str(response.reason, 'utf-8'),
'http_version': str(response.http_version, 'utf-8'),
'headers': c_i_dict(
[(str(name, 'utf-8'), str(value, 'utf-8'))
for name, value in response.headers]),
'body': b'',
'url': self.req_url
}
for header in response.headers:
if header[0] == b'set-cookie':
try:
resp_data['headers']['set-cookie'].append(str(header[1],
'utf-8'))
except (KeyError, AttributeError):
resp_data['headers']['set-cookie'] = [str(header[1],
'utf-8')]
# check whether we should receive body according to RFC 7230
# https://tools.ietf.org/html/rfc7230#section-3.3.3
get_body = False
try:
if int(resp_data['headers']['content-length']) > 0:
get_body = True
except KeyError:
try:
if 'chunked' in resp_data['headers']['transfer-encoding'].lower():
get_body = True
except KeyError:
if resp_data['headers'].get('connection', '').lower() == 'close':
get_body = True
if get_body:
if self.callback is not None:
endof = await self._body_callback(h11_connection)
elif self.stream:
if not ((self.scheme == self.initial_scheme and
self.host == self.initial_netloc) or
resp_data['headers']['connection'].lower() == 'close'):
self.sock._active = False
resp_data['body'] = StreamBody(
h11_connection,
self.sock,
resp_data['headers'].get('content-encoding', None),
resp_data['encoding'])
self.streaming = True
else:
while True:
data = await self._recv_event(h11_connection)
if isinstance(data, h11.Data):
resp_data['body'] += data.data
elif isinstance(data, h11.EndOfMessage):
break
else:
endof = await self._recv_event(h11_connection)
assert isinstance(endof, h11.EndOfMessage)
if self.streaming:
return StreamResponse(**resp_data)
return Response(**resp_data) | [
"async",
"def",
"_catch_response",
"(",
"self",
",",
"h11_connection",
")",
":",
"response",
"=",
"await",
"self",
".",
"_recv_event",
"(",
"h11_connection",
")",
"resp_data",
"=",
"{",
"'encoding'",
":",
"self",
".",
"encoding",
",",
"'method'",
":",
"self"... | 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 noted that in order to remain preformant, if the user
wishes to do any file IO it should use async files or risk long wait
times and risk connection issues server-side when using callbacks.
If a callback is used, the response's body will be None.
Returns:
The most recent response object. | [
"Instantiates",
"the",
"parser",
"which",
"manages",
"incoming",
"data",
"first",
"getting",
"the",
"headers",
"storing",
"cookies",
"and",
"then",
"parsing",
"the",
"response",
"s",
"body",
"if",
"any",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L515-L606 | train | 202,917 |
theelous3/asks | asks/request_object.py | RequestProcessor._send | 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.
'''
await self.sock.send_all(h11_connection.send(request_bytes))
if body_bytes is not None:
await self.sock.send_all(h11_connection.send(body_bytes))
await self.sock.send_all(h11_connection.send(h11.EndOfMessage())) | python | 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.
'''
await self.sock.send_all(h11_connection.send(request_bytes))
if body_bytes is not None:
await self.sock.send_all(h11_connection.send(body_bytes))
await self.sock.send_all(h11_connection.send(h11.EndOfMessage())) | [
"async",
"def",
"_send",
"(",
"self",
",",
"request_bytes",
",",
"body_bytes",
",",
"h11_connection",
")",
":",
"await",
"self",
".",
"sock",
".",
"send_all",
"(",
"h11_connection",
".",
"send",
"(",
"request_bytes",
")",
")",
"if",
"body_bytes",
"is",
"no... | 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. | [
"Takes",
"a",
"package",
"and",
"body",
"combines",
"then",
"then",
"shoots",
"em",
"off",
"in",
"to",
"the",
"ether",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L616-L628 | train | 202,918 |
theelous3/asks | asks/request_object.py | RequestProcessor._location_auth_protect | 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 otherwise.
'''
netloc_sans_port = self.host.split(':')[0]
netloc_sans_port = netloc_sans_port.replace(
(re.match(_WWX_MATCH, netloc_sans_port)[0]), '')
base_domain = '.'.join(netloc_sans_port.split('.')[-2:])
l_scheme, l_netloc, _, _, _, _ = urlparse(location)
location_sans_port = l_netloc.split(':')[0]
location_sans_port = location_sans_port.replace(
(re.match(_WWX_MATCH, location_sans_port)[0]), '')
location_domain = '.'.join(location_sans_port.split('.')[-2:])
if base_domain == location_domain:
if l_scheme < self.scheme:
return False
else:
return True | python | 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 otherwise.
'''
netloc_sans_port = self.host.split(':')[0]
netloc_sans_port = netloc_sans_port.replace(
(re.match(_WWX_MATCH, netloc_sans_port)[0]), '')
base_domain = '.'.join(netloc_sans_port.split('.')[-2:])
l_scheme, l_netloc, _, _, _, _ = urlparse(location)
location_sans_port = l_netloc.split(':')[0]
location_sans_port = location_sans_port.replace(
(re.match(_WWX_MATCH, location_sans_port)[0]), '')
location_domain = '.'.join(location_sans_port.split('.')[-2:])
if base_domain == location_domain:
if l_scheme < self.scheme:
return False
else:
return True | [
"async",
"def",
"_location_auth_protect",
"(",
"self",
",",
"location",
")",
":",
"netloc_sans_port",
"=",
"self",
".",
"host",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"netloc_sans_port",
"=",
"netloc_sans_port",
".",
"replace",
"(",
"(",
"re",
".",
... | 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 otherwise. | [
"Checks",
"to",
"see",
"if",
"the",
"new",
"location",
"is",
"1",
".",
"The",
"same",
"top",
"level",
"domain",
"2",
".",
"As",
"or",
"more",
"secure",
"than",
"the",
"current",
"connection",
"type"
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L680-L708 | train | 202,919 |
theelous3/asks | asks/request_object.py | RequestProcessor._body_callback | 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.
'''
# pylint: disable=not-callable
while True:
next_event = await self._recv_event(h11_connection)
if isinstance(next_event, h11.Data):
await self.callback(next_event.data)
else:
return next_event | python | 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.
'''
# pylint: disable=not-callable
while True:
next_event = await self._recv_event(h11_connection)
if isinstance(next_event, h11.Data):
await self.callback(next_event.data)
else:
return next_event | [
"async",
"def",
"_body_callback",
"(",
"self",
",",
"h11_connection",
")",
":",
"# pylint: disable=not-callable",
"while",
"True",
":",
"next_event",
"=",
"await",
"self",
".",
"_recv_event",
"(",
"h11_connection",
")",
"if",
"isinstance",
"(",
"next_event",
",",
... | A callback func to be supplied if the user wants to do something
directly with the response body's stream. | [
"A",
"callback",
"func",
"to",
"be",
"supplied",
"if",
"the",
"user",
"wants",
"to",
"do",
"something",
"directly",
"with",
"the",
"response",
"body",
"s",
"stream",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L710-L721 | train | 202,920 |
theelous3/asks | asks/sessions.py | BaseSession._connect | async def _connect(self, host_loc):
'''
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 beyond scheme, host.' +
' Host should be top level only: ', path)
host, port = get_netloc_port(scheme, host)
if scheme == 'http':
return await self._open_connection_http(
(host, int(port))), port
else:
return await self._open_connection_https(
(host, int(port))), port | python | async def _connect(self, host_loc):
'''
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 beyond scheme, host.' +
' Host should be top level only: ', path)
host, port = get_netloc_port(scheme, host)
if scheme == 'http':
return await self._open_connection_http(
(host, int(port))), port
else:
return await self._open_connection_https(
(host, int(port))), port | [
"async",
"def",
"_connect",
"(",
"self",
",",
"host_loc",
")",
":",
"scheme",
",",
"host",
",",
"path",
",",
"parameters",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"host_loc",
")",
"if",
"parameters",
"or",
"query",
"or",
"fragment",
":",
"... | Simple enough stuff to figure out where we should connect, and creates
the appropriate connection. | [
"Simple",
"enough",
"stuff",
"to",
"figure",
"out",
"where",
"we",
"should",
"connect",
"and",
"creates",
"the",
"appropriate",
"connection",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/sessions.py#L82-L100 | train | 202,921 |
theelous3/asks | asks/sessions.py | BaseSession.request | async def request(self, method, url=None, *, path='', retries=1,
connection_timeout=60, **kwargs):
'''
This is the template for all of the `http method` methods for
the Session.
Args:
method (str): A http method, such as 'GET' or 'POST'.
url (str): The url the request should be made to.
path (str): An optional kw-arg for use in Session method calls,
for specifying a particular path. Usually to be used in
conjunction with the base_location/endpoint paradigm.
kwargs: Any number of the following:
data (dict or str): Info to be processed as a
body-bound query.
params (dict or str): Info to be processed as a
url-bound query.
headers (dict): User HTTP headers to be used in the
request.
encoding (str): The str representation of the codec to
process the request under.
json (dict): A dict to be formatted as json and sent in
the request body.
files (dict): A dict of `filename:filepath`s to be sent
as multipart.
cookies (dict): A dict of `name:value` cookies to be
passed in request.
callback (func): A callback function to be called on
each bytechunk of of the response body.
timeout (int or float): A numeric representation of the
longest time to wait on a complete response once a
request has been sent.
retries (int): The number of attempts to try against
connection errors.
max_redirects (int): The maximum number of redirects
allowed.
persist_cookies (True or None): Passing True
instantiates a CookieTracker object to manage the
return of cookies to the server under the relevant
domains.
auth (child of AuthBase): An object for handling auth
construction.
When you call something like Session.get() or asks.post(), you're
really calling a partial method that has the 'method' argument
pre-completed.
'''
timeout = kwargs.get('timeout', None)
req_headers = kwargs.pop('headers', None)
if self.headers is not None:
headers = copy(self.headers)
if req_headers is not None:
headers.update(req_headers)
req_headers = headers
async with self.sema:
if url is None:
url = self._make_url() + path
retry = False
sock = None
try:
sock = await timeout_manager(
connection_timeout, self._grab_connection, url)
port = sock.port
req_obj = RequestProcessor(
self,
method,
url,
port,
headers=req_headers,
encoding=self.encoding,
sock=sock,
persist_cookies=self._cookie_tracker,
**kwargs
)
try:
if timeout is None:
sock, r = await req_obj.make_request()
else:
sock, r = await timeout_manager(timeout, req_obj.make_request)
except BadHttpResponse:
if timeout is None:
sock, r = await req_obj.make_request()
else:
sock, r = await timeout_manager(timeout, req_obj.make_request)
if sock is not None:
try:
if r.headers['connection'].lower() == 'close':
sock._active = False
await sock.close()
except KeyError:
pass
await self.return_to_pool(sock)
# ConnectionErrors are special. They are the only kind of exception
# we ever want to suppress. All other exceptions are re-raised or
# raised through another exception.
except ConnectionError as e:
if retries > 0:
retry = True
retries -= 1
else:
raise e
except Exception as e:
if sock:
await self._handle_exception(e, sock)
raise
# any BaseException is considered unlawful murder, and
# Session.cleanup should be called to tidy up sockets.
except BaseException as e:
if sock:
await sock.close()
raise e
if retry:
return (await self.request(method,
url,
path=path,
retries=retries,
headers=headers,
**kwargs))
return r | python | async def request(self, method, url=None, *, path='', retries=1,
connection_timeout=60, **kwargs):
'''
This is the template for all of the `http method` methods for
the Session.
Args:
method (str): A http method, such as 'GET' or 'POST'.
url (str): The url the request should be made to.
path (str): An optional kw-arg for use in Session method calls,
for specifying a particular path. Usually to be used in
conjunction with the base_location/endpoint paradigm.
kwargs: Any number of the following:
data (dict or str): Info to be processed as a
body-bound query.
params (dict or str): Info to be processed as a
url-bound query.
headers (dict): User HTTP headers to be used in the
request.
encoding (str): The str representation of the codec to
process the request under.
json (dict): A dict to be formatted as json and sent in
the request body.
files (dict): A dict of `filename:filepath`s to be sent
as multipart.
cookies (dict): A dict of `name:value` cookies to be
passed in request.
callback (func): A callback function to be called on
each bytechunk of of the response body.
timeout (int or float): A numeric representation of the
longest time to wait on a complete response once a
request has been sent.
retries (int): The number of attempts to try against
connection errors.
max_redirects (int): The maximum number of redirects
allowed.
persist_cookies (True or None): Passing True
instantiates a CookieTracker object to manage the
return of cookies to the server under the relevant
domains.
auth (child of AuthBase): An object for handling auth
construction.
When you call something like Session.get() or asks.post(), you're
really calling a partial method that has the 'method' argument
pre-completed.
'''
timeout = kwargs.get('timeout', None)
req_headers = kwargs.pop('headers', None)
if self.headers is not None:
headers = copy(self.headers)
if req_headers is not None:
headers.update(req_headers)
req_headers = headers
async with self.sema:
if url is None:
url = self._make_url() + path
retry = False
sock = None
try:
sock = await timeout_manager(
connection_timeout, self._grab_connection, url)
port = sock.port
req_obj = RequestProcessor(
self,
method,
url,
port,
headers=req_headers,
encoding=self.encoding,
sock=sock,
persist_cookies=self._cookie_tracker,
**kwargs
)
try:
if timeout is None:
sock, r = await req_obj.make_request()
else:
sock, r = await timeout_manager(timeout, req_obj.make_request)
except BadHttpResponse:
if timeout is None:
sock, r = await req_obj.make_request()
else:
sock, r = await timeout_manager(timeout, req_obj.make_request)
if sock is not None:
try:
if r.headers['connection'].lower() == 'close':
sock._active = False
await sock.close()
except KeyError:
pass
await self.return_to_pool(sock)
# ConnectionErrors are special. They are the only kind of exception
# we ever want to suppress. All other exceptions are re-raised or
# raised through another exception.
except ConnectionError as e:
if retries > 0:
retry = True
retries -= 1
else:
raise e
except Exception as e:
if sock:
await self._handle_exception(e, sock)
raise
# any BaseException is considered unlawful murder, and
# Session.cleanup should be called to tidy up sockets.
except BaseException as e:
if sock:
await sock.close()
raise e
if retry:
return (await self.request(method,
url,
path=path,
retries=retries,
headers=headers,
**kwargs))
return r | [
"async",
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
"=",
"None",
",",
"*",
",",
"path",
"=",
"''",
",",
"retries",
"=",
"1",
",",
"connection_timeout",
"=",
"60",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"g... | This is the template for all of the `http method` methods for
the Session.
Args:
method (str): A http method, such as 'GET' or 'POST'.
url (str): The url the request should be made to.
path (str): An optional kw-arg for use in Session method calls,
for specifying a particular path. Usually to be used in
conjunction with the base_location/endpoint paradigm.
kwargs: Any number of the following:
data (dict or str): Info to be processed as a
body-bound query.
params (dict or str): Info to be processed as a
url-bound query.
headers (dict): User HTTP headers to be used in the
request.
encoding (str): The str representation of the codec to
process the request under.
json (dict): A dict to be formatted as json and sent in
the request body.
files (dict): A dict of `filename:filepath`s to be sent
as multipart.
cookies (dict): A dict of `name:value` cookies to be
passed in request.
callback (func): A callback function to be called on
each bytechunk of of the response body.
timeout (int or float): A numeric representation of the
longest time to wait on a complete response once a
request has been sent.
retries (int): The number of attempts to try against
connection errors.
max_redirects (int): The maximum number of redirects
allowed.
persist_cookies (True or None): Passing True
instantiates a CookieTracker object to manage the
return of cookies to the server under the relevant
domains.
auth (child of AuthBase): An object for handling auth
construction.
When you call something like Session.get() or asks.post(), you're
really calling a partial method that has the 'method' argument
pre-completed. | [
"This",
"is",
"the",
"template",
"for",
"all",
"of",
"the",
"http",
"method",
"methods",
"for",
"the",
"Session",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/sessions.py#L102-L232 | train | 202,922 |
theelous3/asks | asks/sessions.py | BaseSession._handle_exception | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"if",
"isinstance",
"(",
"e",
",",
"(",
"RemoteProtocolError",
",",
"AssertionError",
")",
")",
":",
"await",
"sock",
".",
"close",
"(",
")",
"raise",
"BadHttpResponse",
"... | 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. | [
"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"... | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/sessions.py#L244-L256 | train | 202,923 |
theelous3/asks | asks/sessions.py | Session._grab_connection | 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, register it as checked out, and return it.
Args:
url (str): breaks the url down and uses the top level location
info to see if we have any connections to the location already
lying around.
'''
scheme, host, _, _, _, _ = urlparse(url)
host_loc = urlunparse((scheme, host, '', '', '', ''))
sock = self._checkout_connection(host_loc)
if sock is None:
sock = await self._make_connection(host_loc)
return sock | python | 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, register it as checked out, and return it.
Args:
url (str): breaks the url down and uses the top level location
info to see if we have any connections to the location already
lying around.
'''
scheme, host, _, _, _, _ = urlparse(url)
host_loc = urlunparse((scheme, host, '', '', '', ''))
sock = self._checkout_connection(host_loc)
if sock is None:
sock = await self._make_connection(host_loc)
return sock | [
"async",
"def",
"_grab_connection",
"(",
"self",
",",
"url",
")",
":",
"scheme",
",",
"host",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
"=",
"urlparse",
"(",
"url",
")",
"host_loc",
"=",
"urlunparse",
"(",
"(",
"scheme",
",",
"host",
",",
"''",
","... | 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, register it as checked out, and return it.
Args:
url (str): breaks the url down and uses the top level location
info to see if we have any connections to the location already
lying around. | [
"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",... | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/sessions.py#L346-L369 | train | 202,924 |
theelous3/asks | asks/response_objects.py | Response.json | def json(self, **kwargs):
'''
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) | python | def json(self, **kwargs):
'''
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",
")",
":",
"body",
"=",
"self",
".",
"_decompress",
"(",
"self",
".",
"encoding",
")",
"return",
"_json",
".",
"loads",
"(",
"body",
",",
"*",
"*",
"kwargs",
")"
] | If the response's body is valid json, we load it as a python dict
and return it. | [
"If",
"the",
"response",
"s",
"body",
"is",
"valid",
"json",
"we",
"load",
"it",
"as",
"a",
"python",
"dict",
"and",
"return",
"it",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/response_objects.py#L76-L82 | train | 202,925 |
theelous3/asks | asks/response_objects.py | Response.raise_for_status | def raise_for_status(self):
'''
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('{} Server Error: {} for url: {}'.format(self.status_code, self.reason_phrase, self.url), self.status_code) | python | def raise_for_status(self):
'''
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('{} Server Error: {} for url: {}'.format(self.status_code, self.reason_phrase, self.url), self.status_code) | [
"def",
"raise_for_status",
"(",
"self",
")",
":",
"if",
"400",
"<=",
"self",
".",
"status_code",
"<",
"500",
":",
"raise",
"BadStatus",
"(",
"'{} Client Error: {} for url: {}'",
".",
"format",
"(",
"self",
".",
"status_code",
",",
"self",
".",
"reason_phrase",... | Raise BadStatus if one occurred. | [
"Raise",
"BadStatus",
"if",
"one",
"occurred",
"."
] | ea522ea971ecb031d488a6301dc2718516cadcd6 | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/response_objects.py#L84-L91 | train | 202,926 |
MicroPyramid/django-blog-it | django_blog_it/django_blog_it/views.py | recent_photos | def recent_photos(request):
''' 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, 'thumb': thumburl, 'is_image': True})
return render_to_response('dashboard/browse.html', {'files': imgs}) | python | def recent_photos(request):
''' 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, 'thumb': thumburl, 'is_image': True})
return render_to_response('dashboard/browse.html', {'files': imgs}) | [
"def",
"recent_photos",
"(",
"request",
")",
":",
"imgs",
"=",
"[",
"]",
"for",
"obj",
"in",
"Image_File",
".",
"objects",
".",
"filter",
"(",
"is_image",
"=",
"True",
")",
".",
"order_by",
"(",
"\"-date_created\"",
")",
":",
"upurl",
"=",
"\"/\"",
"+"... | returns all the images from the data base | [
"returns",
"all",
"the",
"images",
"from",
"the",
"data",
"base"
] | c18dd08e3ead8c932471547595e22e77e5858383 | https://github.com/MicroPyramid/django-blog-it/blob/c18dd08e3ead8c932471547595e22e77e5858383/django_blog_it/django_blog_it/views.py#L463-L472 | train | 202,927 |
hozn/stravalib | stravalib/attributes.py | ChoicesAttribute.marshal | 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.
"""
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))
else:
# Too many choices. We could return one possible choice (e.g. orig[0]).
raise NotImplementedError("Too many reverse choices {0} for value {1} for field {2}".format(orig, v, self)) | python | 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.
"""
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))
else:
# Too many choices. We could return one possible choice (e.g. orig[0]).
raise NotImplementedError("Too many reverse choices {0} for value {1} for field {2}".format(orig, v, self)) | [
"def",
"marshal",
"(",
"self",
",",
"v",
")",
":",
"if",
"v",
":",
"orig",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"choices",
"if",
"self",
".",
"choices",
"[",
"i",
"]",
"==",
"v",
"]",
"if",
"len",
"(",
"orig",
")",
"==",
"1",
":",
... | 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. | [
"Turn",
"this",
"value",
"into",
"API",
"format",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/attributes.py#L256-L274 | train | 202,928 |
hozn/stravalib | stravalib/attributes.py | ChoicesAttribute.unmarshal | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"try",
":",
"return",
"self",
".",
"choices",
"[",
"v",
"]",
"except",
"KeyError",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"No such choice {0} for field {1}.\"",
".",
"format",
"(",
"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. | [
"Convert",
"the",
"value",
"from",
"Strava",
"API",
"format",
"to",
"useful",
"python",
"representation",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/attributes.py#L276-L289 | train | 202,929 |
hozn/stravalib | stravalib/attributes.py | EntityAttribute.unmarshal | def unmarshal(self, value, bind_client=None):
"""
Cast the specified value to the entity type.
"""
#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):
for (k, v) in value.items():
if not hasattr(o.__class__, k):
self.log.warning("Unable to set attribute {0} on entity {1!r}".format(k, o))
else:
#self.log.debug("Setting attribute {0} on entity {1!r}".format(k, o))
setattr(o, k, v)
value = o
else:
raise Exception("Unable to unmarshall object {0!r}".format(value))
return value | python | def unmarshal(self, value, bind_client=None):
"""
Cast the specified value to the entity type.
"""
#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):
for (k, v) in value.items():
if not hasattr(o.__class__, k):
self.log.warning("Unable to set attribute {0} on entity {1!r}".format(k, o))
else:
#self.log.debug("Setting attribute {0} on entity {1!r}".format(k, o))
setattr(o, k, v)
value = o
else:
raise Exception("Unable to unmarshall object {0!r}".format(value))
return value | [
"def",
"unmarshal",
"(",
"self",
",",
"value",
",",
"bind_client",
"=",
"None",
")",
":",
"#self.log.debug(\"Unmarshall {0!r}: {1!r}\".format(self, value))",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"type",
")",
":",
"o",
"=",
"self",
".",
"t... | Cast the specified value to the entity type. | [
"Cast",
"the",
"specified",
"value",
"to",
"the",
"entity",
"type",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/attributes.py#L337-L357 | train | 202,930 |
hozn/stravalib | stravalib/attributes.py | EntityCollection.marshal | 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]]
"""
if values is not None:
return [super(EntityCollection, self).marshal(v) for v in values] | python | 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]]
"""
if values is not None:
return [super(EntityCollection, self).marshal(v) for v in values] | [
"def",
"marshal",
"(",
"self",
",",
"values",
")",
":",
"if",
"values",
"is",
"not",
"None",
":",
"return",
"[",
"super",
"(",
"EntityCollection",
",",
"self",
")",
".",
"marshal",
"(",
"v",
")",
"for",
"v",
"in",
"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]] | [
"Turn",
"a",
"list",
"of",
"entities",
"into",
"a",
"list",
"of",
"dictionaries",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/attributes.py#L362-L372 | train | 202,931 |
hozn/stravalib | stravalib/attributes.py | EntityCollection.unmarshal | def unmarshal(self, values, bind_client=None):
"""
Cast the list.
"""
if values is not None:
return [super(EntityCollection, self).unmarshal(v, bind_client=bind_client) for v in values] | python | def unmarshal(self, values, bind_client=None):
"""
Cast the list.
"""
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",
")",
":",
"if",
"values",
"is",
"not",
"None",
":",
"return",
"[",
"super",
"(",
"EntityCollection",
",",
"self",
")",
".",
"unmarshal",
"(",
"v",
",",
"bind_client",
"=",... | Cast the list. | [
"Cast",
"the",
"list",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/attributes.py#L374-L379 | train | 202,932 |
hozn/stravalib | stravalib/client.py | Client.authorization_url | 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
:param approval_prompt: Whether to prompt for approval even if approval already granted to app.
Choices are 'auto' or 'force'. (Default is 'auto')
:type approval_prompt: str
:param scope: The access scope required. Omit to imply "public".
Valid values are 'read', 'read_all', 'profile:read_all', 'profile:write', 'profile:read_all',
'activity:read_all', 'activity:write'
:type scope: str
:param state: An arbitrary variable that will be returned to your application in the redirect URI.
:type state: str
:return: The URL to use for authorization link.
:rtype: str
"""
return self.protocol.authorization_url(client_id=client_id,
redirect_uri=redirect_uri,
approval_prompt=approval_prompt,
scope=scope, state=state) | python | 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
:param approval_prompt: Whether to prompt for approval even if approval already granted to app.
Choices are 'auto' or 'force'. (Default is 'auto')
:type approval_prompt: str
:param scope: The access scope required. Omit to imply "public".
Valid values are 'read', 'read_all', 'profile:read_all', 'profile:write', 'profile:read_all',
'activity:read_all', 'activity:write'
:type scope: str
:param state: An arbitrary variable that will be returned to your application in the redirect URI.
:type state: str
:return: The URL to use for authorization link.
:rtype: str
"""
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",
")",
":",
"return",
"self",
".",
"protocol",
".",
"authorization_url",
"(",
"client_i... | 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
:param approval_prompt: Whether to prompt for approval even if approval already granted to app.
Choices are 'auto' or 'force'. (Default is 'auto')
:type approval_prompt: str
:param scope: The access scope required. Omit to imply "public".
Valid values are 'read', 'read_all', 'profile:read_all', 'profile:write', 'profile:read_all',
'activity:read_all', 'activity:write'
:type scope: str
:param state: An arbitrary variable that will be returned to your application in the redirect URI.
:type state: str
:return: The URL to use for authorization link.
:rtype: str | [
"Get",
"the",
"URL",
"needed",
"to",
"authorize",
"your",
"application",
"to",
"access",
"a",
"Strava",
"user",
"s",
"information",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L82-L111 | train | 202,933 |
hozn/stravalib | stravalib/client.py | Client.get_activities | 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 after: Result will start with activities whose start date is after
specified value. (UTC)
:type after: datetime.datetime or str or None
:param limit: How many maximum activities to return.
:type limit: int or None
:return: An iterator of :class:`stravalib.model.Activity` objects.
:rtype: :class:`BatchedResultsIterator`
"""
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,
'/athlete/activities',
**params)
return BatchedResultsIterator(entity=model.Activity,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | python | 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 after: Result will start with activities whose start date is after
specified value. (UTC)
:type after: datetime.datetime or str or None
:param limit: How many maximum activities to return.
:type limit: int or None
:return: An iterator of :class:`stravalib.model.Activity` objects.
:rtype: :class:`BatchedResultsIterator`
"""
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,
'/athlete/activities',
**params)
return BatchedResultsIterator(entity=model.Activity,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | [
"def",
"get_activities",
"(",
"self",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"before",
":",
"before",
"=",
"self",
".",
"_utc_datetime_to_epoch",
"(",
"before",
")",
"if",
"after",
":",
"after"... | 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 after: Result will start with activities whose start date is after
specified value. (UTC)
:type after: datetime.datetime or str or None
:param limit: How many maximum activities to return.
:type limit: int or None
:return: An iterator of :class:`stravalib.model.Activity` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Get",
"activities",
"for",
"authenticated",
"user",
"sorted",
"by",
"newest",
"first",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L183-L219 | train | 202,934 |
hozn/stravalib | stravalib/client.py | Client.get_athlete | 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-another-details
:return: The athlete model object.
:rtype: :class:`stravalib.model.Athlete`
"""
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 = self.protocol.get('/athletes/{athlete_id}', athlete_id=athlete_id)
return model.Athlete.deserialize(raw, bind_client=self) | python | 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-another-details
:return: The athlete model object.
:rtype: :class:`stravalib.model.Athlete`
"""
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 = self.protocol.get('/athletes/{athlete_id}', athlete_id=athlete_id)
return model.Athlete.deserialize(raw, bind_client=self) | [
"def",
"get_athlete",
"(",
"self",
",",
"athlete_id",
"=",
"None",
")",
":",
"if",
"athlete_id",
"is",
"None",
":",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/athlete'",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"The /athletes/... | 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-another-details
:return: The athlete model object.
:rtype: :class:`stravalib.model.Athlete` | [
"Gets",
"the",
"specified",
"athlete",
";",
"if",
"athlete_id",
"is",
"None",
"then",
"retrieves",
"a",
"detail",
"-",
"level",
"representation",
"of",
"currently",
"authenticated",
"athlete",
";",
"otherwise",
"summary",
"-",
"level",
"representation",
"returned"... | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L221-L242 | train | 202,935 |
hozn/stravalib | stravalib/client.py | Client.update_athlete | 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: Weight of the athlete in kg (float)
:return: The updated athlete
:rtype: :class:`stravalib.model.Athlete`
"""
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.protocol.put('/athlete', **params)
return model.Athlete.deserialize(raw_athlete, bind_client=self) | python | 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: Weight of the athlete in kg (float)
:return: The updated athlete
:rtype: :class:`stravalib.model.Athlete`
"""
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.protocol.put('/athlete', **params)
return model.Athlete.deserialize(raw_athlete, bind_client=self) | [
"def",
"update_athlete",
"(",
"self",
",",
"city",
"=",
"None",
",",
"state",
"=",
"None",
",",
"country",
"=",
"None",
",",
"sex",
"=",
"None",
",",
"weight",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'city'",
":",
"city",
",",
"'state'",
":",
... | 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: Weight of the athlete in kg (float)
:return: The updated athlete
:rtype: :class:`stravalib.model.Athlete` | [
"Updates",
"the",
"properties",
"of",
"the",
"authorized",
"athlete",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L273-L297 | train | 202,936 |
hozn/stravalib | stravalib/client.py | Client.get_athlete_stats | 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
:return: A model containing the Stats
:rtype: :py:class:`stravalib.model.AthleteStats`
"""
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.AthleteStats.deserialize(raw) | python | 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
:return: A model containing the Stats
:rtype: :py:class:`stravalib.model.AthleteStats`
"""
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.AthleteStats.deserialize(raw) | [
"def",
"get_athlete_stats",
"(",
"self",
",",
"athlete_id",
"=",
"None",
")",
":",
"if",
"athlete_id",
"is",
"None",
":",
"athlete_id",
"=",
"self",
".",
"get_athlete",
"(",
")",
".",
"id",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/athle... | 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
:return: A model containing the Stats
:rtype: :py:class:`stravalib.model.AthleteStats` | [
"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",
... | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L381-L400 | train | 202,937 |
hozn/stravalib | stravalib/client.py | Client.get_athlete_clubs | 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`
"""
club_structs = self.protocol.get('/athlete/clubs')
return [model.Club.deserialize(raw, bind_client=self) for raw in club_structs] | python | 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`
"""
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",
")",
":",
"club_structs",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/athlete/clubs'",
")",
"return",
"[",
"model",
".",
"Club",
".",
"deserialize",
"(",
"raw",
",",
"bind_client",
"=",
"self",
")",
"for",
"... | 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` | [
"List",
"the",
"clubs",
"for",
"the",
"currently",
"authenticated",
"athlete",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L402-L412 | train | 202,938 |
hozn/stravalib | stravalib/client.py | Client.get_club | 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`
"""
raw = self.protocol.get("/clubs/{id}", id=club_id)
return model.Club.deserialize(raw, bind_client=self) | python | 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`
"""
raw = self.protocol.get("/clubs/{id}", id=club_id)
return model.Club.deserialize(raw, bind_client=self) | [
"def",
"get_club",
"(",
"self",
",",
"club_id",
")",
":",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"\"/clubs/{id}\"",
",",
"id",
"=",
"club_id",
")",
"return",
"model",
".",
"Club",
".",
"deserialize",
"(",
"raw",
",",
"bind_client",
"=",
... | 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` | [
"Return",
"a",
"specific",
"club",
"object",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L434-L446 | train | 202,939 |
hozn/stravalib | stravalib/client.py | Client.get_club_members | 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 iterator of :class:`stravalib.model.Athlete` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/clubs/{id}/members',
id=club_id)
return BatchedResultsIterator(entity=model.Athlete, bind_client=self,
result_fetcher=result_fetcher, limit=limit) | python | 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 iterator of :class:`stravalib.model.Athlete` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/clubs/{id}/members',
id=club_id)
return BatchedResultsIterator(entity=model.Athlete, bind_client=self,
result_fetcher=result_fetcher, limit=limit) | [
"def",
"get_club_members",
"(",
"self",
",",
"club_id",
",",
"limit",
"=",
"None",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/clubs/{id}/members'",
",",
"id",
"=",
"club_id",
")",
"return... | 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 iterator of :class:`stravalib.model.Athlete` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"the",
"member",
"objects",
"for",
"specified",
"club",
"ID",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L448-L468 | train | 202,940 |
hozn/stravalib | stravalib/client.py | Client.get_club_activities | 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: An iterator of :class:`stravalib.model.Activity` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/clubs/{id}/activities',
id=club_id)
return BatchedResultsIterator(entity=model.Activity, bind_client=self,
result_fetcher=result_fetcher, limit=limit) | python | 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: An iterator of :class:`stravalib.model.Activity` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/clubs/{id}/activities',
id=club_id)
return BatchedResultsIterator(entity=model.Activity, bind_client=self,
result_fetcher=result_fetcher, limit=limit) | [
"def",
"get_club_activities",
"(",
"self",
",",
"club_id",
",",
"limit",
"=",
"None",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/clubs/{id}/activities'",
",",
"id",
"=",
"club_id",
")",
"... | 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: An iterator of :class:`stravalib.model.Activity` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"the",
"activities",
"associated",
"with",
"specified",
"club",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L470-L490 | train | 202,941 |
hozn/stravalib | stravalib/client.py | Client.get_activity | 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 segment efforts - only
available to the owner of the activty.
:type include_all_efforts: bool
:rtype: :class:`stravalib.model.Activity`
"""
raw = self.protocol.get('/activities/{id}', id=activity_id,
include_all_efforts=include_all_efforts)
return model.Activity.deserialize(raw, bind_client=self) | python | 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 segment efforts - only
available to the owner of the activty.
:type include_all_efforts: bool
:rtype: :class:`stravalib.model.Activity`
"""
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",
")",
":",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/activities/{id}'",
",",
"id",
"=",
"activity_id",
",",
"include_all_efforts",
"=",
"include_all... | 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 segment efforts - only
available to the owner of the activty.
:type include_all_efforts: bool
:rtype: :class:`stravalib.model.Activity` | [
"Gets",
"specified",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L492-L511 | train | 202,942 |
hozn/stravalib | stravalib/client.py | Client.create_activity | def create_activity(self, name, activity_type, start_date_local, elapsed_time,
description=None, distance=None):
"""
Create a new manual activity.
If you would like to create an activity from an uploaded GPS file, see the
:meth:`stravalib.client.Client.upload_activity` method instead.
:param name: The name of the activity.
:type name: str
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike, walk, nordicski,
alpineski, backcountryski, iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
:type activity_type: str
:param start_date_local: Local date/time of activity start. (TZ info will be ignored)
:type start_date_local: :class:`datetime.datetime` or string in ISO8601 format.
:param elapsed_time: The time in seconds or a :class:`datetime.timedelta` object.
:type elapsed_time: :class:`datetime.timedelta` or int (seconds)
:param description: The description for the activity.
:type description: str
:param distance: The distance in meters (float) or a :class:`units.quantity.Quantity` instance.
:type distance: :class:`units.quantity.Quantity` or float (meters)
"""
if isinstance(elapsed_time, timedelta):
elapsed_time = unithelper.timedelta_to_seconds(elapsed_time)
if isinstance(distance, Quantity):
distance = float(unithelper.meters(distance))
if isinstance(start_date_local, datetime):
start_date_local = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]:
raise ValueError("Invalid activity type: {0}. Possible values: {1!r}".format(activity_type, model.Activity.TYPES))
params = dict(name=name, type=activity_type, start_date_local=start_date_local,
elapsed_time=elapsed_time)
if description is not None:
params['description'] = description
if distance is not None:
params['distance'] = distance
raw_activity = self.protocol.post('/activities', **params)
return model.Activity.deserialize(raw_activity, bind_client=self) | python | def create_activity(self, name, activity_type, start_date_local, elapsed_time,
description=None, distance=None):
"""
Create a new manual activity.
If you would like to create an activity from an uploaded GPS file, see the
:meth:`stravalib.client.Client.upload_activity` method instead.
:param name: The name of the activity.
:type name: str
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike, walk, nordicski,
alpineski, backcountryski, iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
:type activity_type: str
:param start_date_local: Local date/time of activity start. (TZ info will be ignored)
:type start_date_local: :class:`datetime.datetime` or string in ISO8601 format.
:param elapsed_time: The time in seconds or a :class:`datetime.timedelta` object.
:type elapsed_time: :class:`datetime.timedelta` or int (seconds)
:param description: The description for the activity.
:type description: str
:param distance: The distance in meters (float) or a :class:`units.quantity.Quantity` instance.
:type distance: :class:`units.quantity.Quantity` or float (meters)
"""
if isinstance(elapsed_time, timedelta):
elapsed_time = unithelper.timedelta_to_seconds(elapsed_time)
if isinstance(distance, Quantity):
distance = float(unithelper.meters(distance))
if isinstance(start_date_local, datetime):
start_date_local = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]:
raise ValueError("Invalid activity type: {0}. Possible values: {1!r}".format(activity_type, model.Activity.TYPES))
params = dict(name=name, type=activity_type, start_date_local=start_date_local,
elapsed_time=elapsed_time)
if description is not None:
params['description'] = description
if distance is not None:
params['distance'] = distance
raw_activity = self.protocol.post('/activities', **params)
return model.Activity.deserialize(raw_activity, bind_client=self) | [
"def",
"create_activity",
"(",
"self",
",",
"name",
",",
"activity_type",
",",
"start_date_local",
",",
"elapsed_time",
",",
"description",
"=",
"None",
",",
"distance",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"elapsed_time",
",",
"timedelta",
")",
"... | Create a new manual activity.
If you would like to create an activity from an uploaded GPS file, see the
:meth:`stravalib.client.Client.upload_activity` method instead.
:param name: The name of the activity.
:type name: str
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike, walk, nordicski,
alpineski, backcountryski, iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
:type activity_type: str
:param start_date_local: Local date/time of activity start. (TZ info will be ignored)
:type start_date_local: :class:`datetime.datetime` or string in ISO8601 format.
:param elapsed_time: The time in seconds or a :class:`datetime.timedelta` object.
:type elapsed_time: :class:`datetime.timedelta` or int (seconds)
:param description: The description for the activity.
:type description: str
:param distance: The distance in meters (float) or a :class:`units.quantity.Quantity` instance.
:type distance: :class:`units.quantity.Quantity` or float (meters) | [
"Create",
"a",
"new",
"manual",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L533-L585 | train | 202,943 |
hozn/stravalib | stravalib/client.py | Client.update_activity | def update_activity(self, activity_id, name=None, activity_type=None,
private=None, commute=None, trainer=None, gear_id=None,
description=None,device_name=None):
"""
Updates the properties of a specific activity.
http://strava.github.io/api/v3/activities/#put-updates
:param activity_id: The ID of the activity to update.
:type activity_id: int
:param name: The name of the activity.
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike,
walk, nordicski, alpineski, backcountryski,
iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
:param private: Whether the activity is private.
:param commute: Whether the activity is a commute.
:param trainer: Whether this is a trainer activity.
:param gear_id: Alpha-numeric ID of gear (bike, shoes) used on this activity.
:param description: Description for the activity.
:param device_name: Device name for the activity
:return: The updated activity.
:rtype: :class:`stravalib.model.Activity`
"""
# Convert the kwargs into a params dict
params = {}
if name is not None:
params['name'] = name
if activity_type is not None:
if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]:
raise ValueError("Invalid activity type: {0}. Possible values: {1!r}".format(activity_type, model.Activity.TYPES))
params['type'] = activity_type
if private is not None:
params['private'] = int(private)
if commute is not None:
params['commute'] = int(commute)
if trainer is not None:
params['trainer'] = int(trainer)
if gear_id is not None:
params['gear_id'] = gear_id
if description is not None:
params['description'] = description
if device_name is not None:
params['device_name'] = device_name
raw_activity = self.protocol.put('/activities/{activity_id}', activity_id=activity_id, **params)
return model.Activity.deserialize(raw_activity, bind_client=self) | python | def update_activity(self, activity_id, name=None, activity_type=None,
private=None, commute=None, trainer=None, gear_id=None,
description=None,device_name=None):
"""
Updates the properties of a specific activity.
http://strava.github.io/api/v3/activities/#put-updates
:param activity_id: The ID of the activity to update.
:type activity_id: int
:param name: The name of the activity.
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike,
walk, nordicski, alpineski, backcountryski,
iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
:param private: Whether the activity is private.
:param commute: Whether the activity is a commute.
:param trainer: Whether this is a trainer activity.
:param gear_id: Alpha-numeric ID of gear (bike, shoes) used on this activity.
:param description: Description for the activity.
:param device_name: Device name for the activity
:return: The updated activity.
:rtype: :class:`stravalib.model.Activity`
"""
# Convert the kwargs into a params dict
params = {}
if name is not None:
params['name'] = name
if activity_type is not None:
if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]:
raise ValueError("Invalid activity type: {0}. Possible values: {1!r}".format(activity_type, model.Activity.TYPES))
params['type'] = activity_type
if private is not None:
params['private'] = int(private)
if commute is not None:
params['commute'] = int(commute)
if trainer is not None:
params['trainer'] = int(trainer)
if gear_id is not None:
params['gear_id'] = gear_id
if description is not None:
params['description'] = description
if device_name is not None:
params['device_name'] = device_name
raw_activity = self.protocol.put('/activities/{activity_id}', activity_id=activity_id, **params)
return model.Activity.deserialize(raw_activity, bind_client=self) | [
"def",
"update_activity",
"(",
"self",
",",
"activity_id",
",",
"name",
"=",
"None",
",",
"activity_type",
"=",
"None",
",",
"private",
"=",
"None",
",",
"commute",
"=",
"None",
",",
"trainer",
"=",
"None",
",",
"gear_id",
"=",
"None",
",",
"description"... | Updates the properties of a specific activity.
http://strava.github.io/api/v3/activities/#put-updates
:param activity_id: The ID of the activity to update.
:type activity_id: int
:param name: The name of the activity.
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike,
walk, nordicski, alpineski, backcountryski,
iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
:param private: Whether the activity is private.
:param commute: Whether the activity is a commute.
:param trainer: Whether this is a trainer activity.
:param gear_id: Alpha-numeric ID of gear (bike, shoes) used on this activity.
:param description: Description for the activity.
:param device_name: Device name for the activity
:return: The updated activity.
:rtype: :class:`stravalib.model.Activity` | [
"Updates",
"the",
"properties",
"of",
"a",
"specific",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L587-L646 | train | 202,944 |
hozn/stravalib | stravalib/client.py | Client.get_activity_zones | def get_activity_zones(self, activity_id):
"""
Gets zones for activity.
Requires premium account.
http://strava.github.io/api/v3/activities/#zones
:param activity_id: The activity for which to zones.
:type activity_id: int
:return: An list of :class:`stravalib.model.ActivityComment` objects.
:rtype: :py:class:`list`
"""
zones = self.protocol.get('/activities/{id}/zones', id=activity_id)
# We use a factory to give us the correct zone based on type.
return [model.BaseActivityZone.deserialize(z, bind_client=self) for z in zones] | python | def get_activity_zones(self, activity_id):
"""
Gets zones for activity.
Requires premium account.
http://strava.github.io/api/v3/activities/#zones
:param activity_id: The activity for which to zones.
:type activity_id: int
:return: An list of :class:`stravalib.model.ActivityComment` objects.
:rtype: :py:class:`list`
"""
zones = self.protocol.get('/activities/{id}/zones', id=activity_id)
# We use a factory to give us the correct zone based on type.
return [model.BaseActivityZone.deserialize(z, bind_client=self) for z in zones] | [
"def",
"get_activity_zones",
"(",
"self",
",",
"activity_id",
")",
":",
"zones",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/activities/{id}/zones'",
",",
"id",
"=",
"activity_id",
")",
"# We use a factory to give us the correct zone based on type.",
"return",
"... | Gets zones for activity.
Requires premium account.
http://strava.github.io/api/v3/activities/#zones
:param activity_id: The activity for which to zones.
:type activity_id: int
:return: An list of :class:`stravalib.model.ActivityComment` objects.
:rtype: :py:class:`list` | [
"Gets",
"zones",
"for",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L724-L740 | train | 202,945 |
hozn/stravalib | stravalib/client.py | Client.get_activity_comments | def get_activity_comments(self, activity_id, markdown=False, limit=None):
"""
Gets the comments for an activity.
http://strava.github.io/api/v3/comments/#list
:param activity_id: The activity for which to fetch comments.
:type activity_id: int
:param markdown: Whether to include markdown in comments (default is false/filterout).
:type markdown: bool
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityComment` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/comments',
id=activity_id, markdown=int(markdown))
return BatchedResultsIterator(entity=model.ActivityComment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | python | def get_activity_comments(self, activity_id, markdown=False, limit=None):
"""
Gets the comments for an activity.
http://strava.github.io/api/v3/comments/#list
:param activity_id: The activity for which to fetch comments.
:type activity_id: int
:param markdown: Whether to include markdown in comments (default is false/filterout).
:type markdown: bool
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityComment` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/comments',
id=activity_id, markdown=int(markdown))
return BatchedResultsIterator(entity=model.ActivityComment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | [
"def",
"get_activity_comments",
"(",
"self",
",",
"activity_id",
",",
"markdown",
"=",
"False",
",",
"limit",
"=",
"None",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/activities/{id}/comments'... | Gets the comments for an activity.
http://strava.github.io/api/v3/comments/#list
:param activity_id: The activity for which to fetch comments.
:type activity_id: int
:param markdown: Whether to include markdown in comments (default is false/filterout).
:type markdown: bool
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityComment` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"the",
"comments",
"for",
"an",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L742-L766 | train | 202,946 |
hozn/stravalib | stravalib/client.py | Client.get_activity_kudos | def get_activity_kudos(self, activity_id, limit=None):
"""
Gets the kudos for an activity.
http://strava.github.io/api/v3/kudos/#list
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityKudos` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/kudos',
id=activity_id)
return BatchedResultsIterator(entity=model.ActivityKudos,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | python | def get_activity_kudos(self, activity_id, limit=None):
"""
Gets the kudos for an activity.
http://strava.github.io/api/v3/kudos/#list
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityKudos` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/kudos',
id=activity_id)
return BatchedResultsIterator(entity=model.ActivityKudos,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | [
"def",
"get_activity_kudos",
"(",
"self",
",",
"activity_id",
",",
"limit",
"=",
"None",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/activities/{id}/kudos'",
",",
"id",
"=",
"activity_id",
"... | Gets the kudos for an activity.
http://strava.github.io/api/v3/kudos/#list
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityKudos` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"the",
"kudos",
"for",
"an",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L768-L790 | train | 202,947 |
hozn/stravalib | stravalib/client.py | Client.get_activity_photos | def get_activity_photos(self, activity_id, size=None, only_instagram=False):
"""
Gets the photos from an activity.
http://strava.github.io/api/v3/photos/
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param size: the requested size of the activity's photos. URLs for the photos will be returned that best match
the requested size. If not included, the smallest size is returned
:type size: int
:param only_instagram: Parameter to preserve legacy behavior of only returning Instagram photos.
:type only_instagram: bool
:return: An iterator of :class:`stravalib.model.ActivityPhoto` objects.
:rtype: :class:`BatchedResultsIterator`
"""
params = {}
if not only_instagram:
params['photo_sources'] = 'true'
if size is not None:
params['size'] = size
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/photos',
id=activity_id, **params)
return BatchedResultsIterator(entity=model.ActivityPhoto,
bind_client=self,
result_fetcher=result_fetcher) | python | def get_activity_photos(self, activity_id, size=None, only_instagram=False):
"""
Gets the photos from an activity.
http://strava.github.io/api/v3/photos/
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param size: the requested size of the activity's photos. URLs for the photos will be returned that best match
the requested size. If not included, the smallest size is returned
:type size: int
:param only_instagram: Parameter to preserve legacy behavior of only returning Instagram photos.
:type only_instagram: bool
:return: An iterator of :class:`stravalib.model.ActivityPhoto` objects.
:rtype: :class:`BatchedResultsIterator`
"""
params = {}
if not only_instagram:
params['photo_sources'] = 'true'
if size is not None:
params['size'] = size
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/photos',
id=activity_id, **params)
return BatchedResultsIterator(entity=model.ActivityPhoto,
bind_client=self,
result_fetcher=result_fetcher) | [
"def",
"get_activity_photos",
"(",
"self",
",",
"activity_id",
",",
"size",
"=",
"None",
",",
"only_instagram",
"=",
"False",
")",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"only_instagram",
":",
"params",
"[",
"'photo_sources'",
"]",
"=",
"'true'",
"if",... | Gets the photos from an activity.
http://strava.github.io/api/v3/photos/
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param size: the requested size of the activity's photos. URLs for the photos will be returned that best match
the requested size. If not included, the smallest size is returned
:type size: int
:param only_instagram: Parameter to preserve legacy behavior of only returning Instagram photos.
:type only_instagram: bool
:return: An iterator of :class:`stravalib.model.ActivityPhoto` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"the",
"photos",
"from",
"an",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L792-L825 | train | 202,948 |
hozn/stravalib | stravalib/client.py | Client.get_activity_laps | def get_activity_laps(self, activity_id):
"""
Gets the laps from an activity.
http://strava.github.io/api/v3/activities/#laps
:param activity_id: The activity for which to fetch laps.
:type activity_id: int
:return: An iterator of :class:`stravalib.model.ActivityLaps` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/laps',
id=activity_id)
return BatchedResultsIterator(entity=model.ActivityLap,
bind_client=self,
result_fetcher=result_fetcher) | python | def get_activity_laps(self, activity_id):
"""
Gets the laps from an activity.
http://strava.github.io/api/v3/activities/#laps
:param activity_id: The activity for which to fetch laps.
:type activity_id: int
:return: An iterator of :class:`stravalib.model.ActivityLaps` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/laps',
id=activity_id)
return BatchedResultsIterator(entity=model.ActivityLap,
bind_client=self,
result_fetcher=result_fetcher) | [
"def",
"get_activity_laps",
"(",
"self",
",",
"activity_id",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/activities/{id}/laps'",
",",
"id",
"=",
"activity_id",
")",
"return",
"BatchedResultsIter... | Gets the laps from an activity.
http://strava.github.io/api/v3/activities/#laps
:param activity_id: The activity for which to fetch laps.
:type activity_id: int
:return: An iterator of :class:`stravalib.model.ActivityLaps` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"the",
"laps",
"from",
"an",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L827-L845 | train | 202,949 |
hozn/stravalib | stravalib/client.py | Client.get_gear | def get_gear(self, gear_id):
"""
Get details for an item of gear.
http://strava.github.io/api/v3/gear/#show
:param gear_id: The gear id.
:type gear_id: str
:return: The Bike or Shoe subclass object.
:rtype: :class:`stravalib.model.Gear`
"""
return model.Gear.deserialize(self.protocol.get('/gear/{id}', id=gear_id)) | python | def get_gear(self, gear_id):
"""
Get details for an item of gear.
http://strava.github.io/api/v3/gear/#show
:param gear_id: The gear id.
:type gear_id: str
:return: The Bike or Shoe subclass object.
:rtype: :class:`stravalib.model.Gear`
"""
return model.Gear.deserialize(self.protocol.get('/gear/{id}', id=gear_id)) | [
"def",
"get_gear",
"(",
"self",
",",
"gear_id",
")",
":",
"return",
"model",
".",
"Gear",
".",
"deserialize",
"(",
"self",
".",
"protocol",
".",
"get",
"(",
"'/gear/{id}'",
",",
"id",
"=",
"gear_id",
")",
")"
] | Get details for an item of gear.
http://strava.github.io/api/v3/gear/#show
:param gear_id: The gear id.
:type gear_id: str
:return: The Bike or Shoe subclass object.
:rtype: :class:`stravalib.model.Gear` | [
"Get",
"details",
"for",
"an",
"item",
"of",
"gear",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L871-L883 | train | 202,950 |
hozn/stravalib | stravalib/client.py | Client.get_segment_effort | def get_segment_effort(self, effort_id):
"""
Return a specific segment effort by ID.
http://strava.github.io/api/v3/efforts/#retrieve
:param effort_id: The id of associated effort to fetch.
:type effort_id: int
:return: The specified effort on a segment.
:rtype: :class:`stravalib.model.SegmentEffort`
"""
return model.SegmentEffort.deserialize(self.protocol.get('/segment_efforts/{id}',
id=effort_id)) | python | def get_segment_effort(self, effort_id):
"""
Return a specific segment effort by ID.
http://strava.github.io/api/v3/efforts/#retrieve
:param effort_id: The id of associated effort to fetch.
:type effort_id: int
:return: The specified effort on a segment.
:rtype: :class:`stravalib.model.SegmentEffort`
"""
return model.SegmentEffort.deserialize(self.protocol.get('/segment_efforts/{id}',
id=effort_id)) | [
"def",
"get_segment_effort",
"(",
"self",
",",
"effort_id",
")",
":",
"return",
"model",
".",
"SegmentEffort",
".",
"deserialize",
"(",
"self",
".",
"protocol",
".",
"get",
"(",
"'/segment_efforts/{id}'",
",",
"id",
"=",
"effort_id",
")",
")"
] | Return a specific segment effort by ID.
http://strava.github.io/api/v3/efforts/#retrieve
:param effort_id: The id of associated effort to fetch.
:type effort_id: int
:return: The specified effort on a segment.
:rtype: :class:`stravalib.model.SegmentEffort` | [
"Return",
"a",
"specific",
"segment",
"effort",
"by",
"ID",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L885-L898 | train | 202,951 |
hozn/stravalib | stravalib/client.py | Client.get_segment | def get_segment(self, segment_id):
"""
Gets a specific segment by ID.
http://strava.github.io/api/v3/segments/#retrieve
:param segment_id: The segment to fetch.
:type segment_id: int
:return: A segment object.
:rtype: :class:`stravalib.model.Segment`
"""
return model.Segment.deserialize(self.protocol.get('/segments/{id}',
id=segment_id), bind_client=self) | python | def get_segment(self, segment_id):
"""
Gets a specific segment by ID.
http://strava.github.io/api/v3/segments/#retrieve
:param segment_id: The segment to fetch.
:type segment_id: int
:return: A segment object.
:rtype: :class:`stravalib.model.Segment`
"""
return model.Segment.deserialize(self.protocol.get('/segments/{id}',
id=segment_id), bind_client=self) | [
"def",
"get_segment",
"(",
"self",
",",
"segment_id",
")",
":",
"return",
"model",
".",
"Segment",
".",
"deserialize",
"(",
"self",
".",
"protocol",
".",
"get",
"(",
"'/segments/{id}'",
",",
"id",
"=",
"segment_id",
")",
",",
"bind_client",
"=",
"self",
... | Gets a specific segment by ID.
http://strava.github.io/api/v3/segments/#retrieve
:param segment_id: The segment to fetch.
:type segment_id: int
:return: A segment object.
:rtype: :class:`stravalib.model.Segment` | [
"Gets",
"a",
"specific",
"segment",
"by",
"ID",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L900-L913 | train | 202,952 |
hozn/stravalib | stravalib/client.py | Client.get_starred_segments | def get_starred_segments(self, limit=None):
"""
Returns a summary representation of the segments starred by the
authenticated user. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator`
"""
params = {}
if limit is not None:
params["limit"] = limit
result_fetcher = functools.partial(self.protocol.get,
'/segments/starred')
return BatchedResultsIterator(entity=model.Segment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | python | def get_starred_segments(self, limit=None):
"""
Returns a summary representation of the segments starred by the
authenticated user. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator`
"""
params = {}
if limit is not None:
params["limit"] = limit
result_fetcher = functools.partial(self.protocol.get,
'/segments/starred')
return BatchedResultsIterator(entity=model.Segment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | [
"def",
"get_starred_segments",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"limit",
"is",
"not",
"None",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"... | Returns a summary representation of the segments starred by the
authenticated user. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator` | [
"Returns",
"a",
"summary",
"representation",
"of",
"the",
"segments",
"starred",
"by",
"the",
"authenticated",
"user",
".",
"Pagination",
"is",
"supported",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L915-L939 | train | 202,953 |
hozn/stravalib | stravalib/client.py | Client.get_athlete_starred_segments | def get_athlete_starred_segments(self, athlete_id, limit=None):
"""
Returns a summary representation of the segments starred by the
specified athlete. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param athlete_id: The ID of the athlete.
:type athlete_id: int
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/athletes/{id}/segments/starred',
id=athlete_id)
return BatchedResultsIterator(entity=model.Segment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | python | def get_athlete_starred_segments(self, athlete_id, limit=None):
"""
Returns a summary representation of the segments starred by the
specified athlete. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param athlete_id: The ID of the athlete.
:type athlete_id: int
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get,
'/athletes/{id}/segments/starred',
id=athlete_id)
return BatchedResultsIterator(entity=model.Segment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | [
"def",
"get_athlete_starred_segments",
"(",
"self",
",",
"athlete_id",
",",
"limit",
"=",
"None",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/athletes/{id}/segments/starred'",
",",
"id",
"=",
... | Returns a summary representation of the segments starred by the
specified athlete. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param athlete_id: The ID of the athlete.
:type athlete_id: int
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator` | [
"Returns",
"a",
"summary",
"representation",
"of",
"the",
"segments",
"starred",
"by",
"the",
"specified",
"athlete",
".",
"Pagination",
"is",
"supported",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L941-L964 | train | 202,954 |
hozn/stravalib | stravalib/client.py | Client.get_segment_leaderboard | def get_segment_leaderboard(self, segment_id, gender=None, age_group=None, weight_class=None,
following=None, club_id=None, timeframe=None, top_results_limit=None,
page=None, context_entries = None):
"""
Gets the leaderboard for a segment.
http://strava.github.io/api/v3/segments/#leaderboard
Note that by default Strava will return the top 10 results, and if the current user has ridden
that segment, the current user's result along with the two results above in rank and the two
results below will be included. The top X results can be configured by setting the top_results_limit
parameter; however, the other 5 results will be included if the current user has ridden that segment.
(i.e. if you specify top_results_limit=15, you will get a total of 20 entries back.)
:param segment_id: ID of the segment.
:type segment_id: int
:param gender: (optional) 'M' or 'F'
:type gender: str
:param age_group: (optional) '0_24', '25_34', '35_44', '45_54', '55_64', '65_plus'
:type age_group: str
:param weight_class: (optional) pounds '0_124', '125_149', '150_164', '165_179', '180_199', '200_plus'
or kilograms '0_54', '55_64', '65_74', '75_84', '85_94', '95_plus'
:type weight_class: str
:param following: (optional) Limit to athletes current user is following.
:type following: bool
:param club_id: (optional) limit to specific club
:type club_id: int
:param timeframe: (optional) 'this_year', 'this_month', 'this_week', 'today'
:type timeframe: str
:param top_results_limit: (optional, strava default is 10 + 5 from end) How many of leading leaderboard entries to display.
See description for why this is a little confusing.
:type top_results_limit: int
:param page: (optional, strava default is 1) Page number of leaderboard to return, sorted by highest ranking leaders
:type page: int
:param context_entries: (optional, strava default is 2, max is 15) number of entries surrounding requesting athlete to return
:type context_entries: int
:return: The SegmentLeaderboard for the specified page (default: 1)
:rtype: :class:`stravalib.model.SegmentLeaderboard`
"""
params = {}
if gender is not None:
if gender.upper() not in ('M', 'F'):
raise ValueError("Invalid gender: {0}. Possible values: 'M' or 'F'".format(gender))
params['gender'] = gender
valid_age_groups = ('0_24', '25_34', '35_44', '45_54', '55_64', '65_plus')
if age_group is not None:
if not age_group in valid_age_groups:
raise ValueError("Invalid age group: {0}. Possible values: {1!r}".format(age_group, valid_age_groups))
params['age_group'] = age_group
valid_weight_classes = ('0_124', '125_149', '150_164', '165_179', '180_199', '200_plus',
'0_54', '55_64', '65_74', '75_84', '85_94', '95_plus')
if weight_class is not None:
if not weight_class in valid_weight_classes:
raise ValueError("Invalid weight class: {0}. Possible values: {1!r}".format(weight_class, valid_weight_classes))
params['weight_class'] = weight_class
if following is not None:
params['following'] = int(following)
if club_id is not None:
params['club_id'] = club_id
if timeframe is not None:
valid_timeframes = 'this_year', 'this_month', 'this_week', 'today'
if not timeframe in valid_timeframes:
raise ValueError("Invalid timeframe: {0}. Possible values: {1!r}".format(timeframe, valid_timeframes))
params['date_range'] = timeframe
if top_results_limit is not None:
params['per_page'] = top_results_limit
if page is not None:
params['page'] = page
if context_entries is not None:
params['context_entries'] = context_entries
return model.SegmentLeaderboard.deserialize(self.protocol.get('/segments/{id}/leaderboard',
id=segment_id,
**params),
bind_client=self) | python | def get_segment_leaderboard(self, segment_id, gender=None, age_group=None, weight_class=None,
following=None, club_id=None, timeframe=None, top_results_limit=None,
page=None, context_entries = None):
"""
Gets the leaderboard for a segment.
http://strava.github.io/api/v3/segments/#leaderboard
Note that by default Strava will return the top 10 results, and if the current user has ridden
that segment, the current user's result along with the two results above in rank and the two
results below will be included. The top X results can be configured by setting the top_results_limit
parameter; however, the other 5 results will be included if the current user has ridden that segment.
(i.e. if you specify top_results_limit=15, you will get a total of 20 entries back.)
:param segment_id: ID of the segment.
:type segment_id: int
:param gender: (optional) 'M' or 'F'
:type gender: str
:param age_group: (optional) '0_24', '25_34', '35_44', '45_54', '55_64', '65_plus'
:type age_group: str
:param weight_class: (optional) pounds '0_124', '125_149', '150_164', '165_179', '180_199', '200_plus'
or kilograms '0_54', '55_64', '65_74', '75_84', '85_94', '95_plus'
:type weight_class: str
:param following: (optional) Limit to athletes current user is following.
:type following: bool
:param club_id: (optional) limit to specific club
:type club_id: int
:param timeframe: (optional) 'this_year', 'this_month', 'this_week', 'today'
:type timeframe: str
:param top_results_limit: (optional, strava default is 10 + 5 from end) How many of leading leaderboard entries to display.
See description for why this is a little confusing.
:type top_results_limit: int
:param page: (optional, strava default is 1) Page number of leaderboard to return, sorted by highest ranking leaders
:type page: int
:param context_entries: (optional, strava default is 2, max is 15) number of entries surrounding requesting athlete to return
:type context_entries: int
:return: The SegmentLeaderboard for the specified page (default: 1)
:rtype: :class:`stravalib.model.SegmentLeaderboard`
"""
params = {}
if gender is not None:
if gender.upper() not in ('M', 'F'):
raise ValueError("Invalid gender: {0}. Possible values: 'M' or 'F'".format(gender))
params['gender'] = gender
valid_age_groups = ('0_24', '25_34', '35_44', '45_54', '55_64', '65_plus')
if age_group is not None:
if not age_group in valid_age_groups:
raise ValueError("Invalid age group: {0}. Possible values: {1!r}".format(age_group, valid_age_groups))
params['age_group'] = age_group
valid_weight_classes = ('0_124', '125_149', '150_164', '165_179', '180_199', '200_plus',
'0_54', '55_64', '65_74', '75_84', '85_94', '95_plus')
if weight_class is not None:
if not weight_class in valid_weight_classes:
raise ValueError("Invalid weight class: {0}. Possible values: {1!r}".format(weight_class, valid_weight_classes))
params['weight_class'] = weight_class
if following is not None:
params['following'] = int(following)
if club_id is not None:
params['club_id'] = club_id
if timeframe is not None:
valid_timeframes = 'this_year', 'this_month', 'this_week', 'today'
if not timeframe in valid_timeframes:
raise ValueError("Invalid timeframe: {0}. Possible values: {1!r}".format(timeframe, valid_timeframes))
params['date_range'] = timeframe
if top_results_limit is not None:
params['per_page'] = top_results_limit
if page is not None:
params['page'] = page
if context_entries is not None:
params['context_entries'] = context_entries
return model.SegmentLeaderboard.deserialize(self.protocol.get('/segments/{id}/leaderboard',
id=segment_id,
**params),
bind_client=self) | [
"def",
"get_segment_leaderboard",
"(",
"self",
",",
"segment_id",
",",
"gender",
"=",
"None",
",",
"age_group",
"=",
"None",
",",
"weight_class",
"=",
"None",
",",
"following",
"=",
"None",
",",
"club_id",
"=",
"None",
",",
"timeframe",
"=",
"None",
",",
... | Gets the leaderboard for a segment.
http://strava.github.io/api/v3/segments/#leaderboard
Note that by default Strava will return the top 10 results, and if the current user has ridden
that segment, the current user's result along with the two results above in rank and the two
results below will be included. The top X results can be configured by setting the top_results_limit
parameter; however, the other 5 results will be included if the current user has ridden that segment.
(i.e. if you specify top_results_limit=15, you will get a total of 20 entries back.)
:param segment_id: ID of the segment.
:type segment_id: int
:param gender: (optional) 'M' or 'F'
:type gender: str
:param age_group: (optional) '0_24', '25_34', '35_44', '45_54', '55_64', '65_plus'
:type age_group: str
:param weight_class: (optional) pounds '0_124', '125_149', '150_164', '165_179', '180_199', '200_plus'
or kilograms '0_54', '55_64', '65_74', '75_84', '85_94', '95_plus'
:type weight_class: str
:param following: (optional) Limit to athletes current user is following.
:type following: bool
:param club_id: (optional) limit to specific club
:type club_id: int
:param timeframe: (optional) 'this_year', 'this_month', 'this_week', 'today'
:type timeframe: str
:param top_results_limit: (optional, strava default is 10 + 5 from end) How many of leading leaderboard entries to display.
See description for why this is a little confusing.
:type top_results_limit: int
:param page: (optional, strava default is 1) Page number of leaderboard to return, sorted by highest ranking leaders
:type page: int
:param context_entries: (optional, strava default is 2, max is 15) number of entries surrounding requesting athlete to return
:type context_entries: int
:return: The SegmentLeaderboard for the specified page (default: 1)
:rtype: :class:`stravalib.model.SegmentLeaderboard` | [
"Gets",
"the",
"leaderboard",
"for",
"a",
"segment",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L966-L1059 | train | 202,955 |
hozn/stravalib | stravalib/client.py | Client.get_segment_efforts | def get_segment_efforts(self, segment_id, athlete_id=None,
start_date_local=None, end_date_local=None,
limit=None):
"""
Gets all efforts on a particular segment sorted by start_date_local
Returns an array of segment effort summary representations sorted by
start_date_local ascending or by elapsed_time if an athlete_id is
provided.
If no filtering parameters is provided all efforts for the segment
will be returned.
Date range filtering is accomplished using an inclusive start and end time,
thus start_date_local and end_date_local must be sent together. For open
ended ranges pick dates significantly in the past or future. The
filtering is done over local time for the segment, so there is no need
for timezone conversion. For example, all efforts on Jan. 1st, 2014
for a segment in San Francisco, CA can be fetched using
2014-01-01T00:00:00Z and 2014-01-01T23:59:59Z.
http://strava.github.io/api/v3/segments/#all_efforts
:param segment_id: ID of the segment.
:type segment_id: param
:int athlete_id: (optional) ID of athlete.
:type athlete_id: int
:param start_date_local: (optional) efforts before this date will be excluded.
Either as ISO8601 or datetime object
:type start_date_local: datetime.datetime or str
:param end_date_local: (optional) efforts after this date will be excluded.
Either as ISO8601 or datetime object
:type end_date_local: datetime.datetime or str
:param limit: (optional), limit number of efforts.
:type limit: int
:return: An iterator of :class:`stravalib.model.SegmentEffort` efforts on a segment.
:rtype: :class:`BatchedResultsIterator`
"""
params = {"segment_id": segment_id}
if athlete_id is not None:
params['athlete_id'] = athlete_id
if start_date_local:
if isinstance(start_date_local, six.string_types):
start_date_local = arrow.get(start_date_local).naive
params["start_date_local"] = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if end_date_local:
if isinstance(end_date_local, six.string_types):
end_date_local = arrow.get(end_date_local).naive
params["end_date_local"] = end_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if limit is not None:
params["limit"] = limit
result_fetcher = functools.partial(self.protocol.get,
'/segments/{segment_id}/all_efforts',
**params)
return BatchedResultsIterator(entity=model.BaseEffort, bind_client=self,
result_fetcher=result_fetcher, limit=limit) | python | def get_segment_efforts(self, segment_id, athlete_id=None,
start_date_local=None, end_date_local=None,
limit=None):
"""
Gets all efforts on a particular segment sorted by start_date_local
Returns an array of segment effort summary representations sorted by
start_date_local ascending or by elapsed_time if an athlete_id is
provided.
If no filtering parameters is provided all efforts for the segment
will be returned.
Date range filtering is accomplished using an inclusive start and end time,
thus start_date_local and end_date_local must be sent together. For open
ended ranges pick dates significantly in the past or future. The
filtering is done over local time for the segment, so there is no need
for timezone conversion. For example, all efforts on Jan. 1st, 2014
for a segment in San Francisco, CA can be fetched using
2014-01-01T00:00:00Z and 2014-01-01T23:59:59Z.
http://strava.github.io/api/v3/segments/#all_efforts
:param segment_id: ID of the segment.
:type segment_id: param
:int athlete_id: (optional) ID of athlete.
:type athlete_id: int
:param start_date_local: (optional) efforts before this date will be excluded.
Either as ISO8601 or datetime object
:type start_date_local: datetime.datetime or str
:param end_date_local: (optional) efforts after this date will be excluded.
Either as ISO8601 or datetime object
:type end_date_local: datetime.datetime or str
:param limit: (optional), limit number of efforts.
:type limit: int
:return: An iterator of :class:`stravalib.model.SegmentEffort` efforts on a segment.
:rtype: :class:`BatchedResultsIterator`
"""
params = {"segment_id": segment_id}
if athlete_id is not None:
params['athlete_id'] = athlete_id
if start_date_local:
if isinstance(start_date_local, six.string_types):
start_date_local = arrow.get(start_date_local).naive
params["start_date_local"] = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if end_date_local:
if isinstance(end_date_local, six.string_types):
end_date_local = arrow.get(end_date_local).naive
params["end_date_local"] = end_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if limit is not None:
params["limit"] = limit
result_fetcher = functools.partial(self.protocol.get,
'/segments/{segment_id}/all_efforts',
**params)
return BatchedResultsIterator(entity=model.BaseEffort, bind_client=self,
result_fetcher=result_fetcher, limit=limit) | [
"def",
"get_segment_efforts",
"(",
"self",
",",
"segment_id",
",",
"athlete_id",
"=",
"None",
",",
"start_date_local",
"=",
"None",
",",
"end_date_local",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"segment_id\"",
":",
"segment_i... | Gets all efforts on a particular segment sorted by start_date_local
Returns an array of segment effort summary representations sorted by
start_date_local ascending or by elapsed_time if an athlete_id is
provided.
If no filtering parameters is provided all efforts for the segment
will be returned.
Date range filtering is accomplished using an inclusive start and end time,
thus start_date_local and end_date_local must be sent together. For open
ended ranges pick dates significantly in the past or future. The
filtering is done over local time for the segment, so there is no need
for timezone conversion. For example, all efforts on Jan. 1st, 2014
for a segment in San Francisco, CA can be fetched using
2014-01-01T00:00:00Z and 2014-01-01T23:59:59Z.
http://strava.github.io/api/v3/segments/#all_efforts
:param segment_id: ID of the segment.
:type segment_id: param
:int athlete_id: (optional) ID of athlete.
:type athlete_id: int
:param start_date_local: (optional) efforts before this date will be excluded.
Either as ISO8601 or datetime object
:type start_date_local: datetime.datetime or str
:param end_date_local: (optional) efforts after this date will be excluded.
Either as ISO8601 or datetime object
:type end_date_local: datetime.datetime or str
:param limit: (optional), limit number of efforts.
:type limit: int
:return: An iterator of :class:`stravalib.model.SegmentEffort` efforts on a segment.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"all",
"efforts",
"on",
"a",
"particular",
"segment",
"sorted",
"by",
"start_date_local"
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1061-L1128 | train | 202,956 |
hozn/stravalib | stravalib/client.py | Client.explore_segments | def explore_segments(self, bounds, activity_type=None, min_cat=None, max_cat=None):
"""
Returns an array of up to 10 segments.
http://strava.github.io/api/v3/segments/#explore
:param bounds: list of bounding box corners lat/lon [sw.lat, sw.lng, ne.lat, ne.lng] (south,west,north,east)
:type bounds: list of 4 floats or list of 2 (lat,lon) tuples
:param activity_type: (optional, default is riding) 'running' or 'riding'
:type activity_type: str
:param min_cat: (optional) Minimum climb category filter
:type min_cat: int
:param max_cat: (optional) Maximum climb category filter
:type max_cat: int
:return: An list of :class:`stravalib.model.Segment`.
:rtype: :py:class:`list`
"""
if len(bounds) == 2:
bounds = (bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1])
elif len(bounds) != 4:
raise ValueError("Invalid bounds specified: {0!r}. Must be list of 4 float values or list of 2 (lat,lon) tuples.")
params = {'bounds': ','.join(str(b) for b in bounds)}
valid_activity_types = ('riding', 'running')
if activity_type is not None:
if activity_type not in ('riding', 'running'):
raise ValueError('Invalid activity type: {0}. Possible values: {1!r}'.format(activity_type, valid_activity_types))
params['activity_type'] = activity_type
if min_cat is not None:
params['min_cat'] = min_cat
if max_cat is not None:
params['max_cat'] = max_cat
raw = self.protocol.get('/segments/explore', **params)
return [model.SegmentExplorerResult.deserialize(v, bind_client=self)
for v in raw['segments']] | python | def explore_segments(self, bounds, activity_type=None, min_cat=None, max_cat=None):
"""
Returns an array of up to 10 segments.
http://strava.github.io/api/v3/segments/#explore
:param bounds: list of bounding box corners lat/lon [sw.lat, sw.lng, ne.lat, ne.lng] (south,west,north,east)
:type bounds: list of 4 floats or list of 2 (lat,lon) tuples
:param activity_type: (optional, default is riding) 'running' or 'riding'
:type activity_type: str
:param min_cat: (optional) Minimum climb category filter
:type min_cat: int
:param max_cat: (optional) Maximum climb category filter
:type max_cat: int
:return: An list of :class:`stravalib.model.Segment`.
:rtype: :py:class:`list`
"""
if len(bounds) == 2:
bounds = (bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1])
elif len(bounds) != 4:
raise ValueError("Invalid bounds specified: {0!r}. Must be list of 4 float values or list of 2 (lat,lon) tuples.")
params = {'bounds': ','.join(str(b) for b in bounds)}
valid_activity_types = ('riding', 'running')
if activity_type is not None:
if activity_type not in ('riding', 'running'):
raise ValueError('Invalid activity type: {0}. Possible values: {1!r}'.format(activity_type, valid_activity_types))
params['activity_type'] = activity_type
if min_cat is not None:
params['min_cat'] = min_cat
if max_cat is not None:
params['max_cat'] = max_cat
raw = self.protocol.get('/segments/explore', **params)
return [model.SegmentExplorerResult.deserialize(v, bind_client=self)
for v in raw['segments']] | [
"def",
"explore_segments",
"(",
"self",
",",
"bounds",
",",
"activity_type",
"=",
"None",
",",
"min_cat",
"=",
"None",
",",
"max_cat",
"=",
"None",
")",
":",
"if",
"len",
"(",
"bounds",
")",
"==",
"2",
":",
"bounds",
"=",
"(",
"bounds",
"[",
"0",
"... | Returns an array of up to 10 segments.
http://strava.github.io/api/v3/segments/#explore
:param bounds: list of bounding box corners lat/lon [sw.lat, sw.lng, ne.lat, ne.lng] (south,west,north,east)
:type bounds: list of 4 floats or list of 2 (lat,lon) tuples
:param activity_type: (optional, default is riding) 'running' or 'riding'
:type activity_type: str
:param min_cat: (optional) Minimum climb category filter
:type min_cat: int
:param max_cat: (optional) Maximum climb category filter
:type max_cat: int
:return: An list of :class:`stravalib.model.Segment`.
:rtype: :py:class:`list` | [
"Returns",
"an",
"array",
"of",
"up",
"to",
"10",
"segments",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1130-L1172 | train | 202,957 |
hozn/stravalib | stravalib/client.py | Client.get_activity_streams | def get_activity_streams(self, activity_id, types=None,
resolution=None, series_type=None):
"""
Returns an streams for an activity.
http://strava.github.io/api/v3/streams/#activity
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#activity
:param activity_id: The ID of activity.
:type activity_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the activity or None if there are no streams.
:rtype: :py:class:`dict`
"""
# stream are comma seperated list
if types is not None:
types = ",".join(types)
params = {}
if resolution is not None:
params["resolution"] = resolution
if series_type is not None:
params["series_type"] = series_type
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/streams/{types}'.format(id=activity_id, types=types),
**params)
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
try:
return {i.type: i for i in streams}
except exc.ObjectNotFound:
return None | python | def get_activity_streams(self, activity_id, types=None,
resolution=None, series_type=None):
"""
Returns an streams for an activity.
http://strava.github.io/api/v3/streams/#activity
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#activity
:param activity_id: The ID of activity.
:type activity_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the activity or None if there are no streams.
:rtype: :py:class:`dict`
"""
# stream are comma seperated list
if types is not None:
types = ",".join(types)
params = {}
if resolution is not None:
params["resolution"] = resolution
if series_type is not None:
params["series_type"] = series_type
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/streams/{types}'.format(id=activity_id, types=types),
**params)
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
try:
return {i.type: i for i in streams}
except exc.ObjectNotFound:
return None | [
"def",
"get_activity_streams",
"(",
"self",
",",
"activity_id",
",",
"types",
"=",
"None",
",",
"resolution",
"=",
"None",
",",
"series_type",
"=",
"None",
")",
":",
"# stream are comma seperated list",
"if",
"types",
"is",
"not",
"None",
":",
"types",
"=",
... | Returns an streams for an activity.
http://strava.github.io/api/v3/streams/#activity
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#activity
:param activity_id: The ID of activity.
:type activity_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the activity or None if there are no streams.
:rtype: :py:class:`dict` | [
"Returns",
"an",
"streams",
"for",
"an",
"activity",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1174-L1238 | train | 202,958 |
hozn/stravalib | stravalib/client.py | Client.get_effort_streams | def get_effort_streams(self, effort_id, types=None, resolution=None,
series_type=None):
"""
Returns an streams for an effort.
http://strava.github.io/api/v3/streams/#effort
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#effort
:param effort_id: The ID of effort.
:type effort_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the effort.
:rtype: :py:class:`dict`
"""
# stream are comma seperated list
if types is not None:
types = ",".join(types)
params = {}
if resolution is not None:
params["resolution"] = resolution
if series_type is not None:
params["series_type"] = series_type
result_fetcher = functools.partial(self.protocol.get,
'/segment_efforts/{id}/streams/{types}'.format(id=effort_id, types=types),
**params)
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
return {i.type: i for i in streams} | python | def get_effort_streams(self, effort_id, types=None, resolution=None,
series_type=None):
"""
Returns an streams for an effort.
http://strava.github.io/api/v3/streams/#effort
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#effort
:param effort_id: The ID of effort.
:type effort_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the effort.
:rtype: :py:class:`dict`
"""
# stream are comma seperated list
if types is not None:
types = ",".join(types)
params = {}
if resolution is not None:
params["resolution"] = resolution
if series_type is not None:
params["series_type"] = series_type
result_fetcher = functools.partial(self.protocol.get,
'/segment_efforts/{id}/streams/{types}'.format(id=effort_id, types=types),
**params)
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
return {i.type: i for i in streams} | [
"def",
"get_effort_streams",
"(",
"self",
",",
"effort_id",
",",
"types",
"=",
"None",
",",
"resolution",
"=",
"None",
",",
"series_type",
"=",
"None",
")",
":",
"# stream are comma seperated list",
"if",
"types",
"is",
"not",
"None",
":",
"types",
"=",
"\",... | Returns an streams for an effort.
http://strava.github.io/api/v3/streams/#effort
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#effort
:param effort_id: The ID of effort.
:type effort_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the effort.
:rtype: :py:class:`dict` | [
"Returns",
"an",
"streams",
"for",
"an",
"effort",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1240-L1302 | train | 202,959 |
hozn/stravalib | stravalib/client.py | Client.get_running_race | def get_running_race(self, race_id):
"""
Gets a running race for a given identifier.t
http://strava.github.io/api/v3/running_races/#list
:param race_id: id for the race
:rtype: :class:`stravalib.model.RunningRace`
"""
raw = self.protocol.get('/running_races/{id}', id=race_id)
return model.RunningRace.deserialize(raw, bind_client=self) | python | def get_running_race(self, race_id):
"""
Gets a running race for a given identifier.t
http://strava.github.io/api/v3/running_races/#list
:param race_id: id for the race
:rtype: :class:`stravalib.model.RunningRace`
"""
raw = self.protocol.get('/running_races/{id}', id=race_id)
return model.RunningRace.deserialize(raw, bind_client=self) | [
"def",
"get_running_race",
"(",
"self",
",",
"race_id",
")",
":",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/running_races/{id}'",
",",
"id",
"=",
"race_id",
")",
"return",
"model",
".",
"RunningRace",
".",
"deserialize",
"(",
"raw",
",",
"... | Gets a running race for a given identifier.t
http://strava.github.io/api/v3/running_races/#list
:param race_id: id for the race
:rtype: :class:`stravalib.model.RunningRace` | [
"Gets",
"a",
"running",
"race",
"for",
"a",
"given",
"identifier",
".",
"t"
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1367-L1378 | train | 202,960 |
hozn/stravalib | stravalib/client.py | Client.get_running_races | def get_running_races(self, year=None):
"""
Gets a running races for a given year.
http://strava.github.io/api/v3/running_races/#list
:param year: year for the races (default current)
:return: An iterator of :class:`stravalib.model.RunningRace` objects.
:rtype: :class:`BatchedResultsIterator`
"""
if year is None:
year = datetime.datetime.now().year
params = {"year": year}
result_fetcher = functools.partial(self.protocol.get,
'/running_races',
**params)
return BatchedResultsIterator(entity=model.RunningRace, bind_client=self,
result_fetcher=result_fetcher) | python | def get_running_races(self, year=None):
"""
Gets a running races for a given year.
http://strava.github.io/api/v3/running_races/#list
:param year: year for the races (default current)
:return: An iterator of :class:`stravalib.model.RunningRace` objects.
:rtype: :class:`BatchedResultsIterator`
"""
if year is None:
year = datetime.datetime.now().year
params = {"year": year}
result_fetcher = functools.partial(self.protocol.get,
'/running_races',
**params)
return BatchedResultsIterator(entity=model.RunningRace, bind_client=self,
result_fetcher=result_fetcher) | [
"def",
"get_running_races",
"(",
"self",
",",
"year",
"=",
"None",
")",
":",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"year",
"params",
"=",
"{",
"\"year\"",
":",
"year",
"}",
"result_fetch... | Gets a running races for a given year.
http://strava.github.io/api/v3/running_races/#list
:param year: year for the races (default current)
:return: An iterator of :class:`stravalib.model.RunningRace` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"a",
"running",
"races",
"for",
"a",
"given",
"year",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1381-L1402 | train | 202,961 |
hozn/stravalib | stravalib/client.py | Client.get_routes | def get_routes(self, athlete_id=None, limit=None):
"""
Gets the routes list for an authenticated user.
http://strava.github.io/api/v3/routes/#list
:param athlete_id: id for the
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.Route` objects.
:rtype: :class:`BatchedResultsIterator`
"""
if athlete_id is None:
athlete_id = self.get_athlete().id
result_fetcher = functools.partial(self.protocol.get,
'/athletes/{id}/routes'.format(id=athlete_id))
return BatchedResultsIterator(entity=model.Route,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | python | def get_routes(self, athlete_id=None, limit=None):
"""
Gets the routes list for an authenticated user.
http://strava.github.io/api/v3/routes/#list
:param athlete_id: id for the
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.Route` objects.
:rtype: :class:`BatchedResultsIterator`
"""
if athlete_id is None:
athlete_id = self.get_athlete().id
result_fetcher = functools.partial(self.protocol.get,
'/athletes/{id}/routes'.format(id=athlete_id))
return BatchedResultsIterator(entity=model.Route,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | [
"def",
"get_routes",
"(",
"self",
",",
"athlete_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"athlete_id",
"is",
"None",
":",
"athlete_id",
"=",
"self",
".",
"get_athlete",
"(",
")",
".",
"id",
"result_fetcher",
"=",
"functools",
".",
"... | Gets the routes list for an authenticated user.
http://strava.github.io/api/v3/routes/#list
:param athlete_id: id for the
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.Route` objects.
:rtype: :class:`BatchedResultsIterator` | [
"Gets",
"the",
"routes",
"list",
"for",
"an",
"authenticated",
"user",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1405-L1428 | train | 202,962 |
hozn/stravalib | stravalib/client.py | Client.get_route | def get_route(self, route_id):
"""
Gets specified route.
Will be detail-level if owned by authenticated user; otherwise summary-level.
https://strava.github.io/api/v3/routes/#retreive
:param route_id: The ID of route to fetch.
:type route_id: int
:rtype: :class:`stravalib.model.Route`
"""
raw = self.protocol.get('/routes/{id}', id=route_id)
return model.Route.deserialize(raw, bind_client=self) | python | def get_route(self, route_id):
"""
Gets specified route.
Will be detail-level if owned by authenticated user; otherwise summary-level.
https://strava.github.io/api/v3/routes/#retreive
:param route_id: The ID of route to fetch.
:type route_id: int
:rtype: :class:`stravalib.model.Route`
"""
raw = self.protocol.get('/routes/{id}', id=route_id)
return model.Route.deserialize(raw, bind_client=self) | [
"def",
"get_route",
"(",
"self",
",",
"route_id",
")",
":",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/routes/{id}'",
",",
"id",
"=",
"route_id",
")",
"return",
"model",
".",
"Route",
".",
"deserialize",
"(",
"raw",
",",
"bind_client",
"=... | Gets specified route.
Will be detail-level if owned by authenticated user; otherwise summary-level.
https://strava.github.io/api/v3/routes/#retreive
:param route_id: The ID of route to fetch.
:type route_id: int
:rtype: :class:`stravalib.model.Route` | [
"Gets",
"specified",
"route",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1430-L1444 | train | 202,963 |
hozn/stravalib | stravalib/client.py | Client.get_route_streams | def get_route_streams(self, route_id):
"""
Returns streams for a route.
http://strava.github.io/api/v3/streams/#routes
Streams represent the raw data of the saved route. External
applications may access this information for all public routes and for
the private routes of the authenticated athlete.
The 3 available route stream types `distance`, `altitude` and `latlng`
are always returned.
http://strava.github.io/api/v3/streams/#routes
:param activity_id: The ID of activity.
:type activity_id: int
:return: A dictionary of :class:`stravalib.model.Stream`from the route.
:rtype: :py:class:`dict`
"""
result_fetcher = functools.partial(self.protocol.get,
'/routes/{id}/streams/'.format(id=route_id))
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
return {i.type: i for i in streams} | python | def get_route_streams(self, route_id):
"""
Returns streams for a route.
http://strava.github.io/api/v3/streams/#routes
Streams represent the raw data of the saved route. External
applications may access this information for all public routes and for
the private routes of the authenticated athlete.
The 3 available route stream types `distance`, `altitude` and `latlng`
are always returned.
http://strava.github.io/api/v3/streams/#routes
:param activity_id: The ID of activity.
:type activity_id: int
:return: A dictionary of :class:`stravalib.model.Stream`from the route.
:rtype: :py:class:`dict`
"""
result_fetcher = functools.partial(self.protocol.get,
'/routes/{id}/streams/'.format(id=route_id))
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
return {i.type: i for i in streams} | [
"def",
"get_route_streams",
"(",
"self",
",",
"route_id",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/routes/{id}/streams/'",
".",
"format",
"(",
"id",
"=",
"route_id",
")",
")",
"streams",
... | Returns streams for a route.
http://strava.github.io/api/v3/streams/#routes
Streams represent the raw data of the saved route. External
applications may access this information for all public routes and for
the private routes of the authenticated athlete.
The 3 available route stream types `distance`, `altitude` and `latlng`
are always returned.
http://strava.github.io/api/v3/streams/#routes
:param activity_id: The ID of activity.
:type activity_id: int
:return: A dictionary of :class:`stravalib.model.Stream`from the route.
:rtype: :py:class:`dict` | [
"Returns",
"streams",
"for",
"a",
"route",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1446-L1477 | train | 202,964 |
hozn/stravalib | stravalib/client.py | Client.create_subscription | def create_subscription(self, client_id, client_secret, callback_url,
object_type=model.Subscription.OBJECT_TYPE_ACTIVITY,
aspect_type=model.Subscription.ASPECT_TYPE_CREATE,
verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT):
"""
Creates a webhook event subscription.
http://strava.github.io/api/partner/v3/events/#create-a-subscription
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:param callback_url: callback URL where Strava will first send a GET request to validate, then subsequently send POST requests with updates
:type callback_url: str
:param object_type: object_type (currently only `activity` is supported)
:type object_type: str
:param aspect_type: object_type (currently only `create` is supported)
:type aspect_type: str
:param verify_token: a token you can use to verify Strava's GET callback request
:type verify_token: str
:return: An instance of :class:`stravalib.model.Subscription`.
:rtype: :class:`stravalib.model.Subscription`
Notes:
`object_type` and `aspect_type` are given defaults because there is currently only one valid value for each.
`verify_token` is set to a default in the event that the author doesn't want to specify one.
The appliction must have permission to make use of the webhook API. Access can be requested by contacting developers -at- strava.com.
"""
params = dict(client_id=client_id, client_secret=client_secret,
object_type=object_type, aspect_type=aspect_type,
callback_url=callback_url, verify_token=verify_token)
raw = self.protocol.post('/push_subscriptions', use_webhook_server=True,
**params)
return model.Subscription.deserialize(raw, bind_client=self) | python | def create_subscription(self, client_id, client_secret, callback_url,
object_type=model.Subscription.OBJECT_TYPE_ACTIVITY,
aspect_type=model.Subscription.ASPECT_TYPE_CREATE,
verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT):
"""
Creates a webhook event subscription.
http://strava.github.io/api/partner/v3/events/#create-a-subscription
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:param callback_url: callback URL where Strava will first send a GET request to validate, then subsequently send POST requests with updates
:type callback_url: str
:param object_type: object_type (currently only `activity` is supported)
:type object_type: str
:param aspect_type: object_type (currently only `create` is supported)
:type aspect_type: str
:param verify_token: a token you can use to verify Strava's GET callback request
:type verify_token: str
:return: An instance of :class:`stravalib.model.Subscription`.
:rtype: :class:`stravalib.model.Subscription`
Notes:
`object_type` and `aspect_type` are given defaults because there is currently only one valid value for each.
`verify_token` is set to a default in the event that the author doesn't want to specify one.
The appliction must have permission to make use of the webhook API. Access can be requested by contacting developers -at- strava.com.
"""
params = dict(client_id=client_id, client_secret=client_secret,
object_type=object_type, aspect_type=aspect_type,
callback_url=callback_url, verify_token=verify_token)
raw = self.protocol.post('/push_subscriptions', use_webhook_server=True,
**params)
return model.Subscription.deserialize(raw, bind_client=self) | [
"def",
"create_subscription",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"callback_url",
",",
"object_type",
"=",
"model",
".",
"Subscription",
".",
"OBJECT_TYPE_ACTIVITY",
",",
"aspect_type",
"=",
"model",
".",
"Subscription",
".",
"ASPECT_TYPE_CREAT... | Creates a webhook event subscription.
http://strava.github.io/api/partner/v3/events/#create-a-subscription
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:param callback_url: callback URL where Strava will first send a GET request to validate, then subsequently send POST requests with updates
:type callback_url: str
:param object_type: object_type (currently only `activity` is supported)
:type object_type: str
:param aspect_type: object_type (currently only `create` is supported)
:type aspect_type: str
:param verify_token: a token you can use to verify Strava's GET callback request
:type verify_token: str
:return: An instance of :class:`stravalib.model.Subscription`.
:rtype: :class:`stravalib.model.Subscription`
Notes:
`object_type` and `aspect_type` are given defaults because there is currently only one valid value for each.
`verify_token` is set to a default in the event that the author doesn't want to specify one.
The appliction must have permission to make use of the webhook API. Access can be requested by contacting developers -at- strava.com. | [
"Creates",
"a",
"webhook",
"event",
"subscription",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1479-L1522 | train | 202,965 |
hozn/stravalib | stravalib/client.py | Client.handle_subscription_callback | def handle_subscription_callback(self, raw,
verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT):
"""
Validate callback request and return valid response with challenge.
:return: The JSON response expected by Strava to the challenge request.
:rtype: Dict[str, str]
"""
callback = model.SubscriptionCallback.deserialize(raw)
callback.validate(verify_token)
response_raw = {'hub.challenge': callback.hub_challenge}
return response_raw | python | def handle_subscription_callback(self, raw,
verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT):
"""
Validate callback request and return valid response with challenge.
:return: The JSON response expected by Strava to the challenge request.
:rtype: Dict[str, str]
"""
callback = model.SubscriptionCallback.deserialize(raw)
callback.validate(verify_token)
response_raw = {'hub.challenge': callback.hub_challenge}
return response_raw | [
"def",
"handle_subscription_callback",
"(",
"self",
",",
"raw",
",",
"verify_token",
"=",
"model",
".",
"Subscription",
".",
"VERIFY_TOKEN_DEFAULT",
")",
":",
"callback",
"=",
"model",
".",
"SubscriptionCallback",
".",
"deserialize",
"(",
"raw",
")",
"callback",
... | Validate callback request and return valid response with challenge.
:return: The JSON response expected by Strava to the challenge request.
:rtype: Dict[str, str] | [
"Validate",
"callback",
"request",
"and",
"return",
"valid",
"response",
"with",
"challenge",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1524-L1535 | train | 202,966 |
hozn/stravalib | stravalib/client.py | Client.list_subscriptions | def list_subscriptions(self, client_id, client_secret):
"""
List current webhook event subscriptions in place for the current application.
http://strava.github.io/api/partner/v3/events/#list-push-subscriptions
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:return: An iterator of :class:`stravalib.model.Subscription` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get, '/push_subscriptions', client_id=client_id,
client_secret=client_secret, use_webhook_server=True)
return BatchedResultsIterator(entity=model.Subscription,
bind_client=self,
result_fetcher=result_fetcher) | python | def list_subscriptions(self, client_id, client_secret):
"""
List current webhook event subscriptions in place for the current application.
http://strava.github.io/api/partner/v3/events/#list-push-subscriptions
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:return: An iterator of :class:`stravalib.model.Subscription` objects.
:rtype: :class:`BatchedResultsIterator`
"""
result_fetcher = functools.partial(self.protocol.get, '/push_subscriptions', client_id=client_id,
client_secret=client_secret, use_webhook_server=True)
return BatchedResultsIterator(entity=model.Subscription,
bind_client=self,
result_fetcher=result_fetcher) | [
"def",
"list_subscriptions",
"(",
"self",
",",
"client_id",
",",
"client_secret",
")",
":",
"result_fetcher",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"protocol",
".",
"get",
",",
"'/push_subscriptions'",
",",
"client_id",
"=",
"client_id",
",",
"cl... | List current webhook event subscriptions in place for the current application.
http://strava.github.io/api/partner/v3/events/#list-push-subscriptions
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:return: An iterator of :class:`stravalib.model.Subscription` objects.
:rtype: :class:`BatchedResultsIterator` | [
"List",
"current",
"webhook",
"event",
"subscriptions",
"in",
"place",
"for",
"the",
"current",
"application",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1546-L1566 | train | 202,967 |
hozn/stravalib | stravalib/client.py | Client.delete_subscription | def delete_subscription(self, subscription_id, client_id, client_secret):
"""
Unsubscribe from webhook events for an existing subscription.
http://strava.github.io/api/partner/v3/events/#delete-a-subscription
:param subscription_id: ID of subscription to remove.
:type subscription_id: int
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
"""
self.protocol.delete('/push_subscriptions/{id}', id=subscription_id,
client_id=client_id, client_secret=client_secret, use_webhook_server=True) | python | def delete_subscription(self, subscription_id, client_id, client_secret):
"""
Unsubscribe from webhook events for an existing subscription.
http://strava.github.io/api/partner/v3/events/#delete-a-subscription
:param subscription_id: ID of subscription to remove.
:type subscription_id: int
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
"""
self.protocol.delete('/push_subscriptions/{id}', id=subscription_id,
client_id=client_id, client_secret=client_secret, use_webhook_server=True) | [
"def",
"delete_subscription",
"(",
"self",
",",
"subscription_id",
",",
"client_id",
",",
"client_secret",
")",
":",
"self",
".",
"protocol",
".",
"delete",
"(",
"'/push_subscriptions/{id}'",
",",
"id",
"=",
"subscription_id",
",",
"client_id",
"=",
"client_id",
... | Unsubscribe from webhook events for an existing subscription.
http://strava.github.io/api/partner/v3/events/#delete-a-subscription
:param subscription_id: ID of subscription to remove.
:type subscription_id: int
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str | [
"Unsubscribe",
"from",
"webhook",
"events",
"for",
"an",
"existing",
"subscription",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1568-L1584 | train | 202,968 |
hozn/stravalib | stravalib/client.py | BatchedResultsIterator._fill_buffer | def _fill_buffer(self):
"""
Fills the internal size-50 buffer from Strava API.
"""
# If we cannot fetch anymore from the server then we're done here.
if self._all_results_fetched:
self._eof()
raw_results = self.result_fetcher(page=self._page, per_page=self.per_page)
entities = []
for raw in raw_results:
entities.append(self.entity.deserialize(raw, bind_client=self.bind_client))
self._buffer = collections.deque(entities)
self.log.debug("Requested page {0} (got: {1} items)".format(self._page,
len(self._buffer)))
if len(self._buffer) < self.per_page:
self._all_results_fetched = True
self._page += 1 | python | def _fill_buffer(self):
"""
Fills the internal size-50 buffer from Strava API.
"""
# If we cannot fetch anymore from the server then we're done here.
if self._all_results_fetched:
self._eof()
raw_results = self.result_fetcher(page=self._page, per_page=self.per_page)
entities = []
for raw in raw_results:
entities.append(self.entity.deserialize(raw, bind_client=self.bind_client))
self._buffer = collections.deque(entities)
self.log.debug("Requested page {0} (got: {1} items)".format(self._page,
len(self._buffer)))
if len(self._buffer) < self.per_page:
self._all_results_fetched = True
self._page += 1 | [
"def",
"_fill_buffer",
"(",
"self",
")",
":",
"# If we cannot fetch anymore from the server then we're done here.",
"if",
"self",
".",
"_all_results_fetched",
":",
"self",
".",
"_eof",
"(",
")",
"raw_results",
"=",
"self",
".",
"result_fetcher",
"(",
"page",
"=",
"s... | Fills the internal size-50 buffer from Strava API. | [
"Fills",
"the",
"internal",
"size",
"-",
"50",
"buffer",
"from",
"Strava",
"API",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1637-L1658 | train | 202,969 |
hozn/stravalib | stravalib/client.py | ActivityUploader.update_from_response | def update_from_response(self, response, raise_exc=True):
"""
Updates internal state of object.
:param response: The response object (dict).
:type response: :py:class:`dict`
:param raise_exc: Whether to raise an exception if the response
indicates an error state. (default True)
:type raise_exc: bool
:raise stravalib.exc.ActivityUploadFailed: If the response indicates an error and raise_exc is True.
"""
self.upload_id = response.get('id')
self.external_id = response.get('external_id')
self.activity_id = response.get('activity_id')
self.status = response.get('status') or response.get('message')
if response.get('error'):
self.error = response.get('error')
elif response.get('errors'):
# This appears to be an undocumented API; ths is a bit of a hack for now.
self.error = str(response.get('errors'))
else:
self.error = None
if raise_exc:
self.raise_for_error() | python | def update_from_response(self, response, raise_exc=True):
"""
Updates internal state of object.
:param response: The response object (dict).
:type response: :py:class:`dict`
:param raise_exc: Whether to raise an exception if the response
indicates an error state. (default True)
:type raise_exc: bool
:raise stravalib.exc.ActivityUploadFailed: If the response indicates an error and raise_exc is True.
"""
self.upload_id = response.get('id')
self.external_id = response.get('external_id')
self.activity_id = response.get('activity_id')
self.status = response.get('status') or response.get('message')
if response.get('error'):
self.error = response.get('error')
elif response.get('errors'):
# This appears to be an undocumented API; ths is a bit of a hack for now.
self.error = str(response.get('errors'))
else:
self.error = None
if raise_exc:
self.raise_for_error() | [
"def",
"update_from_response",
"(",
"self",
",",
"response",
",",
"raise_exc",
"=",
"True",
")",
":",
"self",
".",
"upload_id",
"=",
"response",
".",
"get",
"(",
"'id'",
")",
"self",
".",
"external_id",
"=",
"response",
".",
"get",
"(",
"'external_id'",
... | Updates internal state of object.
:param response: The response object (dict).
:type response: :py:class:`dict`
:param raise_exc: Whether to raise an exception if the response
indicates an error state. (default True)
:type raise_exc: bool
:raise stravalib.exc.ActivityUploadFailed: If the response indicates an error and raise_exc is True. | [
"Updates",
"internal",
"state",
"of",
"object",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1706-L1731 | train | 202,970 |
hozn/stravalib | stravalib/client.py | ActivityUploader.wait | def wait(self, timeout=None, poll_interval=1.0):
"""
Wait for the upload to complete or to err out.
Will return the resulting Activity or raise an exception if the upload fails.
:param timeout: The max seconds to wait. Will raise TimeoutExceeded
exception if this time passes without success or error response.
:type timeout: float
:param poll_interval: How long to wait between upload checks. Strava
recommends 1s minimum. (default 1.0s)
:type poll_interval: float
:return: The uploaded Activity object (fetched from server)
:rtype: :class:`stravalib.model.Activity`
:raise stravalib.exc.TimeoutExceeded: If a timeout was specified and
activity is still processing after
timeout has elapsed.
:raise stravalib.exc.ActivityUploadFailed: If the poll returns an error.
"""
start = time.time()
while self.activity_id is None:
self.poll()
time.sleep(poll_interval)
if timeout and (time.time() - start) > timeout:
raise exc.TimeoutExceeded()
# If we got this far, we must have an activity!
return self.client.get_activity(self.activity_id) | python | def wait(self, timeout=None, poll_interval=1.0):
"""
Wait for the upload to complete or to err out.
Will return the resulting Activity or raise an exception if the upload fails.
:param timeout: The max seconds to wait. Will raise TimeoutExceeded
exception if this time passes without success or error response.
:type timeout: float
:param poll_interval: How long to wait between upload checks. Strava
recommends 1s minimum. (default 1.0s)
:type poll_interval: float
:return: The uploaded Activity object (fetched from server)
:rtype: :class:`stravalib.model.Activity`
:raise stravalib.exc.TimeoutExceeded: If a timeout was specified and
activity is still processing after
timeout has elapsed.
:raise stravalib.exc.ActivityUploadFailed: If the poll returns an error.
"""
start = time.time()
while self.activity_id is None:
self.poll()
time.sleep(poll_interval)
if timeout and (time.time() - start) > timeout:
raise exc.TimeoutExceeded()
# If we got this far, we must have an activity!
return self.client.get_activity(self.activity_id) | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"poll_interval",
"=",
"1.0",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"self",
".",
"activity_id",
"is",
"None",
":",
"self",
".",
"poll",
"(",
")",
"time",
".",
... | Wait for the upload to complete or to err out.
Will return the resulting Activity or raise an exception if the upload fails.
:param timeout: The max seconds to wait. Will raise TimeoutExceeded
exception if this time passes without success or error response.
:type timeout: float
:param poll_interval: How long to wait between upload checks. Strava
recommends 1s minimum. (default 1.0s)
:type poll_interval: float
:return: The uploaded Activity object (fetched from server)
:rtype: :class:`stravalib.model.Activity`
:raise stravalib.exc.TimeoutExceeded: If a timeout was specified and
activity is still processing after
timeout has elapsed.
:raise stravalib.exc.ActivityUploadFailed: If the poll returns an error. | [
"Wait",
"for",
"the",
"upload",
"to",
"complete",
"or",
"to",
"err",
"out",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1764-L1793 | train | 202,971 |
hozn/stravalib | stravalib/model.py | Activity.full_photos | def full_photos(self):
"""
Gets a list of photos using default options.
:class:`list` of :class:`stravalib.model.ActivityPhoto` objects for this activity.
"""
if self._photos is None:
if self.total_photo_count > 0:
self.assert_bind_client()
self._photos = self.bind_client.get_activity_photos(self.id, only_instagram=False)
else:
self._photos = []
return self._photos | python | def full_photos(self):
"""
Gets a list of photos using default options.
:class:`list` of :class:`stravalib.model.ActivityPhoto` objects for this activity.
"""
if self._photos is None:
if self.total_photo_count > 0:
self.assert_bind_client()
self._photos = self.bind_client.get_activity_photos(self.id, only_instagram=False)
else:
self._photos = []
return self._photos | [
"def",
"full_photos",
"(",
"self",
")",
":",
"if",
"self",
".",
"_photos",
"is",
"None",
":",
"if",
"self",
".",
"total_photo_count",
">",
"0",
":",
"self",
".",
"assert_bind_client",
"(",
")",
"self",
".",
"_photos",
"=",
"self",
".",
"bind_client",
"... | Gets a list of photos using default options.
:class:`list` of :class:`stravalib.model.ActivityPhoto` objects for this activity. | [
"Gets",
"a",
"list",
"of",
"photos",
"using",
"default",
"options",
"."
] | 5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/model.py#L909-L921 | train | 202,972 |
coleifer/walrus | walrus/cache.py | Cache.get | def get(self, key, default=None):
"""
Retreive a value from the cache. In the event the value
does not exist, return the ``default``.
"""
key = self.make_key(key)
if self.debug:
return default
try:
value = self.database[key]
except KeyError:
self.metrics['misses'] += 1
return default
else:
self.metrics['hits'] += 1
return pickle.loads(value) | python | def get(self, key, default=None):
"""
Retreive a value from the cache. In the event the value
does not exist, return the ``default``.
"""
key = self.make_key(key)
if self.debug:
return default
try:
value = self.database[key]
except KeyError:
self.metrics['misses'] += 1
return default
else:
self.metrics['hits'] += 1
return pickle.loads(value) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"make_key",
"(",
"key",
")",
"if",
"self",
".",
"debug",
":",
"return",
"default",
"try",
":",
"value",
"=",
"self",
".",
"database",
"[",
"key... | Retreive a value from the cache. In the event the value
does not exist, return the ``default``. | [
"Retreive",
"a",
"value",
"from",
"the",
"cache",
".",
"In",
"the",
"event",
"the",
"value",
"does",
"not",
"exist",
"return",
"the",
"default",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/cache.py#L44-L61 | train | 202,973 |
coleifer/walrus | walrus/cache.py | Cache.set | def set(self, key, value, timeout=None):
"""
Cache the given ``value`` in the specified ``key``. If no
timeout is specified, the default timeout will be used.
"""
key = self.make_key(key)
if timeout is None:
timeout = self.default_timeout
if self.debug:
return True
pickled_value = pickle.dumps(value)
self.metrics['writes'] += 1
if timeout:
return self.database.setex(key, int(timeout), pickled_value)
else:
return self.database.set(key, pickled_value) | python | def set(self, key, value, timeout=None):
"""
Cache the given ``value`` in the specified ``key``. If no
timeout is specified, the default timeout will be used.
"""
key = self.make_key(key)
if timeout is None:
timeout = self.default_timeout
if self.debug:
return True
pickled_value = pickle.dumps(value)
self.metrics['writes'] += 1
if timeout:
return self.database.setex(key, int(timeout), pickled_value)
else:
return self.database.set(key, pickled_value) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"timeout",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"make_key",
"(",
"key",
")",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"default_timeout",
"if",
"self",
".",... | Cache the given ``value`` in the specified ``key``. If no
timeout is specified, the default timeout will be used. | [
"Cache",
"the",
"given",
"value",
"in",
"the",
"specified",
"key",
".",
"If",
"no",
"timeout",
"is",
"specified",
"the",
"default",
"timeout",
"will",
"be",
"used",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/cache.py#L63-L80 | train | 202,974 |
coleifer/walrus | walrus/cache.py | Cache.delete | def delete(self, key):
"""Remove the given key from the cache."""
if not self.debug:
self.database.delete(self.make_key(key)) | python | def delete(self, key):
"""Remove the given key from the cache."""
if not self.debug:
self.database.delete(self.make_key(key)) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"debug",
":",
"self",
".",
"database",
".",
"delete",
"(",
"self",
".",
"make_key",
"(",
"key",
")",
")"
] | Remove the given key from the cache. | [
"Remove",
"the",
"given",
"key",
"from",
"the",
"cache",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/cache.py#L82-L85 | train | 202,975 |
coleifer/walrus | walrus/cache.py | Cache.flush | def flush(self):
"""Remove all cached objects from the database."""
keys = list(self.keys())
if keys:
return self.database.delete(*keys) | python | def flush(self):
"""Remove all cached objects from the database."""
keys = list(self.keys())
if keys:
return self.database.delete(*keys) | [
"def",
"flush",
"(",
"self",
")",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
"if",
"keys",
":",
"return",
"self",
".",
"database",
".",
"delete",
"(",
"*",
"keys",
")"
] | Remove all cached objects from the database. | [
"Remove",
"all",
"cached",
"objects",
"from",
"the",
"database",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/cache.py#L93-L97 | train | 202,976 |
coleifer/walrus | walrus/cache.py | Cache.cached_property | def cached_property(self, key_fn=_key_fn, timeout=None):
"""
Decorator that will transparently cache calls to the wrapped
method. The method will be exposed as a property.
Usage::
cache = Cache(my_database)
class Clock(object):
@cache.cached_property()
def now(self):
return datetime.datetime.now()
clock = Clock()
print clock.now
"""
this = self
class _cached_property(object):
def __init__(self, fn):
self._fn = this.cached(key_fn, timeout)(fn)
def __get__(self, instance, instance_type=None):
if instance is None:
return self
return self._fn(instance)
def __delete__(self, obj):
self._fn.bust(obj)
def __set__(self, instance, value):
raise ValueError('Cannot set value of a cached property.')
def decorator(fn):
return _cached_property(fn)
return decorator | python | def cached_property(self, key_fn=_key_fn, timeout=None):
"""
Decorator that will transparently cache calls to the wrapped
method. The method will be exposed as a property.
Usage::
cache = Cache(my_database)
class Clock(object):
@cache.cached_property()
def now(self):
return datetime.datetime.now()
clock = Clock()
print clock.now
"""
this = self
class _cached_property(object):
def __init__(self, fn):
self._fn = this.cached(key_fn, timeout)(fn)
def __get__(self, instance, instance_type=None):
if instance is None:
return self
return self._fn(instance)
def __delete__(self, obj):
self._fn.bust(obj)
def __set__(self, instance, value):
raise ValueError('Cannot set value of a cached property.')
def decorator(fn):
return _cached_property(fn)
return decorator | [
"def",
"cached_property",
"(",
"self",
",",
"key_fn",
"=",
"_key_fn",
",",
"timeout",
"=",
"None",
")",
":",
"this",
"=",
"self",
"class",
"_cached_property",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
... | Decorator that will transparently cache calls to the wrapped
method. The method will be exposed as a property.
Usage::
cache = Cache(my_database)
class Clock(object):
@cache.cached_property()
def now(self):
return datetime.datetime.now()
clock = Clock()
print clock.now | [
"Decorator",
"that",
"will",
"transparently",
"cache",
"calls",
"to",
"the",
"wrapped",
"method",
".",
"The",
"method",
"will",
"be",
"exposed",
"as",
"a",
"property",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/cache.py#L178-L215 | train | 202,977 |
coleifer/walrus | walrus/cache.py | Cache.cache_async | def cache_async(self, key_fn=_key_fn, timeout=3600):
"""
Decorator that will execute the cached function in a separate
thread. The function will immediately return, returning a
callable to the user. This callable can be used to check for
a return value.
For details, see the :ref:`cache-async` section of the docs.
:param key_fn: Function used to generate cache key.
:param int timeout: Cache timeout in seconds.
:returns: A new function which can be called to retrieve the
return value of the decorated function.
"""
def decorator(fn):
wrapped = self.cached(key_fn, timeout)(fn)
@wraps(fn)
def inner(*args, **kwargs):
q = Queue()
def _sub_fn():
q.put(wrapped(*args, **kwargs))
def _get_value(block=True, timeout=None):
if not hasattr(_get_value, '_return_value'):
result = q.get(block=block, timeout=timeout)
_get_value._return_value = result
return _get_value._return_value
thread = threading.Thread(target=_sub_fn)
thread.start()
return _get_value
return inner
return decorator | python | def cache_async(self, key_fn=_key_fn, timeout=3600):
"""
Decorator that will execute the cached function in a separate
thread. The function will immediately return, returning a
callable to the user. This callable can be used to check for
a return value.
For details, see the :ref:`cache-async` section of the docs.
:param key_fn: Function used to generate cache key.
:param int timeout: Cache timeout in seconds.
:returns: A new function which can be called to retrieve the
return value of the decorated function.
"""
def decorator(fn):
wrapped = self.cached(key_fn, timeout)(fn)
@wraps(fn)
def inner(*args, **kwargs):
q = Queue()
def _sub_fn():
q.put(wrapped(*args, **kwargs))
def _get_value(block=True, timeout=None):
if not hasattr(_get_value, '_return_value'):
result = q.get(block=block, timeout=timeout)
_get_value._return_value = result
return _get_value._return_value
thread = threading.Thread(target=_sub_fn)
thread.start()
return _get_value
return inner
return decorator | [
"def",
"cache_async",
"(",
"self",
",",
"key_fn",
"=",
"_key_fn",
",",
"timeout",
"=",
"3600",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"wrapped",
"=",
"self",
".",
"cached",
"(",
"key_fn",
",",
"timeout",
")",
"(",
"fn",
")",
"@",
"wraps... | Decorator that will execute the cached function in a separate
thread. The function will immediately return, returning a
callable to the user. This callable can be used to check for
a return value.
For details, see the :ref:`cache-async` section of the docs.
:param key_fn: Function used to generate cache key.
:param int timeout: Cache timeout in seconds.
:returns: A new function which can be called to retrieve the
return value of the decorated function. | [
"Decorator",
"that",
"will",
"execute",
"the",
"cached",
"function",
"in",
"a",
"separate",
"thread",
".",
"The",
"function",
"will",
"immediately",
"return",
"returning",
"a",
"callable",
"to",
"the",
"user",
".",
"This",
"callable",
"can",
"be",
"used",
"t... | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/cache.py#L217-L249 | train | 202,978 |
coleifer/walrus | walrus/autocomplete.py | Autocomplete.store | def store(self, obj_id, title=None, data=None, obj_type=None):
"""
Store data in the autocomplete index.
:param obj_id: Either a unique identifier for the object
being indexed or the word/phrase to be indexed.
:param title: The word or phrase to be indexed. If not
provided, the ``obj_id`` will be used as the title.
:param data: Arbitrary data to index, which will be
returned when searching for results. If not provided,
this value will default to the title being indexed.
:param obj_type: Optional object type. Since results can be
boosted by type, you might find it useful to specify this
when storing multiple types of objects.
You have the option of storing several types of data as
defined by the parameters. At the minimum, you can specify
an ``obj_id``, which will be the word or phrase you wish to
index. Alternatively, if for instance you were indexing blog
posts, you might specify all parameters.
"""
if title is None:
title = obj_id
if data is None:
data = title
obj_type = obj_type or ''
if self._use_json:
data = json.dumps(data)
combined_id = self.object_key(obj_id, obj_type)
if self.exists(obj_id, obj_type):
stored_title = self._title_data[combined_id]
if stored_title == title:
self._data[combined_id] = data
return
else:
self.remove(obj_id, obj_type)
self._data[combined_id] = data
self._title_data[combined_id] = title
clean_title = ' '.join(self.tokenize_title(title))
title_score = self.score_token(clean_title)
for idx, word in enumerate(self.tokenize_title(title)):
word_score = self.score_token(word)
position_score = word_score + (self._offset * idx)
key_score = position_score + title_score
for substring in self.substrings(word):
self.database.zadd(self.word_key(substring),
{combined_id: key_score})
return True | python | def store(self, obj_id, title=None, data=None, obj_type=None):
"""
Store data in the autocomplete index.
:param obj_id: Either a unique identifier for the object
being indexed or the word/phrase to be indexed.
:param title: The word or phrase to be indexed. If not
provided, the ``obj_id`` will be used as the title.
:param data: Arbitrary data to index, which will be
returned when searching for results. If not provided,
this value will default to the title being indexed.
:param obj_type: Optional object type. Since results can be
boosted by type, you might find it useful to specify this
when storing multiple types of objects.
You have the option of storing several types of data as
defined by the parameters. At the minimum, you can specify
an ``obj_id``, which will be the word or phrase you wish to
index. Alternatively, if for instance you were indexing blog
posts, you might specify all parameters.
"""
if title is None:
title = obj_id
if data is None:
data = title
obj_type = obj_type or ''
if self._use_json:
data = json.dumps(data)
combined_id = self.object_key(obj_id, obj_type)
if self.exists(obj_id, obj_type):
stored_title = self._title_data[combined_id]
if stored_title == title:
self._data[combined_id] = data
return
else:
self.remove(obj_id, obj_type)
self._data[combined_id] = data
self._title_data[combined_id] = title
clean_title = ' '.join(self.tokenize_title(title))
title_score = self.score_token(clean_title)
for idx, word in enumerate(self.tokenize_title(title)):
word_score = self.score_token(word)
position_score = word_score + (self._offset * idx)
key_score = position_score + title_score
for substring in self.substrings(word):
self.database.zadd(self.word_key(substring),
{combined_id: key_score})
return True | [
"def",
"store",
"(",
"self",
",",
"obj_id",
",",
"title",
"=",
"None",
",",
"data",
"=",
"None",
",",
"obj_type",
"=",
"None",
")",
":",
"if",
"title",
"is",
"None",
":",
"title",
"=",
"obj_id",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"titl... | Store data in the autocomplete index.
:param obj_id: Either a unique identifier for the object
being indexed or the word/phrase to be indexed.
:param title: The word or phrase to be indexed. If not
provided, the ``obj_id`` will be used as the title.
:param data: Arbitrary data to index, which will be
returned when searching for results. If not provided,
this value will default to the title being indexed.
:param obj_type: Optional object type. Since results can be
boosted by type, you might find it useful to specify this
when storing multiple types of objects.
You have the option of storing several types of data as
defined by the parameters. At the minimum, you can specify
an ``obj_id``, which will be the word or phrase you wish to
index. Alternatively, if for instance you were indexing blog
posts, you might specify all parameters. | [
"Store",
"data",
"in",
"the",
"autocomplete",
"index",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/autocomplete.py#L93-L147 | train | 202,979 |
coleifer/walrus | walrus/autocomplete.py | Autocomplete.exists | def exists(self, obj_id, obj_type=None):
"""
Return whether the given object exists in the search index.
:param obj_id: The object's unique identifier.
:param obj_type: The object's type.
"""
return self.object_key(obj_id, obj_type) in self._data | python | def exists(self, obj_id, obj_type=None):
"""
Return whether the given object exists in the search index.
:param obj_id: The object's unique identifier.
:param obj_type: The object's type.
"""
return self.object_key(obj_id, obj_type) in self._data | [
"def",
"exists",
"(",
"self",
",",
"obj_id",
",",
"obj_type",
"=",
"None",
")",
":",
"return",
"self",
".",
"object_key",
"(",
"obj_id",
",",
"obj_type",
")",
"in",
"self",
".",
"_data"
] | Return whether the given object exists in the search index.
:param obj_id: The object's unique identifier.
:param obj_type: The object's type. | [
"Return",
"whether",
"the",
"given",
"object",
"exists",
"in",
"the",
"search",
"index",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/autocomplete.py#L175-L182 | train | 202,980 |
coleifer/walrus | walrus/autocomplete.py | Autocomplete.boost_object | def boost_object(self, obj_id=None, obj_type=None, multiplier=1.1,
relative=True):
"""
Boost search results for the given object or type by the
amount specified. When the ``multiplier`` is greater than
1, the results will percolate to the top. Values between
0 and 1 will percolate results to the bottom.
Either an ``obj_id`` or ``obj_type`` (or both) must be
specified.
:param obj_id: An object's unique identifier (optional).
:param obj_type: The object's type (optional).
:param multiplier: A positive floating-point number.
:param relative: If ``True``, then any pre-existing saved
boost will be updated using the given multiplier.
Examples:
.. code-block:: python
# Make all objects of type=photos percolate to top.
ac.boost_object(obj_type='photo', multiplier=2.0)
# Boost a particularly popular blog entry.
ac.boost_object(
popular_entry.id,
'entry',
multipler=5.0,
relative=False)
"""
combined_id = self.object_key(obj_id or '', obj_type or '')
if relative:
current = float(self._boosts[combined_id] or 1.0)
self._boosts[combined_id] = current * multiplier
else:
self._boosts[combined_id] = multiplier | python | def boost_object(self, obj_id=None, obj_type=None, multiplier=1.1,
relative=True):
"""
Boost search results for the given object or type by the
amount specified. When the ``multiplier`` is greater than
1, the results will percolate to the top. Values between
0 and 1 will percolate results to the bottom.
Either an ``obj_id`` or ``obj_type`` (or both) must be
specified.
:param obj_id: An object's unique identifier (optional).
:param obj_type: The object's type (optional).
:param multiplier: A positive floating-point number.
:param relative: If ``True``, then any pre-existing saved
boost will be updated using the given multiplier.
Examples:
.. code-block:: python
# Make all objects of type=photos percolate to top.
ac.boost_object(obj_type='photo', multiplier=2.0)
# Boost a particularly popular blog entry.
ac.boost_object(
popular_entry.id,
'entry',
multipler=5.0,
relative=False)
"""
combined_id = self.object_key(obj_id or '', obj_type or '')
if relative:
current = float(self._boosts[combined_id] or 1.0)
self._boosts[combined_id] = current * multiplier
else:
self._boosts[combined_id] = multiplier | [
"def",
"boost_object",
"(",
"self",
",",
"obj_id",
"=",
"None",
",",
"obj_type",
"=",
"None",
",",
"multiplier",
"=",
"1.1",
",",
"relative",
"=",
"True",
")",
":",
"combined_id",
"=",
"self",
".",
"object_key",
"(",
"obj_id",
"or",
"''",
",",
"obj_typ... | Boost search results for the given object or type by the
amount specified. When the ``multiplier`` is greater than
1, the results will percolate to the top. Values between
0 and 1 will percolate results to the bottom.
Either an ``obj_id`` or ``obj_type`` (or both) must be
specified.
:param obj_id: An object's unique identifier (optional).
:param obj_type: The object's type (optional).
:param multiplier: A positive floating-point number.
:param relative: If ``True``, then any pre-existing saved
boost will be updated using the given multiplier.
Examples:
.. code-block:: python
# Make all objects of type=photos percolate to top.
ac.boost_object(obj_type='photo', multiplier=2.0)
# Boost a particularly popular blog entry.
ac.boost_object(
popular_entry.id,
'entry',
multipler=5.0,
relative=False) | [
"Boost",
"search",
"results",
"for",
"the",
"given",
"object",
"or",
"type",
"by",
"the",
"amount",
"specified",
".",
"When",
"the",
"multiplier",
"is",
"greater",
"than",
"1",
"the",
"results",
"will",
"percolate",
"to",
"the",
"top",
".",
"Values",
"betw... | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/autocomplete.py#L184-L220 | train | 202,981 |
coleifer/walrus | walrus/autocomplete.py | Autocomplete.list_data | def list_data(self):
"""
Return all the data stored in the autocomplete index. If the data was
stored as serialized JSON, then it will be de-serialized before being
returned.
:rtype: list
"""
fn = (lambda v: json.loads(decode(v))) if self._use_json else decode
return map(fn, self._data.values()) | python | def list_data(self):
"""
Return all the data stored in the autocomplete index. If the data was
stored as serialized JSON, then it will be de-serialized before being
returned.
:rtype: list
"""
fn = (lambda v: json.loads(decode(v))) if self._use_json else decode
return map(fn, self._data.values()) | [
"def",
"list_data",
"(",
"self",
")",
":",
"fn",
"=",
"(",
"lambda",
"v",
":",
"json",
".",
"loads",
"(",
"decode",
"(",
"v",
")",
")",
")",
"if",
"self",
".",
"_use_json",
"else",
"decode",
"return",
"map",
"(",
"fn",
",",
"self",
".",
"_data",
... | Return all the data stored in the autocomplete index. If the data was
stored as serialized JSON, then it will be de-serialized before being
returned.
:rtype: list | [
"Return",
"all",
"the",
"data",
"stored",
"in",
"the",
"autocomplete",
"index",
".",
"If",
"the",
"data",
"was",
"stored",
"as",
"serialized",
"JSON",
"then",
"it",
"will",
"be",
"de",
"-",
"serialized",
"before",
"being",
"returned",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/autocomplete.py#L312-L321 | train | 202,982 |
coleifer/walrus | walrus/autocomplete.py | Autocomplete.flush | def flush(self, batch_size=1000):
"""
Delete all autocomplete indexes and metadata.
"""
keys = self.database.keys(self.namespace + ':*')
for i in range(0, len(keys), batch_size):
self.database.delete(*keys[i:i + batch_size]) | python | def flush(self, batch_size=1000):
"""
Delete all autocomplete indexes and metadata.
"""
keys = self.database.keys(self.namespace + ':*')
for i in range(0, len(keys), batch_size):
self.database.delete(*keys[i:i + batch_size]) | [
"def",
"flush",
"(",
"self",
",",
"batch_size",
"=",
"1000",
")",
":",
"keys",
"=",
"self",
".",
"database",
".",
"keys",
"(",
"self",
".",
"namespace",
"+",
"':*'",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"keys",
")",
",",
"... | Delete all autocomplete indexes and metadata. | [
"Delete",
"all",
"autocomplete",
"indexes",
"and",
"metadata",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/autocomplete.py#L331-L337 | train | 202,983 |
coleifer/walrus | walrus/search/__init__.py | Tokenizer.metaphone | def metaphone(self, words):
"""
Apply the double metaphone algorithm to the given words.
Using metaphone allows the search index to tolerate
misspellings and small typos.
Example::
>>> from walrus.search.metaphone import dm as metaphone
>>> print metaphone('walrus')
('ALRS', 'FLRS')
>>> print metaphone('python')
('P0N', 'PTN')
>>> print metaphone('pithonn')
('P0N', 'PTN')
"""
for word in words:
r = 0
for w in double_metaphone(word):
if w:
w = w.strip()
if w:
r += 1
yield w
if not r:
yield word | python | def metaphone(self, words):
"""
Apply the double metaphone algorithm to the given words.
Using metaphone allows the search index to tolerate
misspellings and small typos.
Example::
>>> from walrus.search.metaphone import dm as metaphone
>>> print metaphone('walrus')
('ALRS', 'FLRS')
>>> print metaphone('python')
('P0N', 'PTN')
>>> print metaphone('pithonn')
('P0N', 'PTN')
"""
for word in words:
r = 0
for w in double_metaphone(word):
if w:
w = w.strip()
if w:
r += 1
yield w
if not r:
yield word | [
"def",
"metaphone",
"(",
"self",
",",
"words",
")",
":",
"for",
"word",
"in",
"words",
":",
"r",
"=",
"0",
"for",
"w",
"in",
"double_metaphone",
"(",
"word",
")",
":",
"if",
"w",
":",
"w",
"=",
"w",
".",
"strip",
"(",
")",
"if",
"w",
":",
"r"... | Apply the double metaphone algorithm to the given words.
Using metaphone allows the search index to tolerate
misspellings and small typos.
Example::
>>> from walrus.search.metaphone import dm as metaphone
>>> print metaphone('walrus')
('ALRS', 'FLRS')
>>> print metaphone('python')
('P0N', 'PTN')
>>> print metaphone('pithonn')
('P0N', 'PTN') | [
"Apply",
"the",
"double",
"metaphone",
"algorithm",
"to",
"the",
"given",
"words",
".",
"Using",
"metaphone",
"allows",
"the",
"search",
"index",
"to",
"tolerate",
"misspellings",
"and",
"small",
"typos",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/search/__init__.py#L49-L76 | train | 202,984 |
coleifer/walrus | walrus/search/__init__.py | Tokenizer.tokenize | def tokenize(self, value):
"""
Split the incoming value into tokens and process each token,
optionally stemming or running metaphone.
:returns: A ``dict`` mapping token to score. The score is
based on the relative frequency of the word in the
document.
"""
words = self.split_phrase(decode(value).lower())
if self._stopwords:
words = [w for w in words if w not in self._stopwords]
if self._min_word_length:
words = [w for w in words if len(w) >= self._min_word_length]
fraction = 1. / (len(words) + 1) # Prevent division by zero.
# Apply optional transformations.
if self._use_stemmer:
words = self.stem(words)
if self._use_metaphone:
words = self.metaphone(words)
scores = {}
for word in words:
scores.setdefault(word, 0)
scores[word] += fraction
return scores | python | def tokenize(self, value):
"""
Split the incoming value into tokens and process each token,
optionally stemming or running metaphone.
:returns: A ``dict`` mapping token to score. The score is
based on the relative frequency of the word in the
document.
"""
words = self.split_phrase(decode(value).lower())
if self._stopwords:
words = [w for w in words if w not in self._stopwords]
if self._min_word_length:
words = [w for w in words if len(w) >= self._min_word_length]
fraction = 1. / (len(words) + 1) # Prevent division by zero.
# Apply optional transformations.
if self._use_stemmer:
words = self.stem(words)
if self._use_metaphone:
words = self.metaphone(words)
scores = {}
for word in words:
scores.setdefault(word, 0)
scores[word] += fraction
return scores | [
"def",
"tokenize",
"(",
"self",
",",
"value",
")",
":",
"words",
"=",
"self",
".",
"split_phrase",
"(",
"decode",
"(",
"value",
")",
".",
"lower",
"(",
")",
")",
"if",
"self",
".",
"_stopwords",
":",
"words",
"=",
"[",
"w",
"for",
"w",
"in",
"wor... | Split the incoming value into tokens and process each token,
optionally stemming or running metaphone.
:returns: A ``dict`` mapping token to score. The score is
based on the relative frequency of the word in the
document. | [
"Split",
"the",
"incoming",
"value",
"into",
"tokens",
"and",
"process",
"each",
"token",
"optionally",
"stemming",
"or",
"running",
"metaphone",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/search/__init__.py#L78-L105 | train | 202,985 |
coleifer/walrus | walrus/containers.py | Container.expire | def expire(self, ttl=None):
"""
Expire the given key in the given number of seconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted.
"""
if ttl is not None:
self.database.expire(self.key, ttl)
else:
self.database.persist(self.key) | python | def expire(self, ttl=None):
"""
Expire the given key in the given number of seconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted.
"""
if ttl is not None:
self.database.expire(self.key, ttl)
else:
self.database.persist(self.key) | [
"def",
"expire",
"(",
"self",
",",
"ttl",
"=",
"None",
")",
":",
"if",
"ttl",
"is",
"not",
"None",
":",
"self",
".",
"database",
".",
"expire",
"(",
"self",
".",
"key",
",",
"ttl",
")",
"else",
":",
"self",
".",
"database",
".",
"persist",
"(",
... | Expire the given key in the given number of seconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted. | [
"Expire",
"the",
"given",
"key",
"in",
"the",
"given",
"number",
"of",
"seconds",
".",
"If",
"ttl",
"is",
"None",
"then",
"any",
"expiry",
"will",
"be",
"cleared",
"and",
"key",
"will",
"be",
"persisted",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L57-L66 | train | 202,986 |
coleifer/walrus | walrus/containers.py | Container.pexpire | def pexpire(self, ttl=None):
"""
Expire the given key in the given number of milliseconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted.
"""
if ttl is not None:
self.database.pexpire(self.key, ttl)
else:
self.database.persist(self.key) | python | def pexpire(self, ttl=None):
"""
Expire the given key in the given number of milliseconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted.
"""
if ttl is not None:
self.database.pexpire(self.key, ttl)
else:
self.database.persist(self.key) | [
"def",
"pexpire",
"(",
"self",
",",
"ttl",
"=",
"None",
")",
":",
"if",
"ttl",
"is",
"not",
"None",
":",
"self",
".",
"database",
".",
"pexpire",
"(",
"self",
".",
"key",
",",
"ttl",
")",
"else",
":",
"self",
".",
"database",
".",
"persist",
"(",... | Expire the given key in the given number of milliseconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted. | [
"Expire",
"the",
"given",
"key",
"in",
"the",
"given",
"number",
"of",
"milliseconds",
".",
"If",
"ttl",
"is",
"None",
"then",
"any",
"expiry",
"will",
"be",
"cleared",
"and",
"key",
"will",
"be",
"persisted",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L68-L77 | train | 202,987 |
coleifer/walrus | walrus/containers.py | Hash.search | def search(self, pattern, count=None):
"""
Search the keys of the given hash using the specified pattern.
:param str pattern: Pattern used to match keys.
:param int count: Limit number of results returned.
:returns: An iterator yielding matching key/value pairs.
"""
return self._scan(match=pattern, count=count) | python | def search(self, pattern, count=None):
"""
Search the keys of the given hash using the specified pattern.
:param str pattern: Pattern used to match keys.
:param int count: Limit number of results returned.
:returns: An iterator yielding matching key/value pairs.
"""
return self._scan(match=pattern, count=count) | [
"def",
"search",
"(",
"self",
",",
"pattern",
",",
"count",
"=",
"None",
")",
":",
"return",
"self",
".",
"_scan",
"(",
"match",
"=",
"pattern",
",",
"count",
"=",
"count",
")"
] | Search the keys of the given hash using the specified pattern.
:param str pattern: Pattern used to match keys.
:param int count: Limit number of results returned.
:returns: An iterator yielding matching key/value pairs. | [
"Search",
"the",
"keys",
"of",
"the",
"given",
"hash",
"using",
"the",
"specified",
"pattern",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L156-L164 | train | 202,988 |
coleifer/walrus | walrus/containers.py | Hash.from_dict | def from_dict(cls, database, key, data, clear=False):
"""
Create and populate a Hash object from a data dictionary.
"""
hsh = cls(database, key)
if clear:
hsh.clear()
hsh.update(data)
return hsh | python | def from_dict(cls, database, key, data, clear=False):
"""
Create and populate a Hash object from a data dictionary.
"""
hsh = cls(database, key)
if clear:
hsh.clear()
hsh.update(data)
return hsh | [
"def",
"from_dict",
"(",
"cls",
",",
"database",
",",
"key",
",",
"data",
",",
"clear",
"=",
"False",
")",
":",
"hsh",
"=",
"cls",
"(",
"database",
",",
"key",
")",
"if",
"clear",
":",
"hsh",
".",
"clear",
"(",
")",
"hsh",
".",
"update",
"(",
"... | Create and populate a Hash object from a data dictionary. | [
"Create",
"and",
"populate",
"a",
"Hash",
"object",
"from",
"a",
"data",
"dictionary",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L212-L220 | train | 202,989 |
coleifer/walrus | walrus/containers.py | List.as_list | def as_list(self, decode=False):
"""
Return a list containing all the items in the list.
"""
items = self.database.lrange(self.key, 0, -1)
return [_decode(item) for item in items] if decode else items | python | def as_list(self, decode=False):
"""
Return a list containing all the items in the list.
"""
items = self.database.lrange(self.key, 0, -1)
return [_decode(item) for item in items] if decode else items | [
"def",
"as_list",
"(",
"self",
",",
"decode",
"=",
"False",
")",
":",
"items",
"=",
"self",
".",
"database",
".",
"lrange",
"(",
"self",
".",
"key",
",",
"0",
",",
"-",
"1",
")",
"return",
"[",
"_decode",
"(",
"item",
")",
"for",
"item",
"in",
... | Return a list containing all the items in the list. | [
"Return",
"a",
"list",
"containing",
"all",
"the",
"items",
"in",
"the",
"list",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L347-L352 | train | 202,990 |
coleifer/walrus | walrus/containers.py | List.from_list | def from_list(cls, database, key, data, clear=False):
"""
Create and populate a List object from a data list.
"""
lst = cls(database, key)
if clear:
lst.clear()
lst.extend(data)
return lst | python | def from_list(cls, database, key, data, clear=False):
"""
Create and populate a List object from a data list.
"""
lst = cls(database, key)
if clear:
lst.clear()
lst.extend(data)
return lst | [
"def",
"from_list",
"(",
"cls",
",",
"database",
",",
"key",
",",
"data",
",",
"clear",
"=",
"False",
")",
":",
"lst",
"=",
"cls",
"(",
"database",
",",
"key",
")",
"if",
"clear",
":",
"lst",
".",
"clear",
"(",
")",
"lst",
".",
"extend",
"(",
"... | Create and populate a List object from a data list. | [
"Create",
"and",
"populate",
"a",
"List",
"object",
"from",
"a",
"data",
"list",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L355-L363 | train | 202,991 |
coleifer/walrus | walrus/containers.py | Set.diffstore | def diffstore(self, dest, *others):
"""
Store the set difference of the current set and one or more
others in a new key.
:param dest: the name of the key to store set difference
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``.
"""
keys = [self.key]
keys.extend([other.key for other in others])
self.database.sdiffstore(dest, keys)
return self.database.Set(dest) | python | def diffstore(self, dest, *others):
"""
Store the set difference of the current set and one or more
others in a new key.
:param dest: the name of the key to store set difference
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``.
"""
keys = [self.key]
keys.extend([other.key for other in others])
self.database.sdiffstore(dest, keys)
return self.database.Set(dest) | [
"def",
"diffstore",
"(",
"self",
",",
"dest",
",",
"*",
"others",
")",
":",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
"keys",
".",
"extend",
"(",
"[",
"other",
".",
"key",
"for",
"other",
"in",
"others",
"]",
")",
"self",
".",
"database",
".",
... | Store the set difference of the current set and one or more
others in a new key.
:param dest: the name of the key to store set difference
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``. | [
"Store",
"the",
"set",
"difference",
"of",
"the",
"current",
"set",
"and",
"one",
"or",
"more",
"others",
"in",
"a",
"new",
"key",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L463-L475 | train | 202,992 |
coleifer/walrus | walrus/containers.py | Set.interstore | def interstore(self, dest, *others):
"""
Store the intersection of the current set and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``.
"""
keys = [self.key]
keys.extend([other.key for other in others])
self.database.sinterstore(dest, keys)
return self.database.Set(dest) | python | def interstore(self, dest, *others):
"""
Store the intersection of the current set and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``.
"""
keys = [self.key]
keys.extend([other.key for other in others])
self.database.sinterstore(dest, keys)
return self.database.Set(dest) | [
"def",
"interstore",
"(",
"self",
",",
"dest",
",",
"*",
"others",
")",
":",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
"keys",
".",
"extend",
"(",
"[",
"other",
".",
"key",
"for",
"other",
"in",
"others",
"]",
")",
"self",
".",
"database",
".",
... | Store the intersection of the current set and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``. | [
"Store",
"the",
"intersection",
"of",
"the",
"current",
"set",
"and",
"one",
"or",
"more",
"others",
"in",
"a",
"new",
"key",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L477-L489 | train | 202,993 |
coleifer/walrus | walrus/containers.py | Set.as_set | def as_set(self, decode=False):
"""
Return a Python set containing all the items in the collection.
"""
items = self.database.smembers(self.key)
return set(_decode(item) for item in items) if decode else items | python | def as_set(self, decode=False):
"""
Return a Python set containing all the items in the collection.
"""
items = self.database.smembers(self.key)
return set(_decode(item) for item in items) if decode else items | [
"def",
"as_set",
"(",
"self",
",",
"decode",
"=",
"False",
")",
":",
"items",
"=",
"self",
".",
"database",
".",
"smembers",
"(",
"self",
".",
"key",
")",
"return",
"set",
"(",
"_decode",
"(",
"item",
")",
"for",
"item",
"in",
"items",
")",
"if",
... | Return a Python set containing all the items in the collection. | [
"Return",
"a",
"Python",
"set",
"containing",
"all",
"the",
"items",
"in",
"the",
"collection",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L505-L510 | train | 202,994 |
coleifer/walrus | walrus/containers.py | Set.from_set | def from_set(cls, database, key, data, clear=False):
"""
Create and populate a Set object from a data set.
"""
s = cls(database, key)
if clear:
s.clear()
s.add(*data)
return s | python | def from_set(cls, database, key, data, clear=False):
"""
Create and populate a Set object from a data set.
"""
s = cls(database, key)
if clear:
s.clear()
s.add(*data)
return s | [
"def",
"from_set",
"(",
"cls",
",",
"database",
",",
"key",
",",
"data",
",",
"clear",
"=",
"False",
")",
":",
"s",
"=",
"cls",
"(",
"database",
",",
"key",
")",
"if",
"clear",
":",
"s",
".",
"clear",
"(",
")",
"s",
".",
"add",
"(",
"*",
"dat... | Create and populate a Set object from a data set. | [
"Create",
"and",
"populate",
"a",
"Set",
"object",
"from",
"a",
"data",
"set",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L513-L521 | train | 202,995 |
coleifer/walrus | walrus/containers.py | ZSet.rank | def rank(self, item, reverse=False):
"""Return the rank of the given item."""
fn = reverse and self.database.zrevrank or self.database.zrank
return fn(self.key, item) | python | def rank(self, item, reverse=False):
"""Return the rank of the given item."""
fn = reverse and self.database.zrevrank or self.database.zrank
return fn(self.key, item) | [
"def",
"rank",
"(",
"self",
",",
"item",
",",
"reverse",
"=",
"False",
")",
":",
"fn",
"=",
"reverse",
"and",
"self",
".",
"database",
".",
"zrevrank",
"or",
"self",
".",
"database",
".",
"zrank",
"return",
"fn",
"(",
"self",
".",
"key",
",",
"item... | Return the rank of the given item. | [
"Return",
"the",
"rank",
"of",
"the",
"given",
"item",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L679-L682 | train | 202,996 |
coleifer/walrus | walrus/containers.py | ZSet.count | def count(self, low, high=None):
"""
Return the number of items between the given bounds.
"""
if high is None:
high = low
return self.database.zcount(self.key, low, high) | python | def count(self, low, high=None):
"""
Return the number of items between the given bounds.
"""
if high is None:
high = low
return self.database.zcount(self.key, low, high) | [
"def",
"count",
"(",
"self",
",",
"low",
",",
"high",
"=",
"None",
")",
":",
"if",
"high",
"is",
"None",
":",
"high",
"=",
"low",
"return",
"self",
".",
"database",
".",
"zcount",
"(",
"self",
".",
"key",
",",
"low",
",",
"high",
")"
] | Return the number of items between the given bounds. | [
"Return",
"the",
"number",
"of",
"items",
"between",
"the",
"given",
"bounds",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L684-L690 | train | 202,997 |
coleifer/walrus | walrus/containers.py | ZSet.range | def range(self, low, high, with_scores=False, desc=False, reverse=False):
"""
Return a range of items between ``low`` and ``high``. By
default scores will not be included, but this can be controlled
via the ``with_scores`` parameter.
:param low: Lower bound.
:param high: Upper bound.
:param bool with_scores: Whether the range should include the
scores along with the items.
:param bool desc: Whether to sort the results descendingly.
:param bool reverse: Whether to select the range in reverse.
"""
if reverse:
return self.database.zrevrange(self.key, low, high, with_scores)
else:
return self.database.zrange(self.key, low, high, desc, with_scores) | python | def range(self, low, high, with_scores=False, desc=False, reverse=False):
"""
Return a range of items between ``low`` and ``high``. By
default scores will not be included, but this can be controlled
via the ``with_scores`` parameter.
:param low: Lower bound.
:param high: Upper bound.
:param bool with_scores: Whether the range should include the
scores along with the items.
:param bool desc: Whether to sort the results descendingly.
:param bool reverse: Whether to select the range in reverse.
"""
if reverse:
return self.database.zrevrange(self.key, low, high, with_scores)
else:
return self.database.zrange(self.key, low, high, desc, with_scores) | [
"def",
"range",
"(",
"self",
",",
"low",
",",
"high",
",",
"with_scores",
"=",
"False",
",",
"desc",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"reverse",
":",
"return",
"self",
".",
"database",
".",
"zrevrange",
"(",
"self",
".",
... | Return a range of items between ``low`` and ``high``. By
default scores will not be included, but this can be controlled
via the ``with_scores`` parameter.
:param low: Lower bound.
:param high: Upper bound.
:param bool with_scores: Whether the range should include the
scores along with the items.
:param bool desc: Whether to sort the results descendingly.
:param bool reverse: Whether to select the range in reverse. | [
"Return",
"a",
"range",
"of",
"items",
"between",
"low",
"and",
"high",
".",
"By",
"default",
"scores",
"will",
"not",
"be",
"included",
"but",
"this",
"can",
"be",
"controlled",
"via",
"the",
"with_scores",
"parameter",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L699-L715 | train | 202,998 |
coleifer/walrus | walrus/containers.py | ZSet.remove_by_score | def remove_by_score(self, low, high=None):
"""
Remove elements from the ZSet by their score.
:param low: Lower bound.
:param high: Upper bound.
"""
if high is None:
high = low
return self.database.zremrangebyscore(self.key, low, high) | python | def remove_by_score(self, low, high=None):
"""
Remove elements from the ZSet by their score.
:param low: Lower bound.
:param high: Upper bound.
"""
if high is None:
high = low
return self.database.zremrangebyscore(self.key, low, high) | [
"def",
"remove_by_score",
"(",
"self",
",",
"low",
",",
"high",
"=",
"None",
")",
":",
"if",
"high",
"is",
"None",
":",
"high",
"=",
"low",
"return",
"self",
".",
"database",
".",
"zremrangebyscore",
"(",
"self",
".",
"key",
",",
"low",
",",
"high",
... | Remove elements from the ZSet by their score.
:param low: Lower bound.
:param high: Upper bound. | [
"Remove",
"elements",
"from",
"the",
"ZSet",
"by",
"their",
"score",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L748-L757 | train | 202,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.