blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3c5070507aac4c54dc51a619dced20d44993a80b | [
"prev = -1\nres = float('-inf')\nif seats[0] == 1:\n prev = 0\nfor i, seat in enumerate(seats):\n if i == 1:\n if prev == -1:\n res = max(res, i)\n else:\n res = max(res, (i - prev) // 2)\n prev = i\nif seat[-1] == 0:\n res = max(res, len(seats) - 1 - prev)\nretur... | <|body_start_0|>
prev = -1
res = float('-inf')
if seats[0] == 1:
prev = 0
for i, seat in enumerate(seats):
if i == 1:
if prev == -1:
res = max(res, i)
else:
res = max(res, (i - prev) // 2)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDistToClosest2(self, seats):
""":type seats: List[int] :rtype: int"""
<|body_0|>
def maxDistToClosest(self, seats):
""":type seats: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
prev = -1
res = float(... | stack_v2_sparse_classes_75kplus_train_008000 | 1,617 | no_license | [
{
"docstring": ":type seats: List[int] :rtype: int",
"name": "maxDistToClosest2",
"signature": "def maxDistToClosest2(self, seats)"
},
{
"docstring": ":type seats: List[int] :rtype: int",
"name": "maxDistToClosest",
"signature": "def maxDistToClosest(self, seats)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023410 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDistToClosest2(self, seats): :type seats: List[int] :rtype: int
- def maxDistToClosest(self, seats): :type seats: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDistToClosest2(self, seats): :type seats: List[int] :rtype: int
- def maxDistToClosest(self, seats): :type seats: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def maxDistToClosest2(self, seats):
""":type seats: List[int] :rtype: int"""
<|body_0|>
def maxDistToClosest(self, seats):
""":type seats: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxDistToClosest2(self, seats):
""":type seats: List[int] :rtype: int"""
prev = -1
res = float('-inf')
if seats[0] == 1:
prev = 0
for i, seat in enumerate(seats):
if i == 1:
if prev == -1:
res = m... | the_stack_v2_python_sparse | Algorithm/849_Max_Distance_To_Closest_People.py | Gi1ia/TechNoteBook | train | 7 | |
93d1ebc2b47dc7dd8e59d62e1e411639fd5831dc | [
"order_id = kwargs['order_id']\norder = Order.objects.get(id=order_id)\nreturn render(request, 'order/order_created.html', {'order': order})",
"order_id = request.POST.get('order_id')\norder = Order.objects.get(id=order_id)\nif order.status is True:\n for i in range(len(order.OrderProduct.all())):\n '주문... | <|body_start_0|>
order_id = kwargs['order_id']
order = Order.objects.get(id=order_id)
return render(request, 'order/order_created.html', {'order': order})
<|end_body_0|>
<|body_start_1|>
order_id = request.POST.get('order_id')
order = Order.objects.get(id=order_id)
if or... | 주문이 끝나면 사용되는 뷰 | OrderComplete | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderComplete:
"""주문이 끝나면 사용되는 뷰"""
def get(self, request, *args, **kwargs):
"""get으로 접근할 경우 주문에 대한 데이터만 출력"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""ajax로 post로 접근할 경우 주문한 수량만큼 DB에서 해당 품목의 수량을 빼는 뷰"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_008001 | 8,500 | no_license | [
{
"docstring": "get으로 접근할 경우 주문에 대한 데이터만 출력",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "ajax로 post로 접근할 경우 주문한 수량만큼 DB에서 해당 품목의 수량을 빼는 뷰",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008807 | Implement the Python class `OrderComplete` described below.
Class description:
주문이 끝나면 사용되는 뷰
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): get으로 접근할 경우 주문에 대한 데이터만 출력
- def post(self, request, *args, **kwargs): ajax로 post로 접근할 경우 주문한 수량만큼 DB에서 해당 품목의 수량을 빼는 뷰 | Implement the Python class `OrderComplete` described below.
Class description:
주문이 끝나면 사용되는 뷰
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): get으로 접근할 경우 주문에 대한 데이터만 출력
- def post(self, request, *args, **kwargs): ajax로 post로 접근할 경우 주문한 수량만큼 DB에서 해당 품목의 수량을 빼는 뷰
<|skeleton|>
class OrderC... | 838da4c79a0e84fd0f3d17b2345faadd7ca9465a | <|skeleton|>
class OrderComplete:
"""주문이 끝나면 사용되는 뷰"""
def get(self, request, *args, **kwargs):
"""get으로 접근할 경우 주문에 대한 데이터만 출력"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""ajax로 post로 접근할 경우 주문한 수량만큼 DB에서 해당 품목의 수량을 빼는 뷰"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderComplete:
"""주문이 끝나면 사용되는 뷰"""
def get(self, request, *args, **kwargs):
"""get으로 접근할 경우 주문에 대한 데이터만 출력"""
order_id = kwargs['order_id']
order = Order.objects.get(id=order_id)
return render(request, 'order/order_created.html', {'order': order})
def post(self, requ... | the_stack_v2_python_sparse | order/views.py | Donkey-1028/ANCHOVYMART | train | 0 |
7b49c71f47d171d8a60a0824ba60c6364371d097 | [
"if isinstance(size, numbers.Number):\n if size < 0:\n raise ValueError('If input_size is a single number, it must be positive.')\n size = (size, size)\nelif isinstance(size, list) or isinstance(size, tuple) or isinstance(size, np.ndarray):\n if len(size) != 2:\n raise ValueError('If input_si... | <|body_start_0|>
if isinstance(size, numbers.Number):
if size < 0:
raise ValueError('If input_size is a single number, it must be positive.')
size = (size, size)
elif isinstance(size, list) or isinstance(size, tuple) or isinstance(size, np.ndarray):
if... | RandomResize | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomResize:
def __init__(self, size, random_rate, keep_ratio=False):
""":param input_size: resize尺寸,数字或者list的形式,如果为list形式,就是[w,h] :param ramdon_rate: 随机系数 :param keep_ratio: 是否保持长宽比 :return:"""
<|body_0|>
def __call__(self, data: dict) -> dict:
"""从scales中随机选择一个尺度,... | stack_v2_sparse_classes_75kplus_train_008002 | 10,172 | permissive | [
{
"docstring": ":param input_size: resize尺寸,数字或者list的形式,如果为list形式,就是[w,h] :param ramdon_rate: 随机系数 :param keep_ratio: 是否保持长宽比 :return:",
"name": "__init__",
"signature": "def __init__(self, size, random_rate, keep_ratio=False)"
},
{
"docstring": "从scales中随机选择一个尺度,对图片和文本框进行缩放 :param data: {'img':... | 2 | stack_v2_sparse_classes_30k_train_011541 | Implement the Python class `RandomResize` described below.
Class description:
Implement the RandomResize class.
Method signatures and docstrings:
- def __init__(self, size, random_rate, keep_ratio=False): :param input_size: resize尺寸,数字或者list的形式,如果为list形式,就是[w,h] :param ramdon_rate: 随机系数 :param keep_ratio: 是否保持长宽比 :re... | Implement the Python class `RandomResize` described below.
Class description:
Implement the RandomResize class.
Method signatures and docstrings:
- def __init__(self, size, random_rate, keep_ratio=False): :param input_size: resize尺寸,数字或者list的形式,如果为list形式,就是[w,h] :param ramdon_rate: 随机系数 :param keep_ratio: 是否保持长宽比 :re... | 15963b0d242867a4cc4d76445626dc8965509b2f | <|skeleton|>
class RandomResize:
def __init__(self, size, random_rate, keep_ratio=False):
""":param input_size: resize尺寸,数字或者list的形式,如果为list形式,就是[w,h] :param ramdon_rate: 随机系数 :param keep_ratio: 是否保持长宽比 :return:"""
<|body_0|>
def __call__(self, data: dict) -> dict:
"""从scales中随机选择一个尺度,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomResize:
def __init__(self, size, random_rate, keep_ratio=False):
""":param input_size: resize尺寸,数字或者list的形式,如果为list形式,就是[w,h] :param ramdon_rate: 随机系数 :param keep_ratio: 是否保持长宽比 :return:"""
if isinstance(size, numbers.Number):
if size < 0:
raise ValueError('If... | the_stack_v2_python_sparse | benchmark/PaddleOCR_DBNet/data_loader/modules/augment.py | PaddlePaddle/PaddleOCR | train | 34,195 | |
fe6a542376e4c9948e1198286e86c40beb801bcf | [
"movements = Movement.objects.all()\nserializer = MovementSerializer(movements, many=True, context={'request': request})\nreturn Response(serializer.data)",
"try:\n movement = Movement.objects.get(pk=pk)\n serializer = MovementSerializer(movement, context={'request': request})\n return Response(serialize... | <|body_start_0|>
movements = Movement.objects.all()
serializer = MovementSerializer(movements, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
try:
movement = Movement.objects.get(pk=pk)
serializer = Movem... | Movement for MusicMemory API | MovementView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovementView:
"""Movement for MusicMemory API"""
def list(self, request):
"""Handle GET requests to movement resource Returns: Response -- JSON serialized list of movement"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single movem... | stack_v2_sparse_classes_75kplus_train_008003 | 1,878 | no_license | [
{
"docstring": "Handle GET requests to movement resource Returns: Response -- JSON serialized list of movement",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Handle GET requests for single movement rating Returns: Response -- JSON serialized movement instance",
"... | 3 | null | Implement the Python class `MovementView` described below.
Class description:
Movement for MusicMemory API
Method signatures and docstrings:
- def list(self, request): Handle GET requests to movement resource Returns: Response -- JSON serialized list of movement
- def retrieve(self, request, pk=None): Handle GET requ... | Implement the Python class `MovementView` described below.
Class description:
Movement for MusicMemory API
Method signatures and docstrings:
- def list(self, request): Handle GET requests to movement resource Returns: Response -- JSON serialized list of movement
- def retrieve(self, request, pk=None): Handle GET requ... | ed9621ac92f6f8eae292233de2c9369bd995e1af | <|skeleton|>
class MovementView:
"""Movement for MusicMemory API"""
def list(self, request):
"""Handle GET requests to movement resource Returns: Response -- JSON serialized list of movement"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single movem... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovementView:
"""Movement for MusicMemory API"""
def list(self, request):
"""Handle GET requests to movement resource Returns: Response -- JSON serialized list of movement"""
movements = Movement.objects.all()
serializer = MovementSerializer(movements, many=True, context={'request... | the_stack_v2_python_sparse | musicmemoryapi/views/movement.py | leigharobinson/dementia_music_memory | train | 1 |
76782d495114de1f1b7006976adf26f57a44c34d | [
"Bullet.__init__(self, lifetime, alpha, beta, x, y, True)\nself.width = width\nself.height = height\nself.vx = vx\nself.vy = vy\nself.angle = -atan2(self.vy, self.vx)",
"surface = pygame.transform.smoothscale(bomb_image, (self.width, self.height))\nsurface = pygame.transform.rotate(surface, 180 + self.angle * 180... | <|body_start_0|>
Bullet.__init__(self, lifetime, alpha, beta, x, y, True)
self.width = width
self.height = height
self.vx = vx
self.vy = vy
self.angle = -atan2(self.vy, self.vx)
<|end_body_0|>
<|body_start_1|>
surface = pygame.transform.smoothscale(bomb_image, (s... | Bomb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bomb:
def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta):
"""Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы ... | stack_v2_sparse_classes_75kplus_train_008004 | 9,588 | no_license | [
{
"docstring": "Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param beta: параметр b в формуле силы трения F = -av - bv^2 :param width: длина бомбы :param height: толщина бомбы :param x: начальн... | 3 | stack_v2_sparse_classes_30k_train_023525 | Implement the Python class `Bomb` described below.
Class description:
Implement the Bomb class.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta): Конструктор класса бомб, которыми стреляет истре... | Implement the Python class `Bomb` described below.
Class description:
Implement the Bomb class.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta): Конструктор класса бомб, которыми стреляет истре... | 19d00443e953a487e762676d6682579a537f55f0 | <|skeleton|>
class Bomb:
def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta):
"""Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bomb:
def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta):
"""Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы трения F = -av... | the_stack_v2_python_sparse | Лаба 8/modules/bullets.py | VladimirMolunov/molunov_infa_2021 | train | 0 | |
6bcd9bd3098be2fb41bd5e9bef808c21e2e9f64a | [
"assert uid == SUPERUSER_ID, 'User to force discount value should be the administrator'\nproduct_ids = self.search(cr, uid, [], discount_id, context=context)\n_logger.debug('Dicount id force default : %d', discount_id)\nself.write(cr, uid, product_ids, {'discount_id': discount_id}, context=context)",
"assert uid ... | <|body_start_0|>
assert uid == SUPERUSER_ID, 'User to force discount value should be the administrator'
product_ids = self.search(cr, uid, [], discount_id, context=context)
_logger.debug('Dicount id force default : %d', discount_id)
self.write(cr, uid, product_ids, {'discount_id': discou... | ProductTemplate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductTemplate:
def force_default_discount(self, cr, uid, ids=[], discount_id=0, context=None):
"""Quick solution to avoid encoding the same discount manually for each product User should be admin"""
<|body_0|>
def force_default_taxes(self, cr, uid, ids=[], taxes_ids=[1], c... | stack_v2_sparse_classes_75kplus_train_008005 | 12,134 | no_license | [
{
"docstring": "Quick solution to avoid encoding the same discount manually for each product User should be admin",
"name": "force_default_discount",
"signature": "def force_default_discount(self, cr, uid, ids=[], discount_id=0, context=None)"
},
{
"docstring": "Quick solution to avoid encoding ... | 2 | stack_v2_sparse_classes_30k_train_020663 | Implement the Python class `ProductTemplate` described below.
Class description:
Implement the ProductTemplate class.
Method signatures and docstrings:
- def force_default_discount(self, cr, uid, ids=[], discount_id=0, context=None): Quick solution to avoid encoding the same discount manually for each product User sh... | Implement the Python class `ProductTemplate` described below.
Class description:
Implement the ProductTemplate class.
Method signatures and docstrings:
- def force_default_discount(self, cr, uid, ids=[], discount_id=0, context=None): Quick solution to avoid encoding the same discount manually for each product User sh... | 3681cbad05d5748198318fc1774be77b5f6b420e | <|skeleton|>
class ProductTemplate:
def force_default_discount(self, cr, uid, ids=[], discount_id=0, context=None):
"""Quick solution to avoid encoding the same discount manually for each product User should be admin"""
<|body_0|>
def force_default_taxes(self, cr, uid, ids=[], taxes_ids=[1], c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductTemplate:
def force_default_discount(self, cr, uid, ids=[], discount_id=0, context=None):
"""Quick solution to avoid encoding the same discount manually for each product User should be admin"""
assert uid == SUPERUSER_ID, 'User to force discount value should be the administrator'
... | the_stack_v2_python_sparse | account_grouped_invoice/grouped_invoice.py | dbertha/odoo-addons | train | 1 | |
3d3319840b43424696654fb18535ad10811124cf | [
"self.lr = learning_rate\nself.momentum = momentum\nself.model_weight_specs = model_weight_specs\nself.noise_std = noise_std\nself.random_generator = tf.random.Generator.from_non_deterministic_state()",
"def noise_tensor(spec):\n noise = self.random_generator.normal(spec.shape, stddev=self.noise_std)\n nois... | <|body_start_0|>
self.lr = learning_rate
self.momentum = momentum
self.model_weight_specs = model_weight_specs
self.noise_std = noise_std
self.random_generator = tf.random.Generator.from_non_deterministic_state()
<|end_body_0|>
<|body_start_1|>
def noise_tensor(spec):
... | Momentum DPSGD Optimizer. | DPSGDMServerOptimizer | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPSGDMServerOptimizer:
"""Momentum DPSGD Optimizer."""
def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]):
"""Initialize the momemtum DPSGD Optimizer."""
<|body_0|>
def _noise_fn(self):
"""Re... | stack_v2_sparse_classes_75kplus_train_008006 | 9,237 | permissive | [
{
"docstring": "Initialize the momemtum DPSGD Optimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec])"
},
{
"docstring": "Returns random noise to be added for differential privacy.",... | 4 | stack_v2_sparse_classes_30k_train_025482 | Implement the Python class `DPSGDMServerOptimizer` described below.
Class description:
Momentum DPSGD Optimizer.
Method signatures and docstrings:
- def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): Initialize the momemtum DPSGD Optimizer.
- de... | Implement the Python class `DPSGDMServerOptimizer` described below.
Class description:
Momentum DPSGD Optimizer.
Method signatures and docstrings:
- def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): Initialize the momemtum DPSGD Optimizer.
- de... | 329e60fa56b87f691303638ceb9dfa1fc5083953 | <|skeleton|>
class DPSGDMServerOptimizer:
"""Momentum DPSGD Optimizer."""
def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]):
"""Initialize the momemtum DPSGD Optimizer."""
<|body_0|>
def _noise_fn(self):
"""Re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DPSGDMServerOptimizer:
"""Momentum DPSGD Optimizer."""
def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]):
"""Initialize the momemtum DPSGD Optimizer."""
self.lr = learning_rate
self.momentum = momentum
... | the_stack_v2_python_sparse | dp_ftrl/optimizer_utils.py | google-research/federated | train | 595 |
a742a3298693c8d8b2e853774ee211583aa8305b | [
"super().__init__(problem, kwargs)\nself.epoch = epoch\nself.pop_size = pop_size\nself.p_a = p_a\nself.n_cut = int(self.p_a * self.pop_size)\nself.nfe_per_epoch = self.pop_size + self.n_cut\nself.sort_flag = False",
"if mode != 'sequential':\n print('CSA is only support sequential mode!')\n exit(0)\nfor i i... | <|body_start_0|>
super().__init__(problem, kwargs)
self.epoch = epoch
self.pop_size = pop_size
self.p_a = p_a
self.n_cut = int(self.p_a * self.pop_size)
self.nfe_per_epoch = self.pop_size + self.n_cut
self.sort_flag = False
<|end_body_0|>
<|body_start_1|>
... | The original version of: Cuckoo Search Algorithm (CSA) (Cuckoo search via Levy flights) Link: https://doi.org/10.1109/NABIC.2009.5393690 | BaseCSA | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseCSA:
"""The original version of: Cuckoo Search Algorithm (CSA) (Cuckoo search via Levy flights) Link: https://doi.org/10.1109/NABIC.2009.5393690"""
def __init__(self, problem, epoch=10000, pop_size=100, p_a=0.3, **kwargs):
"""Args: problem (): epoch (int): maximum number of itera... | stack_v2_sparse_classes_75kplus_train_008007 | 4,029 | permissive | [
{
"docstring": "Args: problem (): epoch (int): maximum number of iterations, default = 10000 pop_size (int): number of population size, default = 100 p_a (float): probability a **kwargs ():",
"name": "__init__",
"signature": "def __init__(self, problem, epoch=10000, pop_size=100, p_a=0.3, **kwargs)"
}... | 2 | stack_v2_sparse_classes_30k_train_008306 | Implement the Python class `BaseCSA` described below.
Class description:
The original version of: Cuckoo Search Algorithm (CSA) (Cuckoo search via Levy flights) Link: https://doi.org/10.1109/NABIC.2009.5393690
Method signatures and docstrings:
- def __init__(self, problem, epoch=10000, pop_size=100, p_a=0.3, **kwargs... | Implement the Python class `BaseCSA` described below.
Class description:
The original version of: Cuckoo Search Algorithm (CSA) (Cuckoo search via Levy flights) Link: https://doi.org/10.1109/NABIC.2009.5393690
Method signatures and docstrings:
- def __init__(self, problem, epoch=10000, pop_size=100, p_a=0.3, **kwargs... | 409e832799b3da8ff9590d645ab5b661f30660f6 | <|skeleton|>
class BaseCSA:
"""The original version of: Cuckoo Search Algorithm (CSA) (Cuckoo search via Levy flights) Link: https://doi.org/10.1109/NABIC.2009.5393690"""
def __init__(self, problem, epoch=10000, pop_size=100, p_a=0.3, **kwargs):
"""Args: problem (): epoch (int): maximum number of itera... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseCSA:
"""The original version of: Cuckoo Search Algorithm (CSA) (Cuckoo search via Levy flights) Link: https://doi.org/10.1109/NABIC.2009.5393690"""
def __init__(self, problem, epoch=10000, pop_size=100, p_a=0.3, **kwargs):
"""Args: problem (): epoch (int): maximum number of iterations, defaul... | the_stack_v2_python_sparse | mealpy/swarm_based/CSA.py | songshuang116/mealpy | train | 0 |
ae3b85dbd7a8f66c0287f7b044a4dc422ac48078 | [
"self.user = MyUser.objects.create_test_user(username='test', email='test@yahoo.com', password='password1!')\nself.course = Course(name='testing course', slug='testing-course')\nself.course.save()\nself.coursesection = CourseSection(name='Section 1', course=self.course)\nself.coursesection.save()\nself.category = C... | <|body_start_0|>
self.user = MyUser.objects.create_test_user(username='test', email='test@yahoo.com', password='password1!')
self.course = Course(name='testing course', slug='testing-course')
self.course.save()
self.coursesection = CourseSection(name='Section 1', course=self.course)
... | Tests related to the actual Notification functionality. | NotificationTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationTests:
"""Tests related to the actual Notification functionality."""
def setUp(self):
"""Set up the user infrastructure."""
<|body_0|>
def test_notification_creation(self):
"""Test the creation of a notification."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_008008 | 2,331 | no_license | [
{
"docstring": "Set up the user infrastructure.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the creation of a notification.",
"name": "test_notification_creation",
"signature": "def test_notification_creation(self)"
}
] | 2 | null | Implement the Python class `NotificationTests` described below.
Class description:
Tests related to the actual Notification functionality.
Method signatures and docstrings:
- def setUp(self): Set up the user infrastructure.
- def test_notification_creation(self): Test the creation of a notification. | Implement the Python class `NotificationTests` described below.
Class description:
Tests related to the actual Notification functionality.
Method signatures and docstrings:
- def setUp(self): Set up the user infrastructure.
- def test_notification_creation(self): Test the creation of a notification.
<|skeleton|>
cla... | cd4ff5222e437fca055dce4790c8c349699d3f5f | <|skeleton|>
class NotificationTests:
"""Tests related to the actual Notification functionality."""
def setUp(self):
"""Set up the user infrastructure."""
<|body_0|>
def test_notification_creation(self):
"""Test the creation of a notification."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotificationTests:
"""Tests related to the actual Notification functionality."""
def setUp(self):
"""Set up the user infrastructure."""
self.user = MyUser.objects.create_test_user(username='test', email='test@yahoo.com', password='password1!')
self.course = Course(name='testing co... | the_stack_v2_python_sparse | src/notifications/tests.py | av8ramit/caprende | train | 0 |
b4cf0c0c7e87f35288ceb44f3f5aeb9d1b3bd580 | [
"self.gensim_model = None\nself.num_topics = num_topics\nself.id2word = id2word\nself.chunksize = chunksize\nself.passes = passes\nself.update_every = update_every\nself.alpha = alpha\nself.eta = eta\nself.decay = decay\nself.offset = offset\nself.eval_every = eval_every\nself.iterations = iterations\nself.gamma_th... | <|body_start_0|>
self.gensim_model = None
self.num_topics = num_topics
self.id2word = id2word
self.chunksize = chunksize
self.passes = passes
self.update_every = update_every
self.alpha = alpha
self.eta = eta
self.decay = decay
self.offset ... | Base LDA module | LdaTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LdaTransformer:
"""Base LDA module"""
def __init__(self, num_topics=100, id2word=None, chunksize=2000, passes=1, update_every=1, alpha='symmetric', eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50, gamma_threshold=0.001, minimum_probability=0.01, random_state=None, scorer='perpl... | stack_v2_sparse_classes_75kplus_train_008009 | 5,783 | permissive | [
{
"docstring": "Sklearn wrapper for LDA model. See gensim.model.LdaModel for parameter details. `scorer` specifies the metric used in the `score` function. See `gensim.models.LdaModel` class for description of the other parameters.",
"name": "__init__",
"signature": "def __init__(self, num_topics=100, i... | 5 | null | Implement the Python class `LdaTransformer` described below.
Class description:
Base LDA module
Method signatures and docstrings:
- def __init__(self, num_topics=100, id2word=None, chunksize=2000, passes=1, update_every=1, alpha='symmetric', eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50, gamma_thresho... | Implement the Python class `LdaTransformer` described below.
Class description:
Base LDA module
Method signatures and docstrings:
- def __init__(self, num_topics=100, id2word=None, chunksize=2000, passes=1, update_every=1, alpha='symmetric', eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50, gamma_thresho... | 1bc3390770ddafbba2e2779ba91998643df6d9ec | <|skeleton|>
class LdaTransformer:
"""Base LDA module"""
def __init__(self, num_topics=100, id2word=None, chunksize=2000, passes=1, update_every=1, alpha='symmetric', eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50, gamma_threshold=0.001, minimum_probability=0.01, random_state=None, scorer='perpl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LdaTransformer:
"""Base LDA module"""
def __init__(self, num_topics=100, id2word=None, chunksize=2000, passes=1, update_every=1, alpha='symmetric', eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50, gamma_threshold=0.001, minimum_probability=0.01, random_state=None, scorer='perplexity', dtype... | the_stack_v2_python_sparse | p3/Lib/site-packages/gensim/sklearn_api/ldamodel.py | fpark7/Native2Native | train | 1 |
270d9b8b3c977892d8a0a3cc52a6bc9f97be4810 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing Elasticsearch users. | UserServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserServiceServicer:
"""A set of methods for managing Elasticsearch users."""
def Get(self, request, context):
"""Returns the specified Elasticsearch user. To get the list of available Elasticsearch users, make a [List] request."""
<|body_0|>
def List(self, request, cont... | stack_v2_sparse_classes_75kplus_train_008010 | 10,435 | permissive | [
{
"docstring": "Returns the specified Elasticsearch user. To get the list of available Elasticsearch users, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of Elasticsearch users in the specified cluster.",
"name": ... | 5 | stack_v2_sparse_classes_30k_train_041133 | Implement the Python class `UserServiceServicer` described below.
Class description:
A set of methods for managing Elasticsearch users.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Elasticsearch user. To get the list of available Elasticsearch users, make a [List] request... | Implement the Python class `UserServiceServicer` described below.
Class description:
A set of methods for managing Elasticsearch users.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Elasticsearch user. To get the list of available Elasticsearch users, make a [List] request... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class UserServiceServicer:
"""A set of methods for managing Elasticsearch users."""
def Get(self, request, context):
"""Returns the specified Elasticsearch user. To get the list of available Elasticsearch users, make a [List] request."""
<|body_0|>
def List(self, request, cont... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserServiceServicer:
"""A set of methods for managing Elasticsearch users."""
def Get(self, request, context):
"""Returns the specified Elasticsearch user. To get the list of available Elasticsearch users, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
c... | the_stack_v2_python_sparse | yandex/cloud/mdb/elasticsearch/v1/user_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
8c97c77cf471a7ab19e73df0d6ade833039a011b | [
"input_text = input_text.strip().replace(' ', ' ').replace(' ', ' ')\ninput_text_list = input_text.split()\nword_count = 0\ncolumn_count = 1\ncolumns_since_space = 1\nfor column in input_text:\n if column.isspace():\n word_count += 1\n columns_since_space = 0\n if (column_count / self.LINE_WI... | <|body_start_0|>
input_text = input_text.strip().replace(' ', ' ').replace(' ', ' ')
input_text_list = input_text.split()
word_count = 0
column_count = 1
columns_since_space = 1
for column in input_text:
if column.isspace():
word_count += 1
... | This class contains methods for formatting text. | FormatLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormatLine:
"""This class contains methods for formatting text."""
def breakLine(self, input_text):
"""Creates line breaks at or before the value of self.LINE_WIDTH."""
<|body_0|>
def blockText(self, input_text):
"""Formats text into a block-style."""
<|b... | stack_v2_sparse_classes_75kplus_train_008011 | 6,993 | no_license | [
{
"docstring": "Creates line breaks at or before the value of self.LINE_WIDTH.",
"name": "breakLine",
"signature": "def breakLine(self, input_text)"
},
{
"docstring": "Formats text into a block-style.",
"name": "blockText",
"signature": "def blockText(self, input_text)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_044672 | Implement the Python class `FormatLine` described below.
Class description:
This class contains methods for formatting text.
Method signatures and docstrings:
- def breakLine(self, input_text): Creates line breaks at or before the value of self.LINE_WIDTH.
- def blockText(self, input_text): Formats text into a block-... | Implement the Python class `FormatLine` described below.
Class description:
This class contains methods for formatting text.
Method signatures and docstrings:
- def breakLine(self, input_text): Creates line breaks at or before the value of self.LINE_WIDTH.
- def blockText(self, input_text): Formats text into a block-... | c0ddd8c01e083912e2dd891c963912fabc296d25 | <|skeleton|>
class FormatLine:
"""This class contains methods for formatting text."""
def breakLine(self, input_text):
"""Creates line breaks at or before the value of self.LINE_WIDTH."""
<|body_0|>
def blockText(self, input_text):
"""Formats text into a block-style."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FormatLine:
"""This class contains methods for formatting text."""
def breakLine(self, input_text):
"""Creates line breaks at or before the value of self.LINE_WIDTH."""
input_text = input_text.strip().replace(' ', ' ').replace(' ', ' ')
input_text_list = input_text.split()
... | the_stack_v2_python_sparse | old/gamesrc/tools/old_format_line_generic.py | pixel-parrot/MD | train | 0 |
4d6f2c94bed5af2eabbad5bbdbeda7ede882e2ad | [
"if num < 1:\n return False\nif num & num - 1 != 0:\n return False\nreturn num % 3 == 1",
"if num < 1:\n return False\nif num & num - 1 != 0:\n return False\nwhile True:\n if num == 0:\n return False\n elif num == 1:\n return True\n num >>= 2"
] | <|body_start_0|>
if num < 1:
return False
if num & num - 1 != 0:
return False
return num % 3 == 1
<|end_body_0|>
<|body_start_1|>
if num < 1:
return False
if num & num - 1 != 0:
return False
while True:
if num =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num):
"""Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:"""
<|body_0|>
def isPowerOfFourNaive(self, num):
"""Naive Determine number of 0 bits to be even :type num: int :rtype: bool"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_008012 | 988 | permissive | [
{
"docstring": "Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:",
"name": "isPowerOfFour",
"signature": "def isPowerOfFour(self, num)"
},
{
"docstring": "Naive Determine number of 0 bits to be even :type num: int :rtype: bool",
"name": "isPowerOfFourNaive",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_032384 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num): Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:
- def isPowerOfFourNaive(self, num): Naive Determine number of 0 bits to be eve... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num): Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:
- def isPowerOfFourNaive(self, num): Naive Determine number of 0 bits to be eve... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num):
"""Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:"""
<|body_0|>
def isPowerOfFourNaive(self, num):
"""Naive Determine number of 0 bits to be even :type num: int :rtype: bool"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPowerOfFour(self, num):
"""Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:"""
if num < 1:
return False
if num & num - 1 != 0:
return False
return num % 3 == 1
def isPowerOfFourNaive(self, num):
"""Naive D... | the_stack_v2_python_sparse | 342 Power of Four.py | Aminaba123/LeetCode | train | 1 | |
6ce5c4a7122a3635ffa1c02d3ba6fc41e2e35804 | [
"self.request_user = kwargs.pop('user', None)\nself.workflow = kwargs.pop('workflow')\nself.user_obj = None\nsuper().__init__(*args, **kwargs)",
"form_data = super().clean()\nself.user_obj = get_user_model().objects.filter(email__iexact=form_data['user_email']).first()\nif not self.user_obj:\n self.add_error('... | <|body_start_0|>
self.request_user = kwargs.pop('user', None)
self.workflow = kwargs.pop('workflow')
self.user_obj = None
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
form_data = super().clean()
self.user_obj = get_user_model().objects.filter(email__... | Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list) | SharedForm | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedForm:
"""Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)"""
def __init__(self, *args, **kwargs... | stack_v2_sparse_classes_75kplus_train_008013 | 3,730 | permissive | [
{
"docstring": "Set the request user, workflow.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check that the request has the correct user.",
"name": "clean",
"signature": "def clean(self) -> Dict"
}
] | 2 | stack_v2_sparse_classes_30k_train_011730 | Implement the Python class `SharedForm` described below.
Class description:
Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)
Me... | Implement the Python class `SharedForm` described below.
Class description:
Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)
Me... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class SharedForm:
"""Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)"""
def __init__(self, *args, **kwargs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SharedForm:
"""Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)"""
def __init__(self, *args, **kwargs):
""... | the_stack_v2_python_sparse | ontask/workflow/forms/attribute_shared.py | abelardopardo/ontask_b | train | 43 |
11ce7a7ac72194d13464380542092cdbf9129f97 | [
"self.buffer = deque()\nself.max_size = max_size\nself.min_size = min_size",
"if len(self.buffer) > self.max_size:\n self.buffer.popleft()\nself.buffer.append(exp)",
"sampled_buffer = random.sample(self.buffer, batch_size)\nstate, next_state, reward, action, done = zip(*sampled_buffer)\nstate, next_state = (... | <|body_start_0|>
self.buffer = deque()
self.max_size = max_size
self.min_size = min_size
<|end_body_0|>
<|body_start_1|>
if len(self.buffer) > self.max_size:
self.buffer.popleft()
self.buffer.append(exp)
<|end_body_1|>
<|body_start_2|>
sampled_buffer = rando... | Experience Buffer where the episode information is stored | ExpBuffer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpBuffer:
"""Experience Buffer where the episode information is stored"""
def __init__(self, max_size=10000, min_size=5000):
"""Initializes the maximum size of the buffer. Args: max_size: Height of the imag"""
<|body_0|>
def add_exp(self, exp):
"""Adds an experi... | stack_v2_sparse_classes_75kplus_train_008014 | 1,959 | permissive | [
{
"docstring": "Initializes the maximum size of the buffer. Args: max_size: Height of the imag",
"name": "__init__",
"signature": "def __init__(self, max_size=10000, min_size=5000)"
},
{
"docstring": "Adds an experience to the buffer.",
"name": "add_exp",
"signature": "def add_exp(self, ... | 3 | stack_v2_sparse_classes_30k_train_027309 | Implement the Python class `ExpBuffer` described below.
Class description:
Experience Buffer where the episode information is stored
Method signatures and docstrings:
- def __init__(self, max_size=10000, min_size=5000): Initializes the maximum size of the buffer. Args: max_size: Height of the imag
- def add_exp(self,... | Implement the Python class `ExpBuffer` described below.
Class description:
Experience Buffer where the episode information is stored
Method signatures and docstrings:
- def __init__(self, max_size=10000, min_size=5000): Initializes the maximum size of the buffer. Args: max_size: Height of the imag
- def add_exp(self,... | 975a95032ce5b7012d1772c7f1f5cfe606eae839 | <|skeleton|>
class ExpBuffer:
"""Experience Buffer where the episode information is stored"""
def __init__(self, max_size=10000, min_size=5000):
"""Initializes the maximum size of the buffer. Args: max_size: Height of the imag"""
<|body_0|>
def add_exp(self, exp):
"""Adds an experi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExpBuffer:
"""Experience Buffer where the episode information is stored"""
def __init__(self, max_size=10000, min_size=5000):
"""Initializes the maximum size of the buffer. Args: max_size: Height of the imag"""
self.buffer = deque()
self.max_size = max_size
self.min_size =... | the_stack_v2_python_sparse | blogs/rl-on-gcp/DQN_Breakout/rl_on_gcp/trainer/buffer.py | GoogleCloudPlatform/training-data-analyst | train | 7,311 |
cac5bc80ce50617e784e8a2b96a40115440b6f16 | [
"super(DarknetConv2D_BN_Leaky, self).__init__()\nno_bias_kwargs = {'use_bias': False}\nno_bias_kwargs.update(kwargs)\nself.conv1 = DarknetConv2D(*args, **no_bias_kwargs)\nself.bn1 = tf.keras.layers.BatchNormalization()\nself.leaky_relu1 = tf.keras.layers.LeakyReLU(alpha=0.1)",
"x = self.conv1(x)\nx = self.bn1(x, ... | <|body_start_0|>
super(DarknetConv2D_BN_Leaky, self).__init__()
no_bias_kwargs = {'use_bias': False}
no_bias_kwargs.update(kwargs)
self.conv1 = DarknetConv2D(*args, **no_bias_kwargs)
self.bn1 = tf.keras.layers.BatchNormalization()
self.leaky_relu1 = tf.keras.layers.LeakyR... | DarknetConv2D_BN_Leaky | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarknetConv2D_BN_Leaky:
def __init__(self, *args, **kwargs):
"""初始化网络"""
<|body_0|>
def call(self, x, training):
"""运算部分"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(DarknetConv2D_BN_Leaky, self).__init__()
no_bias_kwargs = {'use_bi... | stack_v2_sparse_classes_75kplus_train_008015 | 16,727 | no_license | [
{
"docstring": "初始化网络",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "运算部分",
"name": "call",
"signature": "def call(self, x, training)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002441 | Implement the Python class `DarknetConv2D_BN_Leaky` described below.
Class description:
Implement the DarknetConv2D_BN_Leaky class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 初始化网络
- def call(self, x, training): 运算部分 | Implement the Python class `DarknetConv2D_BN_Leaky` described below.
Class description:
Implement the DarknetConv2D_BN_Leaky class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 初始化网络
- def call(self, x, training): 运算部分
<|skeleton|>
class DarknetConv2D_BN_Leaky:
def __init__(self, *ar... | b7549701b0b1a7e4cc2c8275df2bc6c7a3253d24 | <|skeleton|>
class DarknetConv2D_BN_Leaky:
def __init__(self, *args, **kwargs):
"""初始化网络"""
<|body_0|>
def call(self, x, training):
"""运算部分"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DarknetConv2D_BN_Leaky:
def __init__(self, *args, **kwargs):
"""初始化网络"""
super(DarknetConv2D_BN_Leaky, self).__init__()
no_bias_kwargs = {'use_bias': False}
no_bias_kwargs.update(kwargs)
self.conv1 = DarknetConv2D(*args, **no_bias_kwargs)
self.bn1 = tf.keras.lay... | the_stack_v2_python_sparse | AIServer/ai_api/ai_models/utils/tf_yolo_utils.py | tfwcn/tensorflow2-machine-vision | train | 1 | |
e85f2b2ebb4a30cdf89388024d98719473e41812 | [
"if maskname not in ['gpi_g10s40', 'jwst_g7s6', 'jwst_g7s6c', 'visir_sam', 'p1640', 'keck_nirc2', 'pharo', 'NIRC2_9NRM']:\n raise ValueError('mask not supported')\nif holeshape is None:\n holeshape = 'circ'\nif holeshape not in ['circ', 'hex']:\n raise ValueError('Unsupported mask holeshape' + maskname)\ns... | <|body_start_0|>
if maskname not in ['gpi_g10s40', 'jwst_g7s6', 'jwst_g7s6c', 'visir_sam', 'p1640', 'keck_nirc2', 'pharo', 'NIRC2_9NRM']:
raise ValueError('mask not supported')
if holeshape is None:
holeshape = 'circ'
if holeshape not in ['circ', 'hex']:
raise... | NRM_mask_definitions | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NRM_mask_definitions:
def __init__(self, maskname=None, rotdeg=None, holeshape='circ', rescale=False, chooseholes=None):
"""Short Summary ------------- Set attributes of NRM_mask_definitions class. Parameters ---------- maskname: string name of mask rotdeg: list of floats range of rotati... | stack_v2_sparse_classes_75kplus_train_008016 | 6,028 | permissive | [
{
"docstring": "Short Summary ------------- Set attributes of NRM_mask_definitions class. Parameters ---------- maskname: string name of mask rotdeg: list of floats range of rotations to search (degrees) holeshape: string shape of apertures rescale: float multiplicative factor to adjust hole sizes and centers i... | 2 | stack_v2_sparse_classes_30k_train_021085 | Implement the Python class `NRM_mask_definitions` described below.
Class description:
Implement the NRM_mask_definitions class.
Method signatures and docstrings:
- def __init__(self, maskname=None, rotdeg=None, holeshape='circ', rescale=False, chooseholes=None): Short Summary ------------- Set attributes of NRM_mask_... | Implement the Python class `NRM_mask_definitions` described below.
Class description:
Implement the NRM_mask_definitions class.
Method signatures and docstrings:
- def __init__(self, maskname=None, rotdeg=None, holeshape='circ', rescale=False, chooseholes=None): Short Summary ------------- Set attributes of NRM_mask_... | a4a0e8ad2b88249f01445ee1dcf175229c51033f | <|skeleton|>
class NRM_mask_definitions:
def __init__(self, maskname=None, rotdeg=None, holeshape='circ', rescale=False, chooseholes=None):
"""Short Summary ------------- Set attributes of NRM_mask_definitions class. Parameters ---------- maskname: string name of mask rotdeg: list of floats range of rotati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NRM_mask_definitions:
def __init__(self, maskname=None, rotdeg=None, holeshape='circ', rescale=False, chooseholes=None):
"""Short Summary ------------- Set attributes of NRM_mask_definitions class. Parameters ---------- maskname: string name of mask rotdeg: list of floats range of rotations to search ... | the_stack_v2_python_sparse | jwst/ami/mask_definitions.py | spacetelescope/jwst | train | 449 | |
571246d3a845424403bf6567980060a9a903bfd8 | [
"self.namespace = namespace\nself.method = method\nself.arg_generator = arg_generator",
"raw = self.arg_generator.raw\nrequest = self.arg_generator.CreateRequest(self.namespace)\nlimit = self.arg_generator.Limit(self.namespace)\npage_size = self.arg_generator.PageSize(self.namespace)\nreturn self.method.Call(requ... | <|body_start_0|>
self.namespace = namespace
self.method = method
self.arg_generator = arg_generator
<|end_body_0|>
<|body_start_1|>
raw = self.arg_generator.raw
request = self.arg_generator.CreateRequest(self.namespace)
limit = self.arg_generator.Limit(self.namespace)
... | Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags were added and manually extract them. T... | MethodRef | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodRef:
"""Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags we... | stack_v2_sparse_classes_75kplus_train_008017 | 5,259 | permissive | [
{
"docstring": "Creates the MethodRef. Args: namespace: The argparse namespace that holds the parsed args. method: APIMethod, The method. arg_generator: arg_marshalling.AutoArgumentGenerator, The generator for this method.",
"name": "__init__",
"signature": "def __init__(self, namespace, method, arg_gen... | 2 | stack_v2_sparse_classes_30k_train_003596 | Implement the Python class `MethodRef` described below.
Class description:
Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doe... | Implement the Python class `MethodRef` described below.
Class description:
Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doe... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class MethodRef:
"""Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags we... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MethodRef:
"""Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags were added and ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/meta/apis/flags.py | bopopescu/socialliteapp | train | 0 |
02c5921e5aa04f23f0ccb1ba8fdac60265fd5789 | [
"self.factory = factory\nself.args = args\nself.kwargs = kwargs",
"factory = self.factory\nif factory is None:\n return []\ncns = []\nfor cn in factory(component, *self.args, **self.kwargs):\n if isinstance(cn, ConstraintHelper):\n cns.extend(cn.create_constraints(component))\n elif cn is not None... | <|body_start_0|>
self.factory = factory
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
factory = self.factory
if factory is None:
return []
cns = []
for cn in factory(component, *self.args, **self.kwargs):
if isinsta... | A constraint helper which delegates to a factory callable. | FactoryHelper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactoryHelper:
"""A constraint helper which delegates to a factory callable."""
def __init__(self, factory, *args, **kwargs):
"""Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional argum... | stack_v2_sparse_classes_75kplus_train_008018 | 2,063 | permissive | [
{
"docstring": "Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional arguments to pass to the factory. **kwargs Additional keyword arguments to pass to the factory.",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_018986 | Implement the Python class `FactoryHelper` described below.
Class description:
A constraint helper which delegates to a factory callable.
Method signatures and docstrings:
- def __init__(self, factory, *args, **kwargs): Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which gen... | Implement the Python class `FactoryHelper` described below.
Class description:
A constraint helper which delegates to a factory callable.
Method signatures and docstrings:
- def __init__(self, factory, *args, **kwargs): Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which gen... | b54467b48941ce20d0ffadb7385483d2e51963f5 | <|skeleton|>
class FactoryHelper:
"""A constraint helper which delegates to a factory callable."""
def __init__(self, factory, *args, **kwargs):
"""Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional argum... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FactoryHelper:
"""A constraint helper which delegates to a factory callable."""
def __init__(self, factory, *args, **kwargs):
"""Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional arguments to pass ... | the_stack_v2_python_sparse | enaml/layout/factory_helper.py | bburan/enaml | train | 0 |
7057fff5234e94b5c122c62117fbef7bb856a7a4 | [
"if os.path.exists(task):\n with open(task, 'r', encoding='utf-8') as f:\n config = yaml.safe_load(f)\n outdir = os.path.dirname(task)\nelse:\n config = yaml.safe_load(task)\n outdir = '.'\nqueries = Task.queries(config)\nreturn (config['name'], config.get('options', {}), queries, outdir)",
... | <|body_start_0|>
if os.path.exists(task):
with open(task, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
outdir = os.path.dirname(task)
else:
config = yaml.safe_load(task)
outdir = '.'
queries = Task.queries(config)
... | YAML task configuration loader | Task | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""YAML task configuration loader"""
def load(task):
"""Loads a YAML configuration. Supports loading from a string or file path. Args: task: YAML string or file path to YAML configuration Returns: (name, queries, output directory)"""
<|body_0|>
def queries(config):... | stack_v2_sparse_classes_75kplus_train_008019 | 1,991 | permissive | [
{
"docstring": "Loads a YAML configuration. Supports loading from a string or file path. Args: task: YAML string or file path to YAML configuration Returns: (name, queries, output directory)",
"name": "load",
"signature": "def load(task)"
},
{
"docstring": "Gets a list of queries from this confi... | 3 | stack_v2_sparse_classes_30k_train_053452 | Implement the Python class `Task` described below.
Class description:
YAML task configuration loader
Method signatures and docstrings:
- def load(task): Loads a YAML configuration. Supports loading from a string or file path. Args: task: YAML string or file path to YAML configuration Returns: (name, queries, output d... | Implement the Python class `Task` described below.
Class description:
YAML task configuration loader
Method signatures and docstrings:
- def load(task): Loads a YAML configuration. Supports loading from a string or file path. Args: task: YAML string or file path to YAML configuration Returns: (name, queries, output d... | e9a33203ef139402523860fe5e7e8ded7521ef16 | <|skeleton|>
class Task:
"""YAML task configuration loader"""
def load(task):
"""Loads a YAML configuration. Supports loading from a string or file path. Args: task: YAML string or file path to YAML configuration Returns: (name, queries, output directory)"""
<|body_0|>
def queries(config):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Task:
"""YAML task configuration loader"""
def load(task):
"""Loads a YAML configuration. Supports loading from a string or file path. Args: task: YAML string or file path to YAML configuration Returns: (name, queries, output directory)"""
if os.path.exists(task):
with open(ta... | the_stack_v2_python_sparse | src/python/paperai/report/task.py | neuml/paperai | train | 1,025 |
7a87f9c55b7753fd63557ef72ee8a5708aa00ffb | [
"super(EncoderMix, self).__init__()\ntyp = etype.lstrip('vgg').rstrip('p')\nif typ not in ['lstm', 'gru', 'blstm', 'bgru']:\n logging.error('Error: need to specify an appropriate encoder architecture')\nif etype.startswith('vgg'):\n if etype[-1] == 'p':\n self.enc_mix = torch.nn.ModuleList([VGG2L(in_ch... | <|body_start_0|>
super(EncoderMix, self).__init__()
typ = etype.lstrip('vgg').rstrip('p')
if typ not in ['lstm', 'gru', 'blstm', 'bgru']:
logging.error('Error: need to specify an appropriate encoder architecture')
if etype.startswith('vgg'):
if etype[-1] == 'p':
... | Encoder module for the case of multi-speaker mixture speech. :param str etype: type of encoder network :param int idim: number of dimensions of encoder network :param int elayers_sd: number of layers of speaker differentiate part in encoder network :param int elayers_rec: number of layers of shared recognition part in ... | EncoderMix | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderMix:
"""Encoder module for the case of multi-speaker mixture speech. :param str etype: type of encoder network :param int idim: number of dimensions of encoder network :param int elayers_sd: number of layers of speaker differentiate part in encoder network :param int elayers_rec: number of... | stack_v2_sparse_classes_75kplus_train_008020 | 30,819 | permissive | [
{
"docstring": "Initialize the encoder of single-channel multi-speaker ASR.",
"name": "__init__",
"signature": "def __init__(self, etype, idim, elayers_sd, elayers_rec, eunits, eprojs, subsample, dropout, num_spkrs=2, in_channel=1)"
},
{
"docstring": "Encodermix forward. :param torch.Tensor xs_p... | 2 | stack_v2_sparse_classes_30k_train_033604 | Implement the Python class `EncoderMix` described below.
Class description:
Encoder module for the case of multi-speaker mixture speech. :param str etype: type of encoder network :param int idim: number of dimensions of encoder network :param int elayers_sd: number of layers of speaker differentiate part in encoder ne... | Implement the Python class `EncoderMix` described below.
Class description:
Encoder module for the case of multi-speaker mixture speech. :param str etype: type of encoder network :param int idim: number of dimensions of encoder network :param int elayers_sd: number of layers of speaker differentiate part in encoder ne... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class EncoderMix:
"""Encoder module for the case of multi-speaker mixture speech. :param str etype: type of encoder network :param int idim: number of dimensions of encoder network :param int elayers_sd: number of layers of speaker differentiate part in encoder network :param int elayers_rec: number of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderMix:
"""Encoder module for the case of multi-speaker mixture speech. :param str etype: type of encoder network :param int idim: number of dimensions of encoder network :param int elayers_sd: number of layers of speaker differentiate part in encoder network :param int elayers_rec: number of layers of sh... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/e2e_asr_mix.py | espnet/espnet | train | 7,242 |
b7b88671aea69106843e7550c5b12571a61d990a | [
"cleaned_name = self._clean_name(filename)\nself.move_file_to_private_folder(cleaned_name)\nreturn cleaned_name",
"public_location = safe_join(self.public_location, filename)\nprivate_location = safe_join(self.location, filename)\ncopy_source = safe_join(self.bucket_name, public_location)\nself.bucket.Object(priv... | <|body_start_0|>
cleaned_name = self._clean_name(filename)
self.move_file_to_private_folder(cleaned_name)
return cleaned_name
<|end_body_0|>
<|body_start_1|>
public_location = safe_join(self.public_location, filename)
private_location = safe_join(self.location, filename)
... | AWS images storage for direct upload. | S3DirectUploadStorage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3DirectUploadStorage:
"""AWS images storage for direct upload."""
def save(self, filename, content=None, max_length=None):
"""Saving image url in model field."""
<|body_0|>
def move_file_to_private_folder(self, filename):
"""Moving from public folder to private.... | stack_v2_sparse_classes_75kplus_train_008021 | 1,968 | no_license | [
{
"docstring": "Saving image url in model field.",
"name": "save",
"signature": "def save(self, filename, content=None, max_length=None)"
},
{
"docstring": "Moving from public folder to private. Because public folder used for direct upload from frontend.",
"name": "move_file_to_private_folde... | 3 | stack_v2_sparse_classes_30k_val_002194 | Implement the Python class `S3DirectUploadStorage` described below.
Class description:
AWS images storage for direct upload.
Method signatures and docstrings:
- def save(self, filename, content=None, max_length=None): Saving image url in model field.
- def move_file_to_private_folder(self, filename): Moving from publ... | Implement the Python class `S3DirectUploadStorage` described below.
Class description:
AWS images storage for direct upload.
Method signatures and docstrings:
- def save(self, filename, content=None, max_length=None): Saving image url in model field.
- def move_file_to_private_folder(self, filename): Moving from publ... | f710b22f3acd6d7bfe639e83a4729c25bc5ca501 | <|skeleton|>
class S3DirectUploadStorage:
"""AWS images storage for direct upload."""
def save(self, filename, content=None, max_length=None):
"""Saving image url in model field."""
<|body_0|>
def move_file_to_private_folder(self, filename):
"""Moving from public folder to private.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class S3DirectUploadStorage:
"""AWS images storage for direct upload."""
def save(self, filename, content=None, max_length=None):
"""Saving image url in model field."""
cleaned_name = self._clean_name(filename)
self.move_file_to_private_folder(cleaned_name)
return cleaned_name
... | the_stack_v2_python_sparse | server/apps/users/storages.py | aslan-im/python-base-graphql-api | train | 0 |
07b96c93f87a7ee435316625171e7f7271168ba5 | [
"super().__init__()\nself.conv = ConvLayer(config)\nself.classify_layer = nn.Linear(config.qa_conv_out_channel * 3, 2, bias=True)",
"concat_output = self.conv(kwargs['x'])\nlogits = self.classify_layer(concat_output)\nreturn logits"
] | <|body_start_0|>
super().__init__()
self.conv = ConvLayer(config)
self.classify_layer = nn.Linear(config.qa_conv_out_channel * 3, 2, bias=True)
<|end_body_0|>
<|body_start_1|>
concat_output = self.conv(kwargs['x'])
logits = self.classify_layer(concat_output)
return logit... | Simple QA conv head | QAConvHead | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QAConvHead:
"""Simple QA conv head"""
def __init__(self, config):
"""Args: config (ModelArguments): ModelArguments"""
<|body_0|>
def forward(self, **kwargs):
"""Args: **kwargs: x, input_ids, sep_token_id Returns: torch.Tensor: output logits (batch_size * max_seq_... | stack_v2_sparse_classes_75kplus_train_008022 | 2,582 | permissive | [
{
"docstring": "Args: config (ModelArguments): ModelArguments",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Args: **kwargs: x, input_ids, sep_token_id Returns: torch.Tensor: output logits (batch_size * max_seq_legth * 2)",
"name": "forward",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_047610 | Implement the Python class `QAConvHead` described below.
Class description:
Simple QA conv head
Method signatures and docstrings:
- def __init__(self, config): Args: config (ModelArguments): ModelArguments
- def forward(self, **kwargs): Args: **kwargs: x, input_ids, sep_token_id Returns: torch.Tensor: output logits (... | Implement the Python class `QAConvHead` described below.
Class description:
Simple QA conv head
Method signatures and docstrings:
- def __init__(self, config): Args: config (ModelArguments): ModelArguments
- def forward(self, **kwargs): Args: **kwargs: x, input_ids, sep_token_id Returns: torch.Tensor: output logits (... | ea60d7a7b0f22c9e2e3b71d1d80cc2f00805e3fa | <|skeleton|>
class QAConvHead:
"""Simple QA conv head"""
def __init__(self, config):
"""Args: config (ModelArguments): ModelArguments"""
<|body_0|>
def forward(self, **kwargs):
"""Args: **kwargs: x, input_ids, sep_token_id Returns: torch.Tensor: output logits (batch_size * max_seq_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QAConvHead:
"""Simple QA conv head"""
def __init__(self, config):
"""Args: config (ModelArguments): ModelArguments"""
super().__init__()
self.conv = ConvLayer(config)
self.classify_layer = nn.Linear(config.qa_conv_out_channel * 3, 2, bias=True)
def forward(self, **kwa... | the_stack_v2_python_sparse | solution/reader/architectures/modeling_heads.py | boostcampaitech2/mrc-level2-nlp-14 | train | 7 |
ac42c35270a1cee73a104ce1c7d4262db6bd936c | [
"delete_blocks = None\ndataLifetime = subscriptionInfo.get('DatasetLifetime', 0) or 0\nif custodialFlag:\n sites = subscriptionInfo['CustodialSites']\nelse:\n sites = subscriptionInfo['NonCustodialSites']\ndelete_blocks = 1 if subscriptionInfo.get('DeleteFromSource', False) else None\nbinds = []\nfor site in ... | <|body_start_0|>
delete_blocks = None
dataLifetime = subscriptionInfo.get('DatasetLifetime', 0) or 0
if custodialFlag:
sites = subscriptionInfo['CustodialSites']
else:
sites = subscriptionInfo['NonCustodialSites']
delete_blocks = 1 if subscriptionInfo.get(... | _NewSubscription_ Create a new subscription in the database | NewSubscription | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewSubscription:
"""_NewSubscription_ Create a new subscription in the database"""
def _createPhEDExSubBinds(self, datasetID, subscriptionInfo, custodialFlag):
"""Creates the database binds for both custodial and non custodial data placements. :param datasetID: integer with the datas... | stack_v2_sparse_classes_75kplus_train_008023 | 2,546 | permissive | [
{
"docstring": "Creates the database binds for both custodial and non custodial data placements. :param datasetID: integer with the dataset id :param subscriptionInfo: dictionary object from the request spec :param custodialFlag: boolean flag defining whether it's custodial or not :return: a list of dictionary ... | 2 | stack_v2_sparse_classes_30k_train_021115 | Implement the Python class `NewSubscription` described below.
Class description:
_NewSubscription_ Create a new subscription in the database
Method signatures and docstrings:
- def _createPhEDExSubBinds(self, datasetID, subscriptionInfo, custodialFlag): Creates the database binds for both custodial and non custodial ... | Implement the Python class `NewSubscription` described below.
Class description:
_NewSubscription_ Create a new subscription in the database
Method signatures and docstrings:
- def _createPhEDExSubBinds(self, datasetID, subscriptionInfo, custodialFlag): Creates the database binds for both custodial and non custodial ... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class NewSubscription:
"""_NewSubscription_ Create a new subscription in the database"""
def _createPhEDExSubBinds(self, datasetID, subscriptionInfo, custodialFlag):
"""Creates the database binds for both custodial and non custodial data placements. :param datasetID: integer with the datas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewSubscription:
"""_NewSubscription_ Create a new subscription in the database"""
def _createPhEDExSubBinds(self, datasetID, subscriptionInfo, custodialFlag):
"""Creates the database binds for both custodial and non custodial data placements. :param datasetID: integer with the dataset id :param ... | the_stack_v2_python_sparse | src/python/WMComponent/DBS3Buffer/MySQL/NewSubscription.py | vkuznet/WMCore | train | 0 |
4274f0f2d0b71170208542db520dd12ccb1761bd | [
"logger.info('+++ Working with Donation class')\nlogger.info('+++ Populating Donation table with initial data')\nDONOR = 0\nAMOUNT = 1\ndonations = [('Speedy Gonzales', 10), ('Ivan Smirnoff', 20), ('Charles Goldberg', 30), ('Toshiro Asai', 40), ('Abdul Abdulah', 50), ('Speedy Gonzales', 100), ('Ivan Smirnoff', 200)... | <|body_start_0|>
logger.info('+++ Working with Donation class')
logger.info('+++ Populating Donation table with initial data')
DONOR = 0
AMOUNT = 1
donations = [('Speedy Gonzales', 10), ('Ivan Smirnoff', 20), ('Charles Goldberg', 30), ('Toshiro Asai', 40), ('Abdul Abdulah', 50), ... | This class defines donations. | Donation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Donation:
"""This class defines donations."""
def populate():
"""Populate Donation table"""
<|body_0|>
def report():
"""Calculates NUMBER, TOTAL, AVERAGE of donations per Donor Updates Donor table: number, total, average"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_008024 | 6,474 | no_license | [
{
"docstring": "Populate Donation table",
"name": "populate",
"signature": "def populate()"
},
{
"docstring": "Calculates NUMBER, TOTAL, AVERAGE of donations per Donor Updates Donor table: number, total, average",
"name": "report",
"signature": "def report()"
}
] | 2 | stack_v2_sparse_classes_30k_train_018611 | Implement the Python class `Donation` described below.
Class description:
This class defines donations.
Method signatures and docstrings:
- def populate(): Populate Donation table
- def report(): Calculates NUMBER, TOTAL, AVERAGE of donations per Donor Updates Donor table: number, total, average | Implement the Python class `Donation` described below.
Class description:
This class defines donations.
Method signatures and docstrings:
- def populate(): Populate Donation table
- def report(): Calculates NUMBER, TOTAL, AVERAGE of donations per Donor Updates Donor table: number, total, average
<|skeleton|>
class D... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class Donation:
"""This class defines donations."""
def populate():
"""Populate Donation table"""
<|body_0|>
def report():
"""Calculates NUMBER, TOTAL, AVERAGE of donations per Donor Updates Donor table: number, total, average"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Donation:
"""This class defines donations."""
def populate():
"""Populate Donation table"""
logger.info('+++ Working with Donation class')
logger.info('+++ Populating Donation table with initial data')
DONOR = 0
AMOUNT = 1
donations = [('Speedy Gonzales', 1... | the_stack_v2_python_sparse | students/Wieslaw_Pucilowski/Lesson07/Mailroom/question2/create_donors_db.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
b94a5bd90b8023e9f286532be6030b404721d8c3 | [
"re = cloudparking_service().mockCarInOut(send_data['carNumA'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = cloudparking_service().mockCarInOut(send_data['carNumB'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, ... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNumA'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = cloudparking_service().mockCarInOut(send_data['carNumB'], 0, send_... | 智能盘点,选择智泊云车场,然后按在场车辆盘点,上传盘点表格,上传成功后,勾选“将未匹配的车辆补录进场”,点击确定后,不在表格中的车辆都被盘点走, 在在场车辆中查看不到被盘点走的车辆,在异常进场中可以查看到该被盘点走的车辆,并且未匹配的车辆以当前时间补录到在场车辆中 | TestIntelligenceCleanCarByFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIntelligenceCleanCarByFile:
"""智能盘点,选择智泊云车场,然后按在场车辆盘点,上传盘点表格,上传成功后,勾选“将未匹配的车辆补录进场”,点击确定后,不在表格中的车辆都被盘点走, 在在场车辆中查看不到被盘点走的车辆,在异常进场中可以查看到该被盘点走的车辆,并且未匹配的车辆以当前时间补录到在场车辆中"""
def test_mockCarInA(self, send_data, expect):
"""模拟车辆A进场"""
<|body_0|>
def test_mockCarInB(self, sen... | stack_v2_sparse_classes_75kplus_train_008025 | 3,111 | no_license | [
{
"docstring": "模拟车辆A进场",
"name": "test_mockCarInA",
"signature": "def test_mockCarInA(self, send_data, expect)"
},
{
"docstring": "模拟车辆B进场",
"name": "test_mockCarInB",
"signature": "def test_mockCarInB(self, send_data, expect)"
},
{
"docstring": "上传盘点表格并-勾选-将未匹配的车辆C补录进场",
"n... | 6 | stack_v2_sparse_classes_30k_train_038595 | Implement the Python class `TestIntelligenceCleanCarByFile` described below.
Class description:
智能盘点,选择智泊云车场,然后按在场车辆盘点,上传盘点表格,上传成功后,勾选“将未匹配的车辆补录进场”,点击确定后,不在表格中的车辆都被盘点走, 在在场车辆中查看不到被盘点走的车辆,在异常进场中可以查看到该被盘点走的车辆,并且未匹配的车辆以当前时间补录到在场车辆中
Method signatures and docstrings:
- def test_mockCarInA(self, send_data, expect): 模拟车辆A进场... | Implement the Python class `TestIntelligenceCleanCarByFile` described below.
Class description:
智能盘点,选择智泊云车场,然后按在场车辆盘点,上传盘点表格,上传成功后,勾选“将未匹配的车辆补录进场”,点击确定后,不在表格中的车辆都被盘点走, 在在场车辆中查看不到被盘点走的车辆,在异常进场中可以查看到该被盘点走的车辆,并且未匹配的车辆以当前时间补录到在场车辆中
Method signatures and docstrings:
- def test_mockCarInA(self, send_data, expect): 模拟车辆A进场... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestIntelligenceCleanCarByFile:
"""智能盘点,选择智泊云车场,然后按在场车辆盘点,上传盘点表格,上传成功后,勾选“将未匹配的车辆补录进场”,点击确定后,不在表格中的车辆都被盘点走, 在在场车辆中查看不到被盘点走的车辆,在异常进场中可以查看到该被盘点走的车辆,并且未匹配的车辆以当前时间补录到在场车辆中"""
def test_mockCarInA(self, send_data, expect):
"""模拟车辆A进场"""
<|body_0|>
def test_mockCarInB(self, sen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestIntelligenceCleanCarByFile:
"""智能盘点,选择智泊云车场,然后按在场车辆盘点,上传盘点表格,上传成功后,勾选“将未匹配的车辆补录进场”,点击确定后,不在表格中的车辆都被盘点走, 在在场车辆中查看不到被盘点走的车辆,在异常进场中可以查看到该被盘点走的车辆,并且未匹配的车辆以当前时间补录到在场车辆中"""
def test_mockCarInA(self, send_data, expect):
"""模拟车辆A进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum... | the_stack_v2_python_sparse | test_suite/informationSearch/carNumSearch/test_intelligenceCleanCarByFile.py | oyebino/pomp_api | train | 1 |
644b7a53588067c05d381d23264f81a1f9986802 | [
"if not s:\n return 0\nres = 0\nstack = [-1]\nfor i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n else:\n stack.pop()\n if not stack:\n stack.append(i)\n else:\n res = max(res, i - stack[-1])\nreturn res",
"dp = [0] * len(s)\nres = 0\nfor i in r... | <|body_start_0|>
if not s:
return 0
res = 0
stack = [-1]
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s: str) -> int:
"""使用栈 :param s: :return:"""
<|body_0|>
def longestValidParentheses1(self, s: str) -> int:
"""使用动态规划 当s[i] == ')' 时 1.判断s[i - 1] 是否等于'(' 如果s[i - 1] 等于 '(', dp[i] = dp[i - 2] + 2 2. 如果s[i - 1] 等于 ')' 并且s[i - ... | stack_v2_sparse_classes_75kplus_train_008026 | 1,733 | no_license | [
{
"docstring": "使用栈 :param s: :return:",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s: str) -> int"
},
{
"docstring": "使用动态规划 当s[i] == ')' 时 1.判断s[i - 1] 是否等于'(' 如果s[i - 1] 等于 '(', dp[i] = dp[i - 2] + 2 2. 如果s[i - 1] 等于 ')' 并且s[i - 1 - dp[i - 1]] 为 '(', 那么... | 2 | stack_v2_sparse_classes_30k_train_027247 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s: str) -> int: 使用栈 :param s: :return:
- def longestValidParentheses1(self, s: str) -> int: 使用动态规划 当s[i] == ')' 时 1.判断s[i - 1] 是否等于'(' 如果s[i - 1... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s: str) -> int: 使用栈 :param s: :return:
- def longestValidParentheses1(self, s: str) -> int: 使用动态规划 当s[i] == ')' 时 1.判断s[i - 1] 是否等于'(' 如果s[i - 1... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s: str) -> int:
"""使用栈 :param s: :return:"""
<|body_0|>
def longestValidParentheses1(self, s: str) -> int:
"""使用动态规划 当s[i] == ')' 时 1.判断s[i - 1] 是否等于'(' 如果s[i - 1] 等于 '(', dp[i] = dp[i - 2] + 2 2. 如果s[i - 1] 等于 ')' 并且s[i - ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestValidParentheses(self, s: str) -> int:
"""使用栈 :param s: :return:"""
if not s:
return 0
res = 0
stack = [-1]
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()... | the_stack_v2_python_sparse | datastructure/dp_exercise/LongestValidParentheses.py | yinhuax/leet_code | train | 0 | |
7a6a93655ff455fd58c5fbcb564538939bfff224 | [
"sorted_s = sorted(s)\nh_list = []\ncount = 0\nfor c, i in enumerate(sorted_s):\n if c + 1 <= len(sorted_s) - 1 and sorted_s[c + 1] == sorted_s[c]:\n count += 1\n else:\n count += 1\n heapq.heappush(h_list, (-count, i))\n count = 0\nresult = ''\nfor _ in xrange(len(h_list)):\n c... | <|body_start_0|>
sorted_s = sorted(s)
h_list = []
count = 0
for c, i in enumerate(sorted_s):
if c + 1 <= len(sorted_s) - 1 and sorted_s[c + 1] == sorted_s[c]:
count += 1
else:
count += 1
heapq.heappush(h_list, (-coun... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def frequencySort(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def rewrite(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sorted_s = sorted(s)
h_list = []
count = 0
for ... | stack_v2_sparse_classes_75kplus_train_008027 | 1,934 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "frequencySort",
"signature": "def frequencySort(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "rewrite",
"signature": "def rewrite(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003846 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def frequencySort(self, s): :type s: str :rtype: str
- def rewrite(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def frequencySort(self, s): :type s: str :rtype: str
- def rewrite(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def frequencySort(self, s):
""":t... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def frequencySort(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def rewrite(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def frequencySort(self, s):
""":type s: str :rtype: str"""
sorted_s = sorted(s)
h_list = []
count = 0
for c, i in enumerate(sorted_s):
if c + 1 <= len(sorted_s) - 1 and sorted_s[c + 1] == sorted_s[c]:
count += 1
else:
... | the_stack_v2_python_sparse | co_google/451_Sort_Characters_By_Frequency.py | vsdrun/lc_public | train | 6 | |
3c1b37ad792f9f98a0426f9e45f95d49afedd1a4 | [
"data = dict(input_context)\ndata['response_format'] = 'json'\nif self.method == 'GET':\n response = test_case.client.get(self.path, data, follow=self.final_views is not None)\nelif self.method == 'POST':\n response = test_case.client.post(self.path, data, follow=self.final_views is not None)\nelse:\n test... | <|body_start_0|>
data = dict(input_context)
data['response_format'] = 'json'
if self.method == 'GET':
response = test_case.client.get(self.path, data, follow=self.final_views is not None)
elif self.method == 'POST':
response = test_case.client.post(self.path, data... | Represents various attributes of a Web page that will be tested. NOTE: to simulate uploading files, a value of the input_context may be an open filehandle. This does not exactly play nicely with the other abstractions in the system; in particular, the functions in the Conditions object must not read this filehandle. | WebTarget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebTarget:
"""Represents various attributes of a Web page that will be tested. NOTE: to simulate uploading files, a value of the input_context may be an open filehandle. This does not exactly play nicely with the other abstractions in the system; in particular, the functions in the Conditions obj... | stack_v2_sparse_classes_75kplus_train_008028 | 9,947 | permissive | [
{
"docstring": "Use the Client object in `test_case` to call up the JSON-formatted version of the given page, test the HTTP-related metadata such as the status code, and return the JSON data to the caller.",
"name": "invoke",
"signature": "def invoke(self, test_case, input_context)"
},
{
"docstr... | 2 | null | Implement the Python class `WebTarget` described below.
Class description:
Represents various attributes of a Web page that will be tested. NOTE: to simulate uploading files, a value of the input_context may be an open filehandle. This does not exactly play nicely with the other abstractions in the system; in particul... | Implement the Python class `WebTarget` described below.
Class description:
Represents various attributes of a Web page that will be tested. NOTE: to simulate uploading files, a value of the input_context may be an open filehandle. This does not exactly play nicely with the other abstractions in the system; in particul... | 5cdbf3066e8f59a1b5e42d1ae36bd8ad04301bee | <|skeleton|>
class WebTarget:
"""Represents various attributes of a Web page that will be tested. NOTE: to simulate uploading files, a value of the input_context may be an open filehandle. This does not exactly play nicely with the other abstractions in the system; in particular, the functions in the Conditions obj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebTarget:
"""Represents various attributes of a Web page that will be tested. NOTE: to simulate uploading files, a value of the input_context may be an open filehandle. This does not exactly play nicely with the other abstractions in the system; in particular, the functions in the Conditions object must not ... | the_stack_v2_python_sparse | main/moretests/expectation.py | clickwork/clickwork | train | 1 |
012dd7d35d274a896c1cfb6cf70acf8b84fe5f96 | [
"try:\n return copy_job_manager.list()\nexcept HTTP_EXCEPTION as e:\n api.abort(e.code, e.payload)\nexcept Exception as e:\n logging.exception(e, exc_info=True)\n api.abort(500, str(e))",
"try:\n return (copy_job_manager.create(request.json), 201)\nexcept HTTP_EXCEPTION as e:\n api.abort(e.code,... | <|body_start_0|>
try:
return copy_job_manager.list()
except HTTP_EXCEPTION as e:
api.abort(e.code, e.payload)
except Exception as e:
logging.exception(e, exc_info=True)
api.abort(500, str(e))
<|end_body_0|>
<|body_start_1|>
try:
... | CopyJobList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyJobList:
def get(self):
"""List all Copy Jobs"""
<|body_0|>
def post(self):
"""Create a new Copy Job"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
return copy_job_manager.list()
except HTTP_EXCEPTION as e:
... | stack_v2_sparse_classes_75kplus_train_008029 | 3,261 | permissive | [
{
"docstring": "List all Copy Jobs",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new Copy Job",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `CopyJobList` described below.
Class description:
Implement the CopyJobList class.
Method signatures and docstrings:
- def get(self): List all Copy Jobs
- def post(self): Create a new Copy Job | Implement the Python class `CopyJobList` described below.
Class description:
Implement the CopyJobList class.
Method signatures and docstrings:
- def get(self): List all Copy Jobs
- def post(self): Create a new Copy Job
<|skeleton|>
class CopyJobList:
def get(self):
"""List all Copy Jobs"""
<|bo... | a8ca673fd3998ce227eeeed39612b36cd2dc4ee5 | <|skeleton|>
class CopyJobList:
def get(self):
"""List all Copy Jobs"""
<|body_0|>
def post(self):
"""Create a new Copy Job"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CopyJobList:
def get(self):
"""List all Copy Jobs"""
try:
return copy_job_manager.list()
except HTTP_EXCEPTION as e:
api.abort(e.code, e.payload)
except Exception as e:
logging.exception(e, exc_info=True)
api.abort(500, str(e))
... | the_stack_v2_python_sparse | src/backend/api/views/copy_job_views.py | FredHutch/motuz | train | 106 | |
5bb142f077e7a28805d934e8b15676ce973ad8c9 | [
"if serialized_batches is not None:\n make_variant_fn = partial(core_ops.io_arrow_serialized_dataset, serialized_batches)\nelif arrow_buffer is None:\n raise ValueError('Must set either serialzied_batches or arrow_buffer')\nelif not tf.executing_eagerly():\n raise ValueError('Using arrow_buffer for zero-co... | <|body_start_0|>
if serialized_batches is not None:
make_variant_fn = partial(core_ops.io_arrow_serialized_dataset, serialized_batches)
elif arrow_buffer is None:
raise ValueError('Must set either serialzied_batches or arrow_buffer')
elif not tf.executing_eagerly():
... | An Arrow Dataset from record batches in memory, or a Pandas DataFrame. | ArrowDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrowDataset:
"""An Arrow Dataset from record batches in memory, or a Pandas DataFrame."""
def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow_buffer=None):
"""Create an ArrowDataset from a Tensor of se... | stack_v2_sparse_classes_75kplus_train_008030 | 27,598 | permissive | [
{
"docstring": "Create an ArrowDataset from a Tensor of serialized batches. This constructor requires pyarrow to be installed. Args: serialized_batches: A string Tensor as a serialized buffer containing Arrow record batches in Arrow File format columns: A list of column indices to be used in the Dataset output_... | 3 | stack_v2_sparse_classes_30k_train_025385 | Implement the Python class `ArrowDataset` described below.
Class description:
An Arrow Dataset from record batches in memory, or a Pandas DataFrame.
Method signatures and docstrings:
- def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow... | Implement the Python class `ArrowDataset` described below.
Class description:
An Arrow Dataset from record batches in memory, or a Pandas DataFrame.
Method signatures and docstrings:
- def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow... | e219e295aa6a00b4b749487d56a79c18cc121574 | <|skeleton|>
class ArrowDataset:
"""An Arrow Dataset from record batches in memory, or a Pandas DataFrame."""
def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow_buffer=None):
"""Create an ArrowDataset from a Tensor of se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArrowDataset:
"""An Arrow Dataset from record batches in memory, or a Pandas DataFrame."""
def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow_buffer=None):
"""Create an ArrowDataset from a Tensor of serialized batc... | the_stack_v2_python_sparse | tensorflow_io/python/ops/arrow_dataset_ops.py | tensorflow/io | train | 694 |
50fa60b10976f3693c1c4b7d8fb71238856a3b9d | [
"res = []\nfor i in range(len(words)):\n for j in range(len(words)):\n if i != j:\n temp = words[i] + words[j]\n if temp == temp[::-1]:\n res.append([i, j])\nreturn res",
"def isPalindrome(temp):\n return temp == temp[::-1]\ndict, res = ({}, [])\nfor i in range(le... | <|body_start_0|>
res = []
for i in range(len(words)):
for j in range(len(words)):
if i != j:
temp = words[i] + words[j]
if temp == temp[::-1]:
res.append([i, j])
return res
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairsSol2(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r... | stack_v2_sparse_classes_75kplus_train_008031 | 2,198 | no_license | [
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairsSol1",
"signature": "def palindromePairsSol1(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairsSol2",
"signature": "def palindromePairsSol2(sel... | 2 | stack_v2_sparse_classes_30k_train_013386 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairsSol1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairsSol2(self, words): :type words: List[str] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairsSol1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairsSol2(self, words): :type words: List[str] :rtype: List[List[int]]
<|ske... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairsSol2(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
res = []
for i in range(len(words)):
for j in range(len(words)):
if i != j:
temp = words[i] + words[j]
if temp == tem... | the_stack_v2_python_sparse | google/hard/palindrome_pairs.py | gerrycfchang/leetcode-python | train | 2 | |
18515dc63d418c56d9edbc4931ab80fe02984372 | [
"if is_zip(path):\n hosts, services, vulns, notes = (Pdict(), Pdict(), Pdict(), Pdict())\n with ZipFile(path) as fzip:\n for ftmp in [fname for fname in fzip.namelist() if re.match(cls.ARCHIVE_PATHS, fname)]:\n thosts, tservices, tvulns, tnotes = NmapParser._parse_data(file_from_zip(path, ft... | <|body_start_0|>
if is_zip(path):
hosts, services, vulns, notes = (Pdict(), Pdict(), Pdict(), Pdict())
with ZipFile(path) as fzip:
for ftmp in [fname for fname in fzip.namelist() if re.match(cls.ARCHIVE_PATHS, fname)]:
thosts, tservices, tvulns, tnotes... | nmap xml output parser | NmapParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NmapParser:
"""nmap xml output parser"""
def parse_path(cls, path):
"""parse data from path"""
<|body_0|>
def _parse_data(data):
"""parse raw string data"""
<|body_1|>
def _parse_hosts(report):
"""parse hosts"""
<|body_2|>
def _p... | stack_v2_sparse_classes_75kplus_train_008032 | 4,535 | permissive | [
{
"docstring": "parse data from path",
"name": "parse_path",
"signature": "def parse_path(cls, path)"
},
{
"docstring": "parse raw string data",
"name": "_parse_data",
"signature": "def _parse_data(data)"
},
{
"docstring": "parse hosts",
"name": "_parse_hosts",
"signature... | 5 | stack_v2_sparse_classes_30k_train_012550 | Implement the Python class `NmapParser` described below.
Class description:
nmap xml output parser
Method signatures and docstrings:
- def parse_path(cls, path): parse data from path
- def _parse_data(data): parse raw string data
- def _parse_hosts(report): parse hosts
- def _parse_services(report): parse services
- ... | Implement the Python class `NmapParser` described below.
Class description:
nmap xml output parser
Method signatures and docstrings:
- def parse_path(cls, path): parse data from path
- def _parse_data(data): parse raw string data
- def _parse_hosts(report): parse hosts
- def _parse_services(report): parse services
- ... | dc382da4fb60f2cfba69a4456a4fa430d6cb77ba | <|skeleton|>
class NmapParser:
"""nmap xml output parser"""
def parse_path(cls, path):
"""parse data from path"""
<|body_0|>
def _parse_data(data):
"""parse raw string data"""
<|body_1|>
def _parse_hosts(report):
"""parse hosts"""
<|body_2|>
def _p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NmapParser:
"""nmap xml output parser"""
def parse_path(cls, path):
"""parse data from path"""
if is_zip(path):
hosts, services, vulns, notes = (Pdict(), Pdict(), Pdict(), Pdict())
with ZipFile(path) as fzip:
for ftmp in [fname for fname in fzip.nam... | the_stack_v2_python_sparse | sner/server/parser/nmap.py | kovariktomas/sner4 | train | 0 |
290af933769b06992b35bf9262b8bc0d36f4d611 | [
"self.resize_factor = resize_factor\nself.crop_size = crop_size\nself.hflip = hflip\nself.p_hflip = p_hflip\nself.rot = rot\nself.angle = angle",
"dataset_dict = copy.deepcopy(dataset_dict)\nimage = utils.read_image(dataset_dict['file_name'], format='BGR')\nnew_shape = (int(image.shape[0] * self.resize_factor), i... | <|body_start_0|>
self.resize_factor = resize_factor
self.crop_size = crop_size
self.hflip = hflip
self.p_hflip = p_hflip
self.rot = rot
self.angle = angle
<|end_body_0|>
<|body_start_1|>
dataset_dict = copy.deepcopy(dataset_dict)
image = utils.read_image(... | A mapper to add data augmentation at the train dataloader. | DataAugmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataAugmentation:
"""A mapper to add data augmentation at the train dataloader."""
def __init__(self, resize_factor=1, crop_size=[1, 1], hflip=False, p_hflip=0.5, rot=False, angle=0):
"""Args: resize_factor (float): percentage of the original image size. crop_size (list of floats): r... | stack_v2_sparse_classes_75kplus_train_008033 | 29,307 | no_license | [
{
"docstring": "Args: resize_factor (float): percentage of the original image size. crop_size (list of floats): relative range of the original image size, if different to [1,1], apply random crop. hflip (bool): if True apply horizontal flip. p_hflip (float): if hflip=True, probability to apply horizontal flip. ... | 2 | stack_v2_sparse_classes_30k_val_001559 | Implement the Python class `DataAugmentation` described below.
Class description:
A mapper to add data augmentation at the train dataloader.
Method signatures and docstrings:
- def __init__(self, resize_factor=1, crop_size=[1, 1], hflip=False, p_hflip=0.5, rot=False, angle=0): Args: resize_factor (float): percentage ... | Implement the Python class `DataAugmentation` described below.
Class description:
A mapper to add data augmentation at the train dataloader.
Method signatures and docstrings:
- def __init__(self, resize_factor=1, crop_size=[1, 1], hflip=False, p_hflip=0.5, rot=False, angle=0): Args: resize_factor (float): percentage ... | 78ae8de8736417f110932b3b344f6fb5f65ec761 | <|skeleton|>
class DataAugmentation:
"""A mapper to add data augmentation at the train dataloader."""
def __init__(self, resize_factor=1, crop_size=[1, 1], hflip=False, p_hflip=0.5, rot=False, angle=0):
"""Args: resize_factor (float): percentage of the original image size. crop_size (list of floats): r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataAugmentation:
"""A mapper to add data augmentation at the train dataloader."""
def __init__(self, resize_factor=1, crop_size=[1, 1], hflip=False, p_hflip=0.5, rot=False, angle=0):
"""Args: resize_factor (float): percentage of the original image size. crop_size (list of floats): relative range... | the_stack_v2_python_sparse | w6-code/utils.py | claragarciamoll/MCV-M5_Group5 | train | 0 |
9e982ddf1c7047c538f70e63b8d6c17f44cf8c5d | [
"cf_status = response.status == 503\ncf_headers = response.headers.get('Server', '').startswith(b'cloudflare')\ncf_text = 'jschl_vc' in response.text and 'jschl_answer' in response.text\nreturn cf_status and cf_headers and cf_text",
"if not self.is_cloudflare(response):\n return response\nspider.logger.info('C... | <|body_start_0|>
cf_status = response.status == 503
cf_headers = response.headers.get('Server', '').startswith(b'cloudflare')
cf_text = 'jschl_vc' in response.text and 'jschl_answer' in response.text
return cf_status and cf_headers and cf_text
<|end_body_0|>
<|body_start_1|>
if ... | Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware | CloudFlareMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudFlareMiddleware:
"""Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware"""
def is_cloudflare(response):
"""Test if the given response contains the CloudFlare anti-bot protection"""
<|body... | stack_v2_sparse_classes_75kplus_train_008034 | 1,661 | permissive | [
{
"docstring": "Test if the given response contains the CloudFlare anti-bot protection",
"name": "is_cloudflare",
"signature": "def is_cloudflare(response)"
},
{
"docstring": "If we can identify a CloudFlare check on this page then use cfscrape to get the cookies",
"name": "process_response"... | 2 | stack_v2_sparse_classes_30k_test_001729 | Implement the Python class `CloudFlareMiddleware` described below.
Class description:
Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware
Method signatures and docstrings:
- def is_cloudflare(response): Test if the given response cont... | Implement the Python class `CloudFlareMiddleware` described below.
Class description:
Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware
Method signatures and docstrings:
- def is_cloudflare(response): Test if the given response cont... | 578fe203b8f4135dd223854d57eb961b977ca145 | <|skeleton|>
class CloudFlareMiddleware:
"""Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware"""
def is_cloudflare(response):
"""Test if the given response contains the CloudFlare anti-bot protection"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudFlareMiddleware:
"""Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware"""
def is_cloudflare(response):
"""Test if the given response contains the CloudFlare anti-bot protection"""
cf_status = respons... | the_stack_v2_python_sparse | misinformation/middlewares/cloudflaremiddleware.py | alan-turing-institute/misinformation-crawler | train | 6 |
2a9b3f4c34fca09e2f38503b62fd7d53626be0a1 | [
"api_path = '/api/v1/wbt/update'\nmsg = {'userId': str(data['user_id']), 'wbtTotal': data['lock'], 'wbtDelta': data['amount'], 'assetType': data['asset_type']}\nrequest_game_api(api_path, data['appid'], msg)",
"api_path = '/api/v1/nft/pour'\nmsg = {'userId': str(data['user_id']), 'id': data['id'] if isinstance(da... | <|body_start_0|>
api_path = '/api/v1/wbt/update'
msg = {'userId': str(data['user_id']), 'wbtTotal': data['lock'], 'wbtDelta': data['amount'], 'assetType': data['asset_type']}
request_game_api(api_path, data['appid'], msg)
<|end_body_0|>
<|body_start_1|>
api_path = '/api/v1/nft/pour'
... | GameApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameApi:
def distribute_erc20_asset(cls, data):
"""分发erc20资产到游戏 wbt"""
<|body_0|>
def distribute_erc721_asset(cls, data):
"""分发erc721资产到游戏"""
<|body_1|>
def distribute_props(cls, data):
"""分发道具到游戏"""
<|body_2|>
def notify_mintage_com... | stack_v2_sparse_classes_75kplus_train_008035 | 3,349 | no_license | [
{
"docstring": "分发erc20资产到游戏 wbt",
"name": "distribute_erc20_asset",
"signature": "def distribute_erc20_asset(cls, data)"
},
{
"docstring": "分发erc721资产到游戏",
"name": "distribute_erc721_asset",
"signature": "def distribute_erc721_asset(cls, data)"
},
{
"docstring": "分发道具到游戏",
"... | 4 | null | Implement the Python class `GameApi` described below.
Class description:
Implement the GameApi class.
Method signatures and docstrings:
- def distribute_erc20_asset(cls, data): 分发erc20资产到游戏 wbt
- def distribute_erc721_asset(cls, data): 分发erc721资产到游戏
- def distribute_props(cls, data): 分发道具到游戏
- def notify_mintage_comp... | Implement the Python class `GameApi` described below.
Class description:
Implement the GameApi class.
Method signatures and docstrings:
- def distribute_erc20_asset(cls, data): 分发erc20资产到游戏 wbt
- def distribute_erc721_asset(cls, data): 分发erc721资产到游戏
- def distribute_props(cls, data): 分发道具到游戏
- def notify_mintage_comp... | 37c239eadd01ab5ce8bc4d6d1f586951952154ad | <|skeleton|>
class GameApi:
def distribute_erc20_asset(cls, data):
"""分发erc20资产到游戏 wbt"""
<|body_0|>
def distribute_erc721_asset(cls, data):
"""分发erc721资产到游戏"""
<|body_1|>
def distribute_props(cls, data):
"""分发道具到游戏"""
<|body_2|>
def notify_mintage_com... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameApi:
def distribute_erc20_asset(cls, data):
"""分发erc20资产到游戏 wbt"""
api_path = '/api/v1/wbt/update'
msg = {'userId': str(data['user_id']), 'wbtTotal': data['lock'], 'wbtDelta': data['amount'], 'assetType': data['asset_type']}
request_game_api(api_path, data['appid'], msg)
... | the_stack_v2_python_sparse | app/game_api.py | trinity-project/nft-shop | train | 3 | |
27d3873fa83d022818448d188bd11429ec7c7598 | [
"try:\n w.OpenClipboard()\n value = w.GetClipboardData(win32con.CF_TEXT)\n w.CloseClipboard()\nexcept Exception as e:\n raise e\nelse:\n return value.decode('gbk')",
"try:\n w.OpenClipboard()\n w.EmptyClipboard()\n w.SetClipboardData(win32con.CF_UNICODETEXT, value)\n w.CloseClipboard()\... | <|body_start_0|>
try:
w.OpenClipboard()
value = w.GetClipboardData(win32con.CF_TEXT)
w.CloseClipboard()
except Exception as e:
raise e
else:
return value.decode('gbk')
<|end_body_0|>
<|body_start_1|>
try:
w.OpenClip... | Clipboard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clipboard:
def get_text():
"""获取剪切板的内容"""
<|body_0|>
def set_text(value):
"""设置剪切板内容"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
w.OpenClipboard()
value = w.GetClipboardData(win32con.CF_TEXT)
w.CloseClipb... | stack_v2_sparse_classes_75kplus_train_008036 | 834 | no_license | [
{
"docstring": "获取剪切板的内容",
"name": "get_text",
"signature": "def get_text()"
},
{
"docstring": "设置剪切板内容",
"name": "set_text",
"signature": "def set_text(value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045447 | Implement the Python class `Clipboard` described below.
Class description:
Implement the Clipboard class.
Method signatures and docstrings:
- def get_text(): 获取剪切板的内容
- def set_text(value): 设置剪切板内容 | Implement the Python class `Clipboard` described below.
Class description:
Implement the Clipboard class.
Method signatures and docstrings:
- def get_text(): 获取剪切板的内容
- def set_text(value): 设置剪切板内容
<|skeleton|>
class Clipboard:
def get_text():
"""获取剪切板的内容"""
<|body_0|>
def set_text(value):
... | febd932f05f13b02fcfa6ab839ee5a5a40ab294f | <|skeleton|>
class Clipboard:
def get_text():
"""获取剪切板的内容"""
<|body_0|>
def set_text(value):
"""设置剪切板内容"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Clipboard:
def get_text():
"""获取剪切板的内容"""
try:
w.OpenClipboard()
value = w.GetClipboardData(win32con.CF_TEXT)
w.CloseClipboard()
except Exception as e:
raise e
else:
return value.decode('gbk')
def set_text(value):... | the_stack_v2_python_sparse | Util/KeyWordDriven/KeyWorldTool/Clipboard.py | yangjourney/Web_UI_AutoTest | train | 1 | |
b1fe2b73b7bf45f7fd84998c05214da302e328e9 | [
"_url_path = '/InsuranceCentre/PortalLandingPage'\n_query_builder = Configuration.get_base_uri()\n_query_builder += _url_path\n_query_parameters = {'id': id}\n_query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization)\n_query_url = APIHelper.cle... | <|body_start_0|>
_url_path = '/InsuranceCentre/PortalLandingPage'
_query_builder = Configuration.get_base_uri()
_query_builder += _url_path
_query_parameters = {'id': id}
_query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.... | A Controller to access Endpoints in the easybimehlanding API. | MainController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainController:
"""A Controller to access Endpoints in the easybimehlanding API."""
def get_portal_landing_page(self, id, x_api_key):
"""Does a GET request to /InsuranceCentre/PortalLandingPage. در یافت اطلاعات لندینگ مراکز بیمه Args: id (string): دامنه یا زیر دامنه ی مرکز بیمه x_api... | stack_v2_sparse_classes_75kplus_train_008037 | 4,330 | permissive | [
{
"docstring": "Does a GET request to /InsuranceCentre/PortalLandingPage. در یافت اطلاعات لندینگ مراکز بیمه Args: id (string): دامنه یا زیر دامنه ی مرکز بیمه x_api_key (string): کلید اختصاصی ارتباط با سرور Returns: BaseModelPortalLandingPage: Response from the API. Raises: APIException: When an error occurs whi... | 2 | stack_v2_sparse_classes_30k_train_000982 | Implement the Python class `MainController` described below.
Class description:
A Controller to access Endpoints in the easybimehlanding API.
Method signatures and docstrings:
- def get_portal_landing_page(self, id, x_api_key): Does a GET request to /InsuranceCentre/PortalLandingPage. در یافت اطلاعات لندینگ مراکز بیم... | Implement the Python class `MainController` described below.
Class description:
A Controller to access Endpoints in the easybimehlanding API.
Method signatures and docstrings:
- def get_portal_landing_page(self, id, x_api_key): Does a GET request to /InsuranceCentre/PortalLandingPage. در یافت اطلاعات لندینگ مراکز بیم... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class MainController:
"""A Controller to access Endpoints in the easybimehlanding API."""
def get_portal_landing_page(self, id, x_api_key):
"""Does a GET request to /InsuranceCentre/PortalLandingPage. در یافت اطلاعات لندینگ مراکز بیمه Args: id (string): دامنه یا زیر دامنه ی مرکز بیمه x_api... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MainController:
"""A Controller to access Endpoints in the easybimehlanding API."""
def get_portal_landing_page(self, id, x_api_key):
"""Does a GET request to /InsuranceCentre/PortalLandingPage. در یافت اطلاعات لندینگ مراکز بیمه Args: id (string): دامنه یا زیر دامنه ی مرکز بیمه x_api_key (string)... | the_stack_v2_python_sparse | easybimehlanding/controllers/main_controller.py | kmelodi/EasyBimehLanding_Python | train | 0 |
15d20dc5ff56947e870fe2f864089ab2b7779079 | [
"ncols = self.max_num_components - 2\nfig, axes = plt.subplots(ncols=ncols, figsize=(panelsize[0] * ncols, panelsize[1]))\nfor i, model in enumerate(self.models):\n model.plot_pdfs(ax=axes[i], **kwargs)\n if i == np.argmin(self.BIC):\n axes[i].set_title('SELECTED')",
"if aic:\n ind = np.argmin(sel... | <|body_start_0|>
ncols = self.max_num_components - 2
fig, axes = plt.subplots(ncols=ncols, figsize=(panelsize[0] * ncols, panelsize[1]))
for i, model in enumerate(self.models):
model.plot_pdfs(ax=axes[i], **kwargs)
if i == np.argmin(self.BIC):
axes[i].set_... | Methods for visualizing model selection procedure. | ModelSelectionVisualization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelSelectionVisualization:
"""Methods for visualizing model selection procedure."""
def plot_models(self, panelsize=(3, 2), **kwargs):
"""Plot model for each number of components."""
<|body_0|>
def plot_information_criteria(self, bic=True, aic=True, ax=None, **kwargs):... | stack_v2_sparse_classes_75kplus_train_008038 | 2,169 | permissive | [
{
"docstring": "Plot model for each number of components.",
"name": "plot_models",
"signature": "def plot_models(self, panelsize=(3, 2), **kwargs)"
},
{
"docstring": "Plot information criteria versus number of components. Args: bic (bool) - include BIC scores aic (bool) - include AIC scores ax (... | 2 | null | Implement the Python class `ModelSelectionVisualization` described below.
Class description:
Methods for visualizing model selection procedure.
Method signatures and docstrings:
- def plot_models(self, panelsize=(3, 2), **kwargs): Plot model for each number of components.
- def plot_information_criteria(self, bic=Tru... | Implement the Python class `ModelSelectionVisualization` described below.
Class description:
Methods for visualizing model selection procedure.
Method signatures and docstrings:
- def plot_models(self, panelsize=(3, 2), **kwargs): Plot model for each number of components.
- def plot_information_criteria(self, bic=Tru... | 4a622c3f5fed4456c3b9240f5a96428789fde9bd | <|skeleton|>
class ModelSelectionVisualization:
"""Methods for visualizing model selection procedure."""
def plot_models(self, panelsize=(3, 2), **kwargs):
"""Plot model for each number of components."""
<|body_0|>
def plot_information_criteria(self, bic=True, aic=True, ax=None, **kwargs):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelSelectionVisualization:
"""Methods for visualizing model selection procedure."""
def plot_models(self, panelsize=(3, 2), **kwargs):
"""Plot model for each number of components."""
ncols = self.max_num_components - 2
fig, axes = plt.subplots(ncols=ncols, figsize=(panelsize[0] ... | the_stack_v2_python_sparse | flyqma/annotation/model_selection/visualization.py | sbernasek/flyqma | train | 1 |
ad2c51064f998af440aab2ec3e785baf9af266b6 | [
"super(FastText, self).__init__()\nself._embedding = torch.nn.Embedding(num_embeddings=vocabulary_size, embedding_dim=embedding_dim, padding_idx=padding_idx)\nself._tree_param = torch.nn.Linear(in_features=embedding_dim, out_features=tree_size)",
"embed = self._embedding(pieces)\nfeature = torch.sum(embed, dim=1)... | <|body_start_0|>
super(FastText, self).__init__()
self._embedding = torch.nn.Embedding(num_embeddings=vocabulary_size, embedding_dim=embedding_dim, padding_idx=padding_idx)
self._tree_param = torch.nn.Linear(in_features=embedding_dim, out_features=tree_size)
<|end_body_0|>
<|body_start_1|>
... | FastText | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastText:
def __init__(self, vocabulary_size: int, embedding_dim: int, dropout_rate: float, tree_size: int, padding_idx: int):
"""initialize FastText model Args: vocabulary_size: size of vocabulary embedding_dim: dim of out of embedding layer dropout_rate: rate of dropout which in [0, 1]... | stack_v2_sparse_classes_75kplus_train_008039 | 1,369 | no_license | [
{
"docstring": "initialize FastText model Args: vocabulary_size: size of vocabulary embedding_dim: dim of out of embedding layer dropout_rate: rate of dropout which in [0, 1] tree_size: number of nodes of huffman tree padding_idx: sign of padding that will be ignored after embedding",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_008872 | Implement the Python class `FastText` described below.
Class description:
Implement the FastText class.
Method signatures and docstrings:
- def __init__(self, vocabulary_size: int, embedding_dim: int, dropout_rate: float, tree_size: int, padding_idx: int): initialize FastText model Args: vocabulary_size: size of voca... | Implement the Python class `FastText` described below.
Class description:
Implement the FastText class.
Method signatures and docstrings:
- def __init__(self, vocabulary_size: int, embedding_dim: int, dropout_rate: float, tree_size: int, padding_idx: int): initialize FastText model Args: vocabulary_size: size of voca... | 93b1ffb561e914da3128844fccf41ab5c4d461c7 | <|skeleton|>
class FastText:
def __init__(self, vocabulary_size: int, embedding_dim: int, dropout_rate: float, tree_size: int, padding_idx: int):
"""initialize FastText model Args: vocabulary_size: size of vocabulary embedding_dim: dim of out of embedding layer dropout_rate: rate of dropout which in [0, 1]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FastText:
def __init__(self, vocabulary_size: int, embedding_dim: int, dropout_rate: float, tree_size: int, padding_idx: int):
"""initialize FastText model Args: vocabulary_size: size of vocabulary embedding_dim: dim of out of embedding layer dropout_rate: rate of dropout which in [0, 1] tree_size: nu... | the_stack_v2_python_sparse | fastText/src/utils/model.py | jchunf/NLP_Model | train | 0 | |
2b446500bba1d59b8c8ce810d52a2c75100ed38f | [
"if n == 0:\n return False\nwhile not n % 2:\n n = n / 2\nreturn n == 1",
"if n == 0:\n return False\nwhile not n % base:\n n = n / base\nreturn n == 1"
] | <|body_start_0|>
if n == 0:
return False
while not n % 2:
n = n / 2
return n == 1
<|end_body_0|>
<|body_start_1|>
if n == 0:
return False
while not n % base:
n = n / base
return n == 1
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOf(self, n, base):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return False
while not n % 2:
... | stack_v2_sparse_classes_75kplus_train_008040 | 545 | no_license | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo",
"signature": "def isPowerOfTwo(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOf",
"signature": "def isPowerOf(self, n, base)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000553 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOf(self, n, base): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOf(self, n, base): :type n: int :rtype: bool
<|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
... | 6ea4e05adf246942949f7faa15ec5175ed646760 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOf(self, n, base):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n == 0:
return False
while not n % 2:
n = n / 2
return n == 1
def isPowerOf(self, n, base):
""":type n: int :rtype: bool"""
if n == 0:
return False
... | the_stack_v2_python_sparse | algorithms/Power of Two.py | abos5/leetcode | train | 0 | |
486b2a0802a4a2516f21676d993abe94a42ea227 | [
"super(Build, self)._pre_put_hook()\nis_completed = self.status == BuildStatus.COMPLETED\nassert (self.result is not None) == is_completed\nis_canceled = self.result == BuildResult.CANCELED\nis_failure = self.result == BuildResult.FAILURE\nassert (self.cancelation_reason is not None) == is_canceled\nassert (self.fa... | <|body_start_0|>
super(Build, self)._pre_put_hook()
is_completed = self.status == BuildStatus.COMPLETED
assert (self.result is not None) == is_completed
is_canceled = self.result == BuildResult.CANCELED
is_failure = self.result == BuildResult.FAILURE
assert (self.cancelat... | Describes a build. Build key: Build keys are autogenerated, monotonically decreasing integers. That is, when sorted by key, new builds are first. Build has no parent. Build id is a 64 bits integer represented as a string to the user. - 1 highest order bit is set to 0 to keep value positive. - 43 bits are 43 lower bits ... | Build | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Build:
"""Describes a build. Build key: Build keys are autogenerated, monotonically decreasing integers. That is, when sorted by key, new builds are first. Build has no parent. Build id is a 64 bits integer represented as a string to the user. - 1 highest order bit is set to 0 to keep value posit... | stack_v2_sparse_classes_75kplus_train_008041 | 7,250 | permissive | [
{
"docstring": "Checks Build invariants before putting.",
"name": "_pre_put_hook",
"signature": "def _pre_put_hook(self)"
},
{
"docstring": "Changes lease key to a different random int.",
"name": "regenerate_lease_key",
"signature": "def regenerate_lease_key(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_034467 | Implement the Python class `Build` described below.
Class description:
Describes a build. Build key: Build keys are autogenerated, monotonically decreasing integers. That is, when sorted by key, new builds are first. Build has no parent. Build id is a 64 bits integer represented as a string to the user. - 1 highest or... | Implement the Python class `Build` described below.
Class description:
Describes a build. Build key: Build keys are autogenerated, monotonically decreasing integers. That is, when sorted by key, new builds are first. Build has no parent. Build id is a 64 bits integer represented as a string to the user. - 1 highest or... | d27ac0b230bedae4bc968515b02927cf9e17c2b7 | <|skeleton|>
class Build:
"""Describes a build. Build key: Build keys are autogenerated, monotonically decreasing integers. That is, when sorted by key, new builds are first. Build has no parent. Build id is a 64 bits integer represented as a string to the user. - 1 highest order bit is set to 0 to keep value posit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Build:
"""Describes a build. Build key: Build keys are autogenerated, monotonically decreasing integers. That is, when sorted by key, new builds are first. Build has no parent. Build id is a 64 bits integer represented as a string to the user. - 1 highest order bit is set to 0 to keep value positive. - 43 bit... | the_stack_v2_python_sparse | appengine/cr-buildbucket/model.py | TrellixVulnTeam/chromium-infra_A6Y5 | train | 0 |
d3258a9f4904080f6b5a3059bf53899bf6a1666a | [
"with open('./test-biofile/test-multiple-fasta-001.fa', 'r') as inf:\n mfr = biofile.MultipleFASTAReader(inf, biofile.UCSCExonHeader)\n for cds_alignment in mfr.CDSs():\n L = None\n for entry in cds_alignment:\n if L is None:\n L = len(entry.sequence)\n self.... | <|body_start_0|>
with open('./test-biofile/test-multiple-fasta-001.fa', 'r') as inf:
mfr = biofile.MultipleFASTAReader(inf, biofile.UCSCExonHeader)
for cds_alignment in mfr.CDSs():
L = None
for entry in cds_alignment:
if L is None:
... | test002 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test002:
def test_reading(self):
"""Reading and length"""
<|body_0|>
def test_length(self):
"""Length"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with open('./test-biofile/test-multiple-fasta-001.fa', 'r') as inf:
mfr = biofile.Multi... | stack_v2_sparse_classes_75kplus_train_008042 | 2,259 | no_license | [
{
"docstring": "Reading and length",
"name": "test_reading",
"signature": "def test_reading(self)"
},
{
"docstring": "Length",
"name": "test_length",
"signature": "def test_length(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010750 | Implement the Python class `test002` described below.
Class description:
Implement the test002 class.
Method signatures and docstrings:
- def test_reading(self): Reading and length
- def test_length(self): Length | Implement the Python class `test002` described below.
Class description:
Implement the test002 class.
Method signatures and docstrings:
- def test_reading(self): Reading and length
- def test_length(self): Length
<|skeleton|>
class test002:
def test_reading(self):
"""Reading and length"""
<|body... | d7ddd2b585a841c6d986974a24a53e4d1abe71ba | <|skeleton|>
class test002:
def test_reading(self):
"""Reading and length"""
<|body_0|>
def test_length(self):
"""Length"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test002:
def test_reading(self):
"""Reading and length"""
with open('./test-biofile/test-multiple-fasta-001.fa', 'r') as inf:
mfr = biofile.MultipleFASTAReader(inf, biofile.UCSCExonHeader)
for cds_alignment in mfr.CDSs():
L = None
for ent... | the_stack_v2_python_sparse | src/biofile_test.py | dad/base | train | 0 | |
c02c5e3b7a2546c91c6d0fa455f4163900f50a4d | [
"self.numiters = numiters\nself.damp = damp\nself.dist_thresh = dist_thresh",
"if not isinstance(maps_pointclouds, Pointclouds):\n raise TypeError('Expected maps_pointclouds to be of type gradslam.Pointclouds. Got {0}.'.format(type(maps_pointclouds)))\nif not isinstance(frames_pointclouds, Pointclouds):\n r... | <|body_start_0|>
self.numiters = numiters
self.damp = damp
self.dist_thresh = dist_thresh
<|end_body_0|>
<|body_start_1|>
if not isinstance(maps_pointclouds, Pointclouds):
raise TypeError('Expected maps_pointclouds to be of type gradslam.Pointclouds. Got {0}.'.format(type(ma... | ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver. | ICPOdometryProvider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICPOdometryProvider:
"""ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver."""
def __init__(self, numiters: int=20, damp: fl... | stack_v2_sparse_classes_75kplus_train_008043 | 3,691 | permissive | [
{
"docstring": "Initializes internal ICPOdometryProvider state. Args: numiters (int): Number of iterations to run the optimization for. Default: 20 damp (float or torch.Tensor): Damping coefficient for nonlinear least-squares. Default: 1e-8 dist_thresh (float or int or None): Distance threshold for removing `sr... | 2 | stack_v2_sparse_classes_30k_train_044370 | Implement the Python class `ICPOdometryProvider` described below.
Class description:
ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver.
Method signat... | Implement the Python class `ICPOdometryProvider` described below.
Class description:
ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver.
Method signat... | 7fb2891b8ad79dc3c89f576fdb80c9e09b5124ea | <|skeleton|>
class ICPOdometryProvider:
"""ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver."""
def __init__(self, numiters: int=20, damp: fl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ICPOdometryProvider:
"""ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver."""
def __init__(self, numiters: int=20, damp: float=1e-08, di... | the_stack_v2_python_sparse | gradslam/odometry/icp.py | saryazdi/gradslam | train | 8 |
67d551dcccde1f32407da6b9c68f8c84f7448b1f | [
"self.id = id\nself.title = title\nself.device_group = device_group\nself.device_type_id = device_type_id\nself.device_brand_id = device_brand_id\nself.create_on = create_on\nself.update_on = update_on\nself.created_by = created_by\nself.updated_by = updated_by\nself.create_on_persian_date = create_on_persian_date\... | <|body_start_0|>
self.id = id
self.title = title
self.device_group = device_group
self.device_type_id = device_type_id
self.device_brand_id = device_brand_id
self.create_on = create_on
self.update_on = update_on
self.created_by = created_by
self.up... | Implementation of the 'DeviceBrandTypes' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. device_group (int): TODO: type description here. device_type_id (int): TODO: type description here. device_brand_id (string): TODO: type desc... | DeviceBrandTypes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceBrandTypes:
"""Implementation of the 'DeviceBrandTypes' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. device_group (int): TODO: type description here. device_type_id (int): TODO: type description her... | stack_v2_sparse_classes_75kplus_train_008044 | 5,769 | permissive | [
{
"docstring": "Constructor for the DeviceBrandTypes class",
"name": "__init__",
"signature": "def __init__(self, id=None, title=None, device_group=None, create_on=None, update_on=None, created_by=None, create_on_persian_date=None, update_on_persian_date=None, device_type_brand_model_title=None, device_... | 2 | stack_v2_sparse_classes_30k_train_009958 | Implement the Python class `DeviceBrandTypes` described below.
Class description:
Implementation of the 'DeviceBrandTypes' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. device_group (int): TODO: type description here. device_ty... | Implement the Python class `DeviceBrandTypes` described below.
Class description:
Implementation of the 'DeviceBrandTypes' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. device_group (int): TODO: type description here. device_ty... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class DeviceBrandTypes:
"""Implementation of the 'DeviceBrandTypes' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. device_group (int): TODO: type description here. device_type_id (int): TODO: type description her... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceBrandTypes:
"""Implementation of the 'DeviceBrandTypes' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. device_group (int): TODO: type description here. device_type_id (int): TODO: type description here. device_bra... | the_stack_v2_python_sparse | easybimehlanding/models/device_brand_types.py | kmelodi/EasyBimehLanding_Python | train | 0 |
4bfeee61d30a69d46493f289e6b65ae86ae4df2d | [
"group_fields = [f.name for f in self.fields]\nis_kwargs = {}\nfor field in kwargs.copy():\n if field not in group_fields:\n is_kwargs[field] = kwargs.pop(field)\nif is_kwargs.get('source', None) == 'manual':\n is_kwargs.pop('source')\nanswer = super(Resource, self).create(fail_on_found=fail_on_found, ... | <|body_start_0|>
group_fields = [f.name for f in self.fields]
is_kwargs = {}
for field in kwargs.copy():
if field not in group_fields:
is_kwargs[field] = kwargs.pop(field)
if is_kwargs.get('source', None) == 'manual':
is_kwargs.pop('source')
... | Resource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
def create(self, fail_on_found=False, force_on_exists=False, **kwargs):
"""Create a group and, if necessary, modify the inventory source within the group."""
<|body_0|>
def modify(self, pk=None, create_on_missing=False, **kwargs):
"""Modify a group and, if ... | stack_v2_sparse_classes_75kplus_train_008045 | 9,703 | permissive | [
{
"docstring": "Create a group and, if necessary, modify the inventory source within the group.",
"name": "create",
"signature": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs)"
},
{
"docstring": "Modify a group and, if necessary, the inventory source within the group.",
... | 5 | stack_v2_sparse_classes_30k_train_037471 | Implement the Python class `Resource` described below.
Class description:
Implement the Resource class.
Method signatures and docstrings:
- def create(self, fail_on_found=False, force_on_exists=False, **kwargs): Create a group and, if necessary, modify the inventory source within the group.
- def modify(self, pk=None... | Implement the Python class `Resource` described below.
Class description:
Implement the Resource class.
Method signatures and docstrings:
- def create(self, fail_on_found=False, force_on_exists=False, **kwargs): Create a group and, if necessary, modify the inventory source within the group.
- def modify(self, pk=None... | e6a1f62a4f33ea94ff7dd53b9690a7b3057a7a31 | <|skeleton|>
class Resource:
def create(self, fail_on_found=False, force_on_exists=False, **kwargs):
"""Create a group and, if necessary, modify the inventory source within the group."""
<|body_0|>
def modify(self, pk=None, create_on_missing=False, **kwargs):
"""Modify a group and, if ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resource:
def create(self, fail_on_found=False, force_on_exists=False, **kwargs):
"""Create a group and, if necessary, modify the inventory source within the group."""
group_fields = [f.name for f in self.fields]
is_kwargs = {}
for field in kwargs.copy():
if field n... | the_stack_v2_python_sparse | lib/tower_cli/resources/group.py | willthames/tower-cli | train | 2 | |
4aab9a9cbcee3e6c40fff168ed9e4b53f3bb4e9e | [
"if not matrix:\n return\nm, n = (len(matrix), len(matrix[0]))\ndp = [[matrix[0][0] for j in range(n)] for i in range(m)]\nfor i in range(1, m):\n dp[i][0] = matrix[i][0] + dp[i - 1][0]\nfor j in range(1, n):\n dp[0][j] = matrix[0][j] + dp[0][j - 1]\nfor i in range(1, m):\n for j in range(1, n):\n ... | <|body_start_0|>
if not matrix:
return
m, n = (len(matrix), len(matrix[0]))
dp = [[matrix[0][0] for j in range(n)] for i in range(m)]
for i in range(1, m):
dp[i][0] = matrix[i][0] + dp[i - 1][0]
for j in range(1, n):
dp[0][j] = matrix[0][j] + d... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_008046 | 1,337 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_021553 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 7ff4d8ed1b8897385da046ba7f4afc0796d6ddc1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix:
return
m, n = (len(matrix), len(matrix[0]))
dp = [[matrix[0][0] for j in range(n)] for i in range(m)]
for i in range(1, m):
dp[i][0] = matrix[i][0] + dp[i -... | the_stack_v2_python_sparse | 304_Range_Sum_Query_2D_Immutable.py | gzk2018/leetcode | train | 0 | |
55e893dddf6a74c87159007e5157e01239c720da | [
"nn.Module.__init__(self)\nself.residual = res\nself.dropout_p = dropout_p\nself.conv_bias = conv_bias\nself.leakiness = leakiness\nself.inst_norm_affine = inst_norm_affine\nself.lrelu_inplace = lrelu_inplace\nself.dropout = nn.Dropout3d(dropout_p)\nself.in_0 = nn.InstanceNorm3d(output_channels, affine=self.inst_no... | <|body_start_0|>
nn.Module.__init__(self)
self.residual = res
self.dropout_p = dropout_p
self.conv_bias = conv_bias
self.leakiness = leakiness
self.inst_norm_affine = inst_norm_affine
self.lrelu_inplace = lrelu_inplace
self.dropout = nn.Dropout3d(dropout_p... | in_conv | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class in_conv:
def __init__(self, input_channels, output_channels, kernel_size=3, dropout_p=0.3, leakiness=0.01, conv_bias=True, inst_norm_affine=True, res=False, lrelu_inplace=True):
"""[The initial convolution to enter the network, kind of like encode] [This function will create the input co... | stack_v2_sparse_classes_75kplus_train_008047 | 20,028 | permissive | [
{
"docstring": "[The initial convolution to enter the network, kind of like encode] [This function will create the input convolution] Arguments: input_channels {[int]} -- [the input number of channels, in our case the number of modalities] output_channels {[int]} -- [the output number of channels, will determin... | 2 | null | Implement the Python class `in_conv` described below.
Class description:
Implement the in_conv class.
Method signatures and docstrings:
- def __init__(self, input_channels, output_channels, kernel_size=3, dropout_p=0.3, leakiness=0.01, conv_bias=True, inst_norm_affine=True, res=False, lrelu_inplace=True): [The initia... | Implement the Python class `in_conv` described below.
Class description:
Implement the in_conv class.
Method signatures and docstrings:
- def __init__(self, input_channels, output_channels, kernel_size=3, dropout_p=0.3, leakiness=0.01, conv_bias=True, inst_norm_affine=True, res=False, lrelu_inplace=True): [The initia... | 9acfe15cce2297ea706f6fb0406796c0e9305ccb | <|skeleton|>
class in_conv:
def __init__(self, input_channels, output_channels, kernel_size=3, dropout_p=0.3, leakiness=0.01, conv_bias=True, inst_norm_affine=True, res=False, lrelu_inplace=True):
"""[The initial convolution to enter the network, kind of like encode] [This function will create the input co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class in_conv:
def __init__(self, input_channels, output_channels, kernel_size=3, dropout_p=0.3, leakiness=0.01, conv_bias=True, inst_norm_affine=True, res=False, lrelu_inplace=True):
"""[The initial convolution to enter the network, kind of like encode] [This function will create the input convolution] Arg... | the_stack_v2_python_sparse | BrainMaGe/models/seg_modules.py | AugustKRZhu/BrainMaGe | train | 0 | |
706f326e5412cbd3eaf0f554ec83278475d265ec | [
"u = np.linalg.norm(x, 2)\nif u != 0:\n aux_b = x[0] + np.sign(x[0]) * u\n x = x[1:] / aux_b\n x = np.concatenate((np.array([1]), x))\nreturn x",
"b = -2 / np.dot(v.T, v)\nw = b * np.dot(RA.T, v)\nw = w.reshape(1, -1)\nv = v.reshape(-1, 1)\nRA = RA + v * w\nB = RA\nreturn B"
] | <|body_start_0|>
u = np.linalg.norm(x, 2)
if u != 0:
aux_b = x[0] + np.sign(x[0]) * u
x = x[1:] / aux_b
x = np.concatenate((np.array([1]), x))
return x
<|end_body_0|>
<|body_start_1|>
b = -2 / np.dot(v.T, v)
w = b * np.dot(RA.T, v)
w =... | Householder reflection and transformation. | HouseHolder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HouseHolder:
"""Householder reflection and transformation."""
def _house(self, x):
"""Perform a Househoulder reflection of vector. Parameters ---------- x : array-like of shape = number_of_training_samples The respective column of the matrix of regressors in each iteration of ERR fun... | stack_v2_sparse_classes_75kplus_train_008048 | 17,096 | permissive | [
{
"docstring": "Perform a Househoulder reflection of vector. Parameters ---------- x : array-like of shape = number_of_training_samples The respective column of the matrix of regressors in each iteration of ERR function. Returns ------- v : array-like of shape = number_of_training_samples The reflection of the ... | 2 | null | Implement the Python class `HouseHolder` described below.
Class description:
Householder reflection and transformation.
Method signatures and docstrings:
- def _house(self, x): Perform a Househoulder reflection of vector. Parameters ---------- x : array-like of shape = number_of_training_samples The respective column... | Implement the Python class `HouseHolder` described below.
Class description:
Householder reflection and transformation.
Method signatures and docstrings:
- def _house(self, x): Perform a Househoulder reflection of vector. Parameters ---------- x : array-like of shape = number_of_training_samples The respective column... | 3d241ff3c460a8e01f9bd8afbaf17f27ec3937f3 | <|skeleton|>
class HouseHolder:
"""Householder reflection and transformation."""
def _house(self, x):
"""Perform a Househoulder reflection of vector. Parameters ---------- x : array-like of shape = number_of_training_samples The respective column of the matrix of regressors in each iteration of ERR fun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HouseHolder:
"""Householder reflection and transformation."""
def _house(self, x):
"""Perform a Househoulder reflection of vector. Parameters ---------- x : array-like of shape = number_of_training_samples The respective column of the matrix of regressors in each iteration of ERR function. Return... | the_stack_v2_python_sparse | sysidentpy/base.py | JaquesZanon/sysidentpy | train | 0 |
888f8d30eafb54a3a3b15c30e988ee44c2ead35b | [
"self.inline_class = config.get('inline_class', '')\nself.latex2svg = latex2svg\nInlineProcessor.__init__(self, pattern, md)",
"escapes = m.group(1)\nif not escapes:\n escapes = m.group(4)\nif escapes:\n return (escapes.replace('\\\\\\\\', self.ESCAPED_BSLASH), m.start(0), m.end(0))\nlatex = m.group(3)\nif ... | <|body_start_0|>
self.inline_class = config.get('inline_class', '')
self.latex2svg = latex2svg
InlineProcessor.__init__(self, pattern, md)
<|end_body_0|>
<|body_start_1|>
escapes = m.group(1)
if not escapes:
escapes = m.group(4)
if escapes:
return... | MathSvg inline pattern handler. | InlineMathSvgPattern | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InlineMathSvgPattern:
"""MathSvg inline pattern handler."""
def __init__(self, pattern, config, latex2svg, md):
"""Initialize."""
<|body_0|>
def handleMatch(self, m, data):
"""Handle inline content."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008049 | 22,334 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, pattern, config, latex2svg, md)"
},
{
"docstring": "Handle inline content.",
"name": "handleMatch",
"signature": "def handleMatch(self, m, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047588 | Implement the Python class `InlineMathSvgPattern` described below.
Class description:
MathSvg inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config, latex2svg, md): Initialize.
- def handleMatch(self, m, data): Handle inline content. | Implement the Python class `InlineMathSvgPattern` described below.
Class description:
MathSvg inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config, latex2svg, md): Initialize.
- def handleMatch(self, m, data): Handle inline content.
<|skeleton|>
class InlineMathSvgPattern:
... | 45c862669d8d4e72c95f6b278819379a1c1e68d4 | <|skeleton|>
class InlineMathSvgPattern:
"""MathSvg inline pattern handler."""
def __init__(self, pattern, config, latex2svg, md):
"""Initialize."""
<|body_0|>
def handleMatch(self, m, data):
"""Handle inline content."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InlineMathSvgPattern:
"""MathSvg inline pattern handler."""
def __init__(self, pattern, config, latex2svg, md):
"""Initialize."""
self.inline_class = config.get('inline_class', '')
self.latex2svg = latex2svg
InlineProcessor.__init__(self, pattern, md)
def handleMatch(... | the_stack_v2_python_sparse | pylbm_ui/widgets/mdx_math_svg.py | gouarin/pylbm_ui | train | 0 |
82a352f85297fc8f9e9f207e6ecfe31a68596a6f | [
"self.data = data\nself.class_ind = class_ind\nself.prediction_fn = prediction_fn\nself.cat_features = cat_features\nself.verbose = verbose",
"if number_sub_samples is not None:\n num_sub_samples = number_sub_samples\nelif sub_sample_pct is None:\n num_sub_samples = int(len(self.data) * 0.1)\nelif sub_sampl... | <|body_start_0|>
self.data = data
self.class_ind = class_ind
self.prediction_fn = prediction_fn
self.cat_features = cat_features
self.verbose = verbose
<|end_body_0|>
<|body_start_1|>
if number_sub_samples is not None:
num_sub_samples = number_sub_samples
... | Feature interaction explainer. | FeatureInteraction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureInteraction:
"""Feature interaction explainer."""
def __init__(self, data: pd.DataFrame, prediction_fn: Any, cat_features: list[str], class_ind: int=None, verbose: bool=False):
"""Init. Args: data: data to compute feature interactions prediction_fn: the prediction function cat... | stack_v2_sparse_classes_75kplus_train_008050 | 6,451 | permissive | [
{
"docstring": "Init. Args: data: data to compute feature interactions prediction_fn: the prediction function cat_features: categorical features class_ind: the class index to compute the feature interaction effects on verbose: whether to enable verbosity",
"name": "__init__",
"signature": "def __init__(... | 6 | stack_v2_sparse_classes_30k_train_009748 | Implement the Python class `FeatureInteraction` described below.
Class description:
Feature interaction explainer.
Method signatures and docstrings:
- def __init__(self, data: pd.DataFrame, prediction_fn: Any, cat_features: list[str], class_ind: int=None, verbose: bool=False): Init. Args: data: data to compute featur... | Implement the Python class `FeatureInteraction` described below.
Class description:
Feature interaction explainer.
Method signatures and docstrings:
- def __init__(self, data: pd.DataFrame, prediction_fn: Any, cat_features: list[str], class_ind: int=None, verbose: bool=False): Init. Args: data: data to compute featur... | 73612ebb3e72f4f8172380bab8c7ba941e70224b | <|skeleton|>
class FeatureInteraction:
"""Feature interaction explainer."""
def __init__(self, data: pd.DataFrame, prediction_fn: Any, cat_features: list[str], class_ind: int=None, verbose: bool=False):
"""Init. Args: data: data to compute feature interactions prediction_fn: the prediction function cat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureInteraction:
"""Feature interaction explainer."""
def __init__(self, data: pd.DataFrame, prediction_fn: Any, cat_features: list[str], class_ind: int=None, verbose: bool=False):
"""Init. Args: data: data to compute feature interactions prediction_fn: the prediction function cat_features: ca... | the_stack_v2_python_sparse | explain/feature_interaction.py | dylan-slack/TalkToModel | train | 84 |
d1df998163385d3e3106ffdc620f2d659c647e17 | [
"device = self.device\nif hasattr(device.api, 'check_sensors'):\n data = await device.async_request(device.api.check_sensors)\n return self.normalize(data, self.coordinator.data)\nawait device.async_request(device.api.update)\nreturn {}",
"if data['temperature'] == -7:\n if previous_data is None or previ... | <|body_start_0|>
device = self.device
if hasattr(device.api, 'check_sensors'):
data = await device.async_request(device.api.check_sensors)
return self.normalize(data, self.coordinator.data)
await device.async_request(device.api.update)
return {}
<|end_body_0|>
<|... | Manages updates for Broadlink remotes. | BroadlinkRMUpdateManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadlinkRMUpdateManager:
"""Manages updates for Broadlink remotes."""
async def async_fetch_data(self):
"""Fetch data from the device."""
<|body_0|>
def normalize(data, previous_data):
"""Fix firmware issue. See https://github.com/home-assistant/core/issues/4210... | stack_v2_sparse_classes_75kplus_train_008051 | 6,174 | permissive | [
{
"docstring": "Fetch data from the device.",
"name": "async_fetch_data",
"signature": "async def async_fetch_data(self)"
},
{
"docstring": "Fix firmware issue. See https://github.com/home-assistant/core/issues/42100.",
"name": "normalize",
"signature": "def normalize(data, previous_data... | 2 | stack_v2_sparse_classes_30k_train_032524 | Implement the Python class `BroadlinkRMUpdateManager` described below.
Class description:
Manages updates for Broadlink remotes.
Method signatures and docstrings:
- async def async_fetch_data(self): Fetch data from the device.
- def normalize(data, previous_data): Fix firmware issue. See https://github.com/home-assis... | Implement the Python class `BroadlinkRMUpdateManager` described below.
Class description:
Manages updates for Broadlink remotes.
Method signatures and docstrings:
- async def async_fetch_data(self): Fetch data from the device.
- def normalize(data, previous_data): Fix firmware issue. See https://github.com/home-assis... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BroadlinkRMUpdateManager:
"""Manages updates for Broadlink remotes."""
async def async_fetch_data(self):
"""Fetch data from the device."""
<|body_0|>
def normalize(data, previous_data):
"""Fix firmware issue. See https://github.com/home-assistant/core/issues/4210... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BroadlinkRMUpdateManager:
"""Manages updates for Broadlink remotes."""
async def async_fetch_data(self):
"""Fetch data from the device."""
device = self.device
if hasattr(device.api, 'check_sensors'):
data = await device.async_request(device.api.check_sensors)
... | the_stack_v2_python_sparse | homeassistant/components/broadlink/updater.py | home-assistant/core | train | 35,501 |
76233e39db5a0bb5352a9188dc77ae22aa6116c4 | [
"Inferencia.__init__(self)\nself.hallazgo = hallazgo\nself.parametrosCandidatos = parametrosCandidatos",
"for parametro in self.parametrosCandidatos:\n if parametro.nombre == self.hallazgo.parametro:\n return parametro"
] | <|body_start_0|>
Inferencia.__init__(self)
self.hallazgo = hallazgo
self.parametrosCandidatos = parametrosCandidatos
<|end_body_0|>
<|body_start_1|>
for parametro in self.parametrosCandidatos:
if parametro.nombre == self.hallazgo.parametro:
return parametro
<... | Clase representativa de la inferencia encargada de seleccionar el parametro del valor recibido del exterior :author: Michael Castillo Polo y Luis Miguel López Coleto :date: 10/06/2015 | Seleccionar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seleccionar:
"""Clase representativa de la inferencia encargada de seleccionar el parametro del valor recibido del exterior :author: Michael Castillo Polo y Luis Miguel López Coleto :date: 10/06/2015"""
def __init__(self, parametrosCandidatos, hallazgo):
"""Constructor de la clase :p... | stack_v2_sparse_classes_75kplus_train_008052 | 7,195 | no_license | [
{
"docstring": "Constructor de la clase :param hallazgo: Informacion recibida del exterior :param parametrosCandidatos: Listado con todos los parametros candidatos del dominio :author: Michael Castillo Polo y Luis Miguel López Coleto :date: 10/06/2015",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_025677 | Implement the Python class `Seleccionar` described below.
Class description:
Clase representativa de la inferencia encargada de seleccionar el parametro del valor recibido del exterior :author: Michael Castillo Polo y Luis Miguel López Coleto :date: 10/06/2015
Method signatures and docstrings:
- def __init__(self, pa... | Implement the Python class `Seleccionar` described below.
Class description:
Clase representativa de la inferencia encargada de seleccionar el parametro del valor recibido del exterior :author: Michael Castillo Polo y Luis Miguel López Coleto :date: 10/06/2015
Method signatures and docstrings:
- def __init__(self, pa... | 2679bb833d4b849c109b2242af9417908c7bea21 | <|skeleton|>
class Seleccionar:
"""Clase representativa de la inferencia encargada de seleccionar el parametro del valor recibido del exterior :author: Michael Castillo Polo y Luis Miguel López Coleto :date: 10/06/2015"""
def __init__(self, parametrosCandidatos, hallazgo):
"""Constructor de la clase :p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Seleccionar:
"""Clase representativa de la inferencia encargada de seleccionar el parametro del valor recibido del exterior :author: Michael Castillo Polo y Luis Miguel López Coleto :date: 10/06/2015"""
def __init__(self, parametrosCandidatos, hallazgo):
"""Constructor de la clase :param hallazgo... | the_stack_v2_python_sparse | Third_year/ISSBC/TrabajoFinal_Monitorizacion/source/ckModMonitorizacion.py | AlexTheMagnus/UCO-Practices | train | 0 |
cb5b1ac731e7b5872d937e03a159d4c86f78f2f1 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | RoleServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_all(self, request, context):
"""Missing associated documentation comm... | stack_v2_sparse_classes_75kplus_train_008053 | 10,249 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "table",
"signature": "def table(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "get_all",
"signature": "def get_all(self, request, context)"... | 6 | stack_v2_sparse_classes_30k_train_020429 | Implement the Python class `RoleServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def table(self, request, context): Missing associated documentation comment in .proto file.
- def get_all(self, request, context): Missing associat... | Implement the Python class `RoleServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def table(self, request, context): Missing associated documentation comment in .proto file.
- def get_all(self, request, context): Missing associat... | 47d57bda959afa0b53d65e996b08e2f3b650c1a8 | <|skeleton|>
class RoleServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_all(self, request, context):
"""Missing associated documentation comm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoleServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
rai... | the_stack_v2_python_sparse | pix/authentication_client/protos/role_pb2_grpc.py | thecodeworkers/testing-clients | train | 0 |
728e47538e55568d4411b8638ca8789bb84005d4 | [
"super().__init__()\nself.channel_bn = nn.BatchNorm2d(in_channels, eps=model_config.HEAD.BATCHNORM_EPS, momentum=model_config.HEAD.BATCHNORM_MOMENTUM)\nself.clf = MLP(model_config, dims, use_bn=use_bn, use_relu=use_relu)",
"if len(batch.shape) == 2:\n batch = batch.unsqueeze(2).unsqueeze(3)\nassert len(batch.s... | <|body_start_0|>
super().__init__()
self.channel_bn = nn.BatchNorm2d(in_channels, eps=model_config.HEAD.BATCHNORM_EPS, momentum=model_config.HEAD.BATCHNORM_MOMENTUM)
self.clf = MLP(model_config, dims, use_bn=use_bn, use_relu=use_relu)
<|end_body_0|>
<|body_start_1|>
if len(batch.shape) ... | A standard Linear classification module that can be attached to several layers of the model to evaluate the representation quality of features. The layers attached are: BatchNorm2d -> Linear (1 or more) Accepts a 4D input tensor. If you want to use 2D input tensor instead, use the "mlp" head directly. | LinearEvalMLP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearEvalMLP:
"""A standard Linear classification module that can be attached to several layers of the model to evaluate the representation quality of features. The layers attached are: BatchNorm2d -> Linear (1 or more) Accepts a 4D input tensor. If you want to use 2D input tensor instead, use t... | stack_v2_sparse_classes_75kplus_train_008054 | 3,023 | permissive | [
{
"docstring": "Args: model_config (AttrDict): dictionary config.MODEL in the config file in_channels (int): number of channels the input has. This information is used to attached the BatchNorm2D layer. dims (int): dimensions of the linear layer. Example [8192, 1000] which means attaches `nn.Linear(8192, 1000, ... | 2 | null | Implement the Python class `LinearEvalMLP` described below.
Class description:
A standard Linear classification module that can be attached to several layers of the model to evaluate the representation quality of features. The layers attached are: BatchNorm2d -> Linear (1 or more) Accepts a 4D input tensor. If you wan... | Implement the Python class `LinearEvalMLP` described below.
Class description:
A standard Linear classification module that can be attached to several layers of the model to evaluate the representation quality of features. The layers attached are: BatchNorm2d -> Linear (1 or more) Accepts a 4D input tensor. If you wan... | b647c256447af7ea66655811849be1f642377db8 | <|skeleton|>
class LinearEvalMLP:
"""A standard Linear classification module that can be attached to several layers of the model to evaluate the representation quality of features. The layers attached are: BatchNorm2d -> Linear (1 or more) Accepts a 4D input tensor. If you want to use 2D input tensor instead, use t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearEvalMLP:
"""A standard Linear classification module that can be attached to several layers of the model to evaluate the representation quality of features. The layers attached are: BatchNorm2d -> Linear (1 or more) Accepts a 4D input tensor. If you want to use 2D input tensor instead, use the "mlp" head... | the_stack_v2_python_sparse | vissl/models/heads/linear_eval_mlp.py | pzharrington/vissl | train | 1 |
665f02fc1e5802f0d52be7994eb5b3dcb8a15e76 | [
"it = iter(test_inputs.split('\\n')) if test_inputs else None\n\ndef uinput():\n return next(it) if it else sys.stdin.readline().rstrip()\n[self.n, self.m] = map(int, uinput().split())\nself.nums = list(map(int, uinput().split()))\nself.genr = [0] * self.m\nfor n in self.nums:\n self.genr[n - 1] += 1\nself.su... | <|body_start_0|>
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.n, self.m] = map(int, uinput().split())
self.nums = list(map(int, uinput().split()))
self.genr = [0] * self.m
... | Gift representation | Gift | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gift:
"""Gift representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
it = iter(test_inputs.split... | stack_v2_sparse_classes_75kplus_train_008055 | 3,092 | permissive | [
{
"docstring": "Default constructor",
"name": "__init__",
"signature": "def __init__(self, test_inputs=None)"
},
{
"docstring": "Main calcualtion function of the class",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037994 | Implement the Python class `Gift` described below.
Class description:
Gift representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class | Implement the Python class `Gift` described below.
Class description:
Gift representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class
<|skeleton|>
class Gift:
"""Gift representation"""
def __init_... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class Gift:
"""Gift representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gift:
"""Gift representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.n, self.m] = map(int, uinpu... | the_stack_v2_python_sparse | codeforces/609B_gift.py | snsokolov/contests | train | 1 |
b84e71ba1220bdb44966376d31cc7b02176e1112 | [
"kwargs.setdefault('sheriffs', ['sheriff'])\nkwargs.setdefault('sendToInterestedUsers', True)\nkwargs.setdefault('status_header', 'Automatically closing tree for \"%(steps)s\" on \"%(builder)s\"')\nchromium_notifier.ChromiumNotifier.__init__(self, **kwargs)\nself.tree_status_url = tree_status_url\nself.check_revisi... | <|body_start_0|>
kwargs.setdefault('sheriffs', ['sheriff'])
kwargs.setdefault('sendToInterestedUsers', True)
kwargs.setdefault('status_header', 'Automatically closing tree for "%(steps)s" on "%(builder)s"')
chromium_notifier.ChromiumNotifier.__init__(self, **kwargs)
self.tree_sta... | This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type. | GateKeeper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GateKeeper:
"""This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type."""
def __init__(self, tree_status_url, tree_message=None, check_revisions=True, **kwargs):
"""Constructor with foll... | stack_v2_sparse_classes_75kplus_train_008056 | 8,792 | no_license | [
{
"docstring": "Constructor with following specific arguments (on top of base class'). @type tree_status_url: String. @param tree_status_url: Web end-point for tree status updates. @type tree_message: String. @param tree_message: Message posted to the tree status site when closed. @type check_revisions: Boolean... | 4 | stack_v2_sparse_classes_30k_train_029772 | Implement the Python class `GateKeeper` described below.
Class description:
This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type.
Method signatures and docstrings:
- def __init__(self, tree_status_url, tree_message=Non... | Implement the Python class `GateKeeper` described below.
Class description:
This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type.
Method signatures and docstrings:
- def __init__(self, tree_status_url, tree_message=Non... | 516718f9b7b95c4280257b2d319638d4728a90e1 | <|skeleton|>
class GateKeeper:
"""This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type."""
def __init__(self, tree_status_url, tree_message=None, check_revisions=True, **kwargs):
"""Constructor with foll... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GateKeeper:
"""This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type."""
def __init__(self, tree_status_url, tree_message=None, check_revisions=True, **kwargs):
"""Constructor with following specifi... | the_stack_v2_python_sparse | build/scripts/master/gatekeeper.py | mhcchang/chromium30 | train | 0 |
fd914caf2b0673c4dcc02d3a5fd3a23b0b81db36 | [
"self.dll = DoublyLinkedList()\nself.cache = {}\nself.size = 0\nself.capacity = capacity",
"if key not in self.cache:\n return -1\nelse:\n node = self.cache[key]\n self.dll.remove_node(node)\n self.dll.add_to_head(node)\n return node.val",
"if self.capacity <= 0:\n return\nif key in self.cache... | <|body_start_0|>
self.dll = DoublyLinkedList()
self.cache = {}
self.size = 0
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
else:
node = self.cache[key]
self.dll.remove_node(node)
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_008057 | 2,305 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 9a79fd854e9842050da07f9c9b0ce5cadc94be89 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.dll = DoublyLinkedList()
self.cache = {}
self.size = 0
self.capacity = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.cache:
return ... | the_stack_v2_python_sparse | Amazon/146.py | cloi1994/session1 | train | 0 | |
3bd69ed6e03f6bcdc0d9e51131c5bbbb42fd79be | [
"source = yaml.get('source', None)\nself.source: Optional[SourceName] = None if source is None else SourceName(source)\nself.remote: Optional[str] = yaml.get('remote', None)",
"yaml = {}\nif self.remote is not None:\n yaml['remote'] = self.remote\nif self.source is not None:\n yaml['source'] = self.source\n... | <|body_start_0|>
source = yaml.get('source', None)
self.source: Optional[SourceName] = None if source is None else SourceName(source)
self.remote: Optional[str] = yaml.get('remote', None)
<|end_body_0|>
<|body_start_1|>
yaml = {}
if self.remote is not None:
yaml['rem... | clowder yaml UpstreamDefaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name | UpstreamDefaults | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpstreamDefaults:
"""clowder yaml UpstreamDefaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name"""
def __init__(self, yaml: dict):
"""Defaults __init__ :param dict yaml: Parsed YAML python object for upstream defau... | stack_v2_sparse_classes_75kplus_train_008058 | 1,046 | permissive | [
{
"docstring": "Defaults __init__ :param dict yaml: Parsed YAML python object for upstream defaults",
"name": "__init__",
"signature": "def __init__(self, yaml: dict)"
},
{
"docstring": "Return python object representation for saving yaml :return: YAML python object",
"name": "get_yaml",
... | 2 | stack_v2_sparse_classes_30k_train_001248 | Implement the Python class `UpstreamDefaults` described below.
Class description:
clowder yaml UpstreamDefaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name
Method signatures and docstrings:
- def __init__(self, yaml: dict): Defaults __init__ :para... | Implement the Python class `UpstreamDefaults` described below.
Class description:
clowder yaml UpstreamDefaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name
Method signatures and docstrings:
- def __init__(self, yaml: dict): Defaults __init__ :para... | 1438fc8b1bb7379de66142ffcb0e20b459b59159 | <|skeleton|>
class UpstreamDefaults:
"""clowder yaml UpstreamDefaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name"""
def __init__(self, yaml: dict):
"""Defaults __init__ :param dict yaml: Parsed YAML python object for upstream defau... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpstreamDefaults:
"""clowder yaml UpstreamDefaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name"""
def __init__(self, yaml: dict):
"""Defaults __init__ :param dict yaml: Parsed YAML python object for upstream defaults"""
... | the_stack_v2_python_sparse | clowder/model/upstream_defaults.py | JrGoodle/clowder | train | 17 |
e578d6410710cc0017e06ec8d9686fec78e5bff8 | [
"questions = ShadowingFeedbackQuestions.objects.all()\ncontext = {'story_id': story_id, 'questions': questions, 'session_id': session_id}\nreturn render(request, 'shadowing/feedback.html', context)",
"change_score_by_constant = float(ShadowingConfig.objects.get(name='CHANGE_SCORE_BY').config)\nyes_ratio_for_incre... | <|body_start_0|>
questions = ShadowingFeedbackQuestions.objects.all()
context = {'story_id': story_id, 'questions': questions, 'session_id': session_id}
return render(request, 'shadowing/feedback.html', context)
<|end_body_0|>
<|body_start_1|>
change_score_by_constant = float(ShadowingC... | Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is. | ShadowingFeedBack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShadowingFeedBack:
"""Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is."""
def get(self, request, story_id, session_id):
"""Gets all the questions from the database for shadowing questions and puts it into a context to... | stack_v2_sparse_classes_75kplus_train_008059 | 7,360 | no_license | [
{
"docstring": "Gets all the questions from the database for shadowing questions and puts it into a context to show the user. :param request: :param story_id: :return:",
"name": "get",
"signature": "def get(self, request, story_id, session_id)"
},
{
"docstring": "Logs all the answers to the ques... | 2 | null | Implement the Python class `ShadowingFeedBack` described below.
Class description:
Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is.
Method signatures and docstrings:
- def get(self, request, story_id, session_id): Gets all the questions from the datab... | Implement the Python class `ShadowingFeedBack` described below.
Class description:
Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is.
Method signatures and docstrings:
- def get(self, request, story_id, session_id): Gets all the questions from the datab... | 174c8c6c9ecb2905830832419e9c332b4d8b13df | <|skeleton|>
class ShadowingFeedBack:
"""Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is."""
def get(self, request, story_id, session_id):
"""Gets all the questions from the database for shadowing questions and puts it into a context to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShadowingFeedBack:
"""Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is."""
def get(self, request, story_id, session_id):
"""Gets all the questions from the database for shadowing questions and puts it into a context to show the use... | the_stack_v2_python_sparse | CreeTutorBackEnd/shadowing/views.py | EdTeKLA/Cree-Tutor | train | 0 |
6f0b4af700568c9ccd54438fe853278c6f5f5552 | [
"if value is None:\n value = ''\nelif hasattr(value, 'to_json'):\n value = json.dumps(value.to_json())\nfinal_attrs = self.build_attrs(attrs, name=name)\nreturn \"\\n <div id='tempo-{uuid}-controls' class='tempo-controls'>\\n <input id='tempo-{uuid}-create' type='button' value='Create' />\\n... | <|body_start_0|>
if value is None:
value = ''
elif hasattr(value, 'to_json'):
value = json.dumps(value.to_json())
final_attrs = self.build_attrs(attrs, name=name)
return "\n <div id='tempo-{uuid}-controls' class='tempo-controls'>\n <input id='tem... | Django-Admin widget, that represents RecurrentEventSet. | RecurrentEventSetWidget | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurrentEventSetWidget:
"""Django-Admin widget, that represents RecurrentEventSet."""
def render(self, name, value, attrs=None):
"""Renders HTML representation and needed JavaScript."""
<|body_0|>
def value_from_datadict(self, data, files, name):
"""Retrieves da... | stack_v2_sparse_classes_75kplus_train_008060 | 2,683 | permissive | [
{
"docstring": "Renders HTML representation and needed JavaScript.",
"name": "render",
"signature": "def render(self, name, value, attrs=None)"
},
{
"docstring": "Retrieves data, from HTML representation.",
"name": "value_from_datadict",
"signature": "def value_from_datadict(self, data, ... | 2 | stack_v2_sparse_classes_30k_val_001943 | Implement the Python class `RecurrentEventSetWidget` described below.
Class description:
Django-Admin widget, that represents RecurrentEventSet.
Method signatures and docstrings:
- def render(self, name, value, attrs=None): Renders HTML representation and needed JavaScript.
- def value_from_datadict(self, data, files... | Implement the Python class `RecurrentEventSetWidget` described below.
Class description:
Django-Admin widget, that represents RecurrentEventSet.
Method signatures and docstrings:
- def render(self, name, value, attrs=None): Renders HTML representation and needed JavaScript.
- def value_from_datadict(self, data, files... | 36e600581059d27d36bd2b922acb9c403010ebc6 | <|skeleton|>
class RecurrentEventSetWidget:
"""Django-Admin widget, that represents RecurrentEventSet."""
def render(self, name, value, attrs=None):
"""Renders HTML representation and needed JavaScript."""
<|body_0|>
def value_from_datadict(self, data, files, name):
"""Retrieves da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecurrentEventSetWidget:
"""Django-Admin widget, that represents RecurrentEventSet."""
def render(self, name, value, attrs=None):
"""Renders HTML representation and needed JavaScript."""
if value is None:
value = ''
elif hasattr(value, 'to_json'):
value = j... | the_stack_v2_python_sparse | src/tempo/django/widgets.py | AndreiPashkin/python-tempo | train | 3 |
3a679414aadea906bd7ce5f436ca960facb8554d | [
"event_data = OLECFItemEventData()\nevent_data.creation_time = self._GetCreationTime(olecf_item)\nevent_data.modification_time = self._GetModificationTime(olecf_item)\nevent_data.name = olecf_item.name\nevent_data.size = olecf_item.size\nparser_mediator.ProduceEventData(event_data)\nfor sub_item in olecf_item.sub_i... | <|body_start_0|>
event_data = OLECFItemEventData()
event_data.creation_time = self._GetCreationTime(olecf_item)
event_data.modification_time = self._GetModificationTime(olecf_item)
event_data.name = olecf_item.name
event_data.size = olecf_item.size
parser_mediator.Produce... | Class to define the default OLECF file plugin. | DefaultOLECFPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultOLECFPlugin:
"""Class to define the default OLECF file plugin."""
def _ParseItem(self, parser_mediator, olecf_item):
"""Parses an OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. olecf_it... | stack_v2_sparse_classes_75kplus_train_008061 | 2,478 | permissive | [
{
"docstring": "Parses an OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. olecf_item (pyolecf.item): OLECF item. Returns: bool: True if an event was produced.",
"name": "_ParseItem",
"signature": "def _ParseItem(s... | 2 | stack_v2_sparse_classes_30k_train_048344 | Implement the Python class `DefaultOLECFPlugin` described below.
Class description:
Class to define the default OLECF file plugin.
Method signatures and docstrings:
- def _ParseItem(self, parser_mediator, olecf_item): Parses an OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers ... | Implement the Python class `DefaultOLECFPlugin` described below.
Class description:
Class to define the default OLECF file plugin.
Method signatures and docstrings:
- def _ParseItem(self, parser_mediator, olecf_item): Parses an OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class DefaultOLECFPlugin:
"""Class to define the default OLECF file plugin."""
def _ParseItem(self, parser_mediator, olecf_item):
"""Parses an OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. olecf_it... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultOLECFPlugin:
"""Class to define the default OLECF file plugin."""
def _ParseItem(self, parser_mediator, olecf_item):
"""Parses an OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. olecf_item (pyolecf.i... | the_stack_v2_python_sparse | plaso/parsers/olecf_plugins/default.py | log2timeline/plaso | train | 1,506 |
ba4d65bf64eb39a4b0030d08db90dfce526d802e | [
"if model == DjangoPlotlyDashDashapp or model == DjangoPlotlyDashStatelessapp:\n return 'default'\nreturn None",
"if model == DjangoPlotlyDashDashapp or model == DjangoPlotlyDashStatelessapp:\n return 'default'\nreturn None",
"if app_label in ['django_plotly_dash']:\n return db == 'default'\nreturn Non... | <|body_start_0|>
if model == DjangoPlotlyDashDashapp or model == DjangoPlotlyDashStatelessapp:
return 'default'
return None
<|end_body_0|>
<|body_start_1|>
if model == DjangoPlotlyDashDashapp or model == DjangoPlotlyDashStatelessapp:
return 'default'
return None
... | MyDBRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyDBRouter:
def db_for_read(self, model, **hints):
"""reading Django plotly models from default db"""
<|body_0|>
def db_for_write(self, model, **hints):
"""writing Django plotly models to default db"""
<|body_1|>
def allow_migrate(self, db, app_label, mo... | stack_v2_sparse_classes_75kplus_train_008062 | 869 | no_license | [
{
"docstring": "reading Django plotly models from default db",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "writing Django plotly models to default db",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
... | 3 | stack_v2_sparse_classes_30k_train_020031 | Implement the Python class `MyDBRouter` described below.
Class description:
Implement the MyDBRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): reading Django plotly models from default db
- def db_for_write(self, model, **hints): writing Django plotly models to default db
- def... | Implement the Python class `MyDBRouter` described below.
Class description:
Implement the MyDBRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): reading Django plotly models from default db
- def db_for_write(self, model, **hints): writing Django plotly models to default db
- def... | 28bdc2cec17a84ee2f9eeeb8eac58155b113abd4 | <|skeleton|>
class MyDBRouter:
def db_for_read(self, model, **hints):
"""reading Django plotly models from default db"""
<|body_0|>
def db_for_write(self, model, **hints):
"""writing Django plotly models to default db"""
<|body_1|>
def allow_migrate(self, db, app_label, mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyDBRouter:
def db_for_read(self, model, **hints):
"""reading Django plotly models from default db"""
if model == DjangoPlotlyDashDashapp or model == DjangoPlotlyDashStatelessapp:
return 'default'
return None
def db_for_write(self, model, **hints):
"""writing D... | the_stack_v2_python_sparse | django-web/dcmm/dbrouters.py | Matovidlo/Digital-capability-management-model | train | 1 | |
9dee3d9da49f590ad6c1710ccbe2aa49ec91ff37 | [
"super().__init__()\nself.half_channels = in_channels // 2\nself.hidden_channels = hidden_channels\nself.bins = bins\nself.tail_bound = tail_bound\nself.input_conv = nn.Conv1D(self.half_channels, hidden_channels, 1)\nself.dds_conv = DilatedDepthSeparableConv(hidden_channels, kernel_size, layers, dropout_rate=0.0)\n... | <|body_start_0|>
super().__init__()
self.half_channels = in_channels // 2
self.hidden_channels = hidden_channels
self.bins = bins
self.tail_bound = tail_bound
self.input_conv = nn.Conv1D(self.half_channels, hidden_channels, 1)
self.dds_conv = DilatedDepthSeparable... | Convolutional flow module. | ConvFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvFlow:
"""Convolutional flow module."""
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, layers: int, bins: int=10, tail_bound: float=5.0):
"""Initialize ConvFlow module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number o... | stack_v2_sparse_classes_75kplus_train_008063 | 11,302 | permissive | [
{
"docstring": "Initialize ConvFlow module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number of hidden channels. kernel_size (int): Kernel size. layers (int): Number of layers. bins (int): Number of bins. tail_bound (float): Tail bound value.",
"name": "__init__",
"signat... | 2 | null | Implement the Python class `ConvFlow` described below.
Class description:
Convolutional flow module.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, layers: int, bins: int=10, tail_bound: float=5.0): Initialize ConvFlow module. Args: in_channels (int): ... | Implement the Python class `ConvFlow` described below.
Class description:
Convolutional flow module.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, layers: int, bins: int=10, tail_bound: float=5.0): Initialize ConvFlow module. Args: in_channels (int): ... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class ConvFlow:
"""Convolutional flow module."""
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, layers: int, bins: int=10, tail_bound: float=5.0):
"""Initialize ConvFlow module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvFlow:
"""Convolutional flow module."""
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, layers: int, bins: int=10, tail_bound: float=5.0):
"""Initialize ConvFlow module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number of hidden chan... | the_stack_v2_python_sparse | paddlespeech/t2s/models/vits/flow.py | anniyanvr/DeepSpeech-1 | train | 0 |
d8cb7f29fffb26307813c6a77cb930b4c3e7891d | [
"self.Wf = np.random.normal(size=(i + h, h))\nself.Wu = np.random.normal(size=(i + h, h))\nself.Wc = np.random.normal(size=(i + h, h))\nself.Wo = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bf = np.zeros((1, h))\nself.bu = np.zeros((1, h))\nself.bc = np.zeros((1, h))\nself.bo = ... | <|body_start_0|>
self.Wf = np.random.normal(size=(i + h, h))
self.Wu = np.random.normal(size=(i + h, h))
self.Wc = np.random.normal(size=(i + h, h))
self.Wo = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bf = np.zeros((1, h))
self... | LSTM cell class | LSTMCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMCell:
"""LSTM cell class"""
def __init__(self, i, h, o):
"""Constructor"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
"""Method that performs forward propagation for one time step"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.... | stack_v2_sparse_classes_75kplus_train_008064 | 1,302 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "Method that performs forward propagation for one time step",
"name": "forward",
"signature": "def forward(self, h_prev, c_prev, x_t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043984 | Implement the Python class `LSTMCell` described below.
Class description:
LSTM cell class
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor
- def forward(self, h_prev, c_prev, x_t): Method that performs forward propagation for one time step | Implement the Python class `LSTMCell` described below.
Class description:
LSTM cell class
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor
- def forward(self, h_prev, c_prev, x_t): Method that performs forward propagation for one time step
<|skeleton|>
class LSTMCell:
"""LSTM cell cla... | 131be8fcf61aafb5a4ddc0b3853ba625560eb786 | <|skeleton|>
class LSTMCell:
"""LSTM cell class"""
def __init__(self, i, h, o):
"""Constructor"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
"""Method that performs forward propagation for one time step"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTMCell:
"""LSTM cell class"""
def __init__(self, i, h, o):
"""Constructor"""
self.Wf = np.random.normal(size=(i + h, h))
self.Wu = np.random.normal(size=(i + h, h))
self.Wc = np.random.normal(size=(i + h, h))
self.Wo = np.random.normal(size=(i + h, h))
se... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/3-lstm_cell.py | zahraaassaad/holbertonschool-machine_learning | train | 1 |
6c952ce6ef498b3213542d60cb26c72a2df90e6d | [
"self.X = X\nself.fs = fs\nself.N = 2 * (len(self.X) - 1)",
"x = np.zeros(self.N)\nfor n in range(self.N):\n x[n] = 1 / np.sqrt(self.N) * self.X[0] * np.exp(1j * 2 * cmath.pi * 0 * n / self.N)\n for k in range(1, int(self.N / 2)):\n x[n] = x[n] + 1 / np.sqrt(self.N) * self.X[k] * np.exp(1j * 2 * cmat... | <|body_start_0|>
self.X = X
self.fs = fs
self.N = 2 * (len(self.X) - 1)
<|end_body_0|>
<|body_start_1|>
x = np.zeros(self.N)
for n in range(self.N):
x[n] = 1 / np.sqrt(self.N) * self.X[0] * np.exp(1j * 2 * cmath.pi * 0 * n / self.N)
for k in range(1, int(... | idft Inverse Discrete Fourier transform. | idft_p11 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class idft_p11:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the iDFT with truncated N/2+1 coefficie... | stack_v2_sparse_classes_75kplus_train_008065 | 25,417 | no_license | [
{
"docstring": ":param X: Input DFT X :param fs: Input integer fs contains the sample frequency",
"name": "__init__",
"signature": "def __init__(self, X, fs)"
},
{
"docstring": "\\\\\\\\\\\\ METHOD: Compute the iDFT with truncated N/2+1 coefficients :return iDFT x of duration N from partial DFT ... | 2 | stack_v2_sparse_classes_30k_train_040426 | Implement the Python class `idft_p11` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, X, fs): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency
- def solve(self): \\\\\\ METHOD: Compute the iDFT with trun... | Implement the Python class `idft_p11` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, X, fs): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency
- def solve(self): \\\\\\ METHOD: Compute the iDFT with trun... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class idft_p11:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the iDFT with truncated N/2+1 coefficie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class idft_p11:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency"""
self.X = X
self.fs = fs
self.N = 2 * (len(self.X) - 1)
def solve(self):
"""\\\\\\ METHOD: ... | the_stack_v2_python_sparse | Inverse Discrete Fourier Transform/iDFT_main.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
055975ecb12f592a556b0d36954bd4635e508b77 | [
"list.__init__(self)\nself.version = [version]\nself.name = name\nself.units = [logicalUnit, physicalUnit]\nassert physicalUnit > 0 and logicalUnit > 0",
"stream.write(pack_data('HEADER', self.version))\nstream.write(pack_bgn('BGNLIB'))\nstream.write(pack_data('LIBNAME', self.name))\nstream.write(pack_data('UNITS... | <|body_start_0|>
list.__init__(self)
self.version = [version]
self.name = name
self.units = [logicalUnit, physicalUnit]
assert physicalUnit > 0 and logicalUnit > 0
<|end_body_0|>
<|body_start_1|>
stream.write(pack_data('HEADER', self.version))
stream.write(pack_b... | Library | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Library:
def __init__(self, version, name, physicalUnit, logicalUnit):
"""initialize Library object Parameters ---------- version : int GDSII file version. 5 is used for v5 name : byte string Library name physicalUnit : float Physical resolution logicalUnit : float Logical resolution"""
... | stack_v2_sparse_classes_75kplus_train_008066 | 9,146 | permissive | [
{
"docstring": "initialize Library object Parameters ---------- version : int GDSII file version. 5 is used for v5 name : byte string Library name physicalUnit : float Physical resolution logicalUnit : float Logical resolution",
"name": "__init__",
"signature": "def __init__(self, version, name, physica... | 2 | null | Implement the Python class `Library` described below.
Class description:
Implement the Library class.
Method signatures and docstrings:
- def __init__(self, version, name, physicalUnit, logicalUnit): initialize Library object Parameters ---------- version : int GDSII file version. 5 is used for v5 name : byte string ... | Implement the Python class `Library` described below.
Class description:
Implement the Library class.
Method signatures and docstrings:
- def __init__(self, version, name, physicalUnit, logicalUnit): initialize Library object Parameters ---------- version : int GDSII file version. 5 is used for v5 name : byte string ... | 86d795fd8e9c95b54dc80309a31bb1ad89e5c261 | <|skeleton|>
class Library:
def __init__(self, version, name, physicalUnit, logicalUnit):
"""initialize Library object Parameters ---------- version : int GDSII file version. 5 is used for v5 name : byte string Library name physicalUnit : float Physical resolution logicalUnit : float Logical resolution"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Library:
def __init__(self, version, name, physicalUnit, logicalUnit):
"""initialize Library object Parameters ---------- version : int GDSII file version. 5 is used for v5 name : byte string Library name physicalUnit : float Physical resolution logicalUnit : float Logical resolution"""
list._... | the_stack_v2_python_sparse | GDSIO.py | xyabc/laygo_obsolete | train | 0 | |
60d1c2446d772b0cd36a17b045f1f3f9b432cf6e | [
"super().__init__()\nself.steps = None\nself.dt = None\nself.max_t = None",
"if 'steps' in conf:\n self.steps = conf.getint('steps')\nif 'dt' in conf:\n self.dt = conf.getfloat('dt')\nif 'max_t' in conf:\n self.max_t = conf.getfloat('max_t')"
] | <|body_start_0|>
super().__init__()
self.steps = None
self.dt = None
self.max_t = None
<|end_body_0|>
<|body_start_1|>
if 'steps' in conf:
self.steps = conf.getint('steps')
if 'dt' in conf:
self.dt = conf.getfloat('dt')
if 'max_t' in conf:... | A parser for the time section of the config file. Attributes: steps (int): The instantiated number of steps for time iteration. dt (float): The value for dt (change in time) max_t (float): The time to iterate until. | TimeParser | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeParser:
"""A parser for the time section of the config file. Attributes: steps (int): The instantiated number of steps for time iteration. dt (float): The value for dt (change in time) max_t (float): The time to iterate until."""
def __init__(self):
"""Initialiser for the TimePar... | stack_v2_sparse_classes_75kplus_train_008067 | 1,165 | permissive | [
{
"docstring": "Initialiser for the TimeParser class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parse the given config section into the relevent time values. Args: conf (configparser section): The config section for the time values.",
"name": "parse",
"si... | 2 | stack_v2_sparse_classes_30k_train_014180 | Implement the Python class `TimeParser` described below.
Class description:
A parser for the time section of the config file. Attributes: steps (int): The instantiated number of steps for time iteration. dt (float): The value for dt (change in time) max_t (float): The time to iterate until.
Method signatures and docs... | Implement the Python class `TimeParser` described below.
Class description:
A parser for the time section of the config file. Attributes: steps (int): The instantiated number of steps for time iteration. dt (float): The value for dt (change in time) max_t (float): The time to iterate until.
Method signatures and docs... | cc4e7f7b9abb498893aaa05e2b25416f513905b0 | <|skeleton|>
class TimeParser:
"""A parser for the time section of the config file. Attributes: steps (int): The instantiated number of steps for time iteration. dt (float): The value for dt (change in time) max_t (float): The time to iterate until."""
def __init__(self):
"""Initialiser for the TimePar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeParser:
"""A parser for the time section of the config file. Attributes: steps (int): The instantiated number of steps for time iteration. dt (float): The value for dt (change in time) max_t (float): The time to iterate until."""
def __init__(self):
"""Initialiser for the TimeParser class."""... | the_stack_v2_python_sparse | TTiP/parsers/time_parser.py | AndrewLister-STFC/TTiP | train | 0 |
41045a21262b5d3f0ca57662f6d2149e6cbe5781 | [
"self._data_set = data_set\nself._missing_data_strategy = missing_data_strategy\nself._tz_aware = isinstance(self._data_set.index[0], datetime.datetime) and self._data_set.index[0].tzinfo is not None\nif self._missing_data_strategy == MissingDataStrategy.interpolate:\n self._data_set.interpolate()\nelif self._mi... | <|body_start_0|>
self._data_set = data_set
self._missing_data_strategy = missing_data_strategy
self._tz_aware = isinstance(self._data_set.index[0], datetime.datetime) and self._data_set.index[0].tzinfo is not None
if self._missing_data_strategy == MissingDataStrategy.interpolate:
... | GenericDataSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericDataSource:
def __init__(self, data_set: pd.Series, missing_data_strategy: MissingDataStrategy=MissingDataStrategy.fail):
"""A data source which holds a pandas series indexed by date or datetime :param data_set: a pandas dataframe indexed by date or datetime :param missing_data_st... | stack_v2_sparse_classes_75kplus_train_008068 | 6,463 | permissive | [
{
"docstring": "A data source which holds a pandas series indexed by date or datetime :param data_set: a pandas dataframe indexed by date or datetime :param missing_data_strategy: MissingDataStrategy which defines behaviour if data is missing, will only take effect if using get_data, gat_data_range has no expec... | 3 | stack_v2_sparse_classes_30k_train_039573 | Implement the Python class `GenericDataSource` described below.
Class description:
Implement the GenericDataSource class.
Method signatures and docstrings:
- def __init__(self, data_set: pd.Series, missing_data_strategy: MissingDataStrategy=MissingDataStrategy.fail): A data source which holds a pandas series indexed ... | Implement the Python class `GenericDataSource` described below.
Class description:
Implement the GenericDataSource class.
Method signatures and docstrings:
- def __init__(self, data_set: pd.Series, missing_data_strategy: MissingDataStrategy=MissingDataStrategy.fail): A data source which holds a pandas series indexed ... | 52b280b35cf8dcca55e1f124cbe65003aeee0ba6 | <|skeleton|>
class GenericDataSource:
def __init__(self, data_set: pd.Series, missing_data_strategy: MissingDataStrategy=MissingDataStrategy.fail):
"""A data source which holds a pandas series indexed by date or datetime :param data_set: a pandas dataframe indexed by date or datetime :param missing_data_st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericDataSource:
def __init__(self, data_set: pd.Series, missing_data_strategy: MissingDataStrategy=MissingDataStrategy.fail):
"""A data source which holds a pandas series indexed by date or datetime :param data_set: a pandas dataframe indexed by date or datetime :param missing_data_strategy: Missin... | the_stack_v2_python_sparse | gs_quant/backtests/data_sources.py | hausea/gs-quant | train | 0 | |
11eb1db94086cfe2581eb2aee651972c7403cc56 | [
"ret = 0\nwhile n != 1:\n ret += 1\n if n & 1 == 0:\n n >>= 1\n elif n == 3 or n >> 1 & 1 == 0:\n n -= 1\n else:\n n += 1\nreturn ret",
"if n == 1:\n return 0\nret = 1\nif n % 2 == 0:\n ret += self.integerReplacement(n / 2)\nelse:\n ret += min(self.integerReplacement(n + ... | <|body_start_0|>
ret = 0
while n != 1:
ret += 1
if n & 1 == 0:
n >>= 1
elif n == 3 or n >> 1 & 1 == 0:
n -= 1
else:
n += 1
return ret
<|end_body_0|>
<|body_start_1|>
if n == 1:
re... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerReplacement(self, n):
"""Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int"""
<|b... | stack_v2_sparse_classes_75kplus_train_008069 | 1,391 | permissive | [
{
"docstring": "Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int",
"name": "integerReplacement",
"signature": "def integerRep... | 2 | stack_v2_sparse_classes_30k_test_000545 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement(self, n): Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement(self, n): Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def integerReplacement(self, n):
"""Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def integerReplacement(self, n):
"""Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int"""
ret = 0
w... | the_stack_v2_python_sparse | 397 Integer Replacement.py | Aminaba123/LeetCode | train | 1 | |
d85678952facf6367768711db944a98d363f187d | [
"for i, num_i in enumerate(nums):\n for j, num_j in enumerate(nums[i + 1:]):\n if num_i + num_j == target:\n return [i, j + i + 1]\nreturn",
"import numpy as np\ndata = target / 2\nindex = np.where(np.array(nums) == data)[0]\nif len(index) == 2:\n return index\nnums_unique = np.unique(nums... | <|body_start_0|>
for i, num_i in enumerate(nums):
for j, num_j in enumerate(nums[i + 1:]):
if num_i + num_j == target:
return [i, j + i + 1]
return
<|end_body_0|>
<|body_start_1|>
import numpy as np
data = target / 2
index = np.whe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
"""执行用时:2892 ms, 在所有 Python 提交中击败了38.29%的用户 内存消耗:12.8 MB, 在所有 Python 提交中击败了95.72%的用户"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_008070 | 1,262 | no_license | [
{
"docstring": "执行用时:2892 ms, 在所有 Python 提交中击败了38.29%的用户 内存消耗:12.8 MB, 在所有 Python 提交中击败了95.72%的用户",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum2",
"signature": "def twoSum2(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): 执行用时:2892 ms, 在所有 Python 提交中击败了38.29%的用户 内存消耗:12.8 MB, 在所有 Python 提交中击败了95.72%的用户
- def twoSum2(self, nums, target): :type nums: List[int] :type t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): 执行用时:2892 ms, 在所有 Python 提交中击败了38.29%的用户 内存消耗:12.8 MB, 在所有 Python 提交中击败了95.72%的用户
- def twoSum2(self, nums, target): :type nums: List[int] :type t... | 89f44b711ea1788f1a25fcd07a974a22539587ef | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
"""执行用时:2892 ms, 在所有 Python 提交中击败了38.29%的用户 内存消耗:12.8 MB, 在所有 Python 提交中击败了95.72%的用户"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum(self, nums, target):
"""执行用时:2892 ms, 在所有 Python 提交中击败了38.29%的用户 内存消耗:12.8 MB, 在所有 Python 提交中击败了95.72%的用户"""
for i, num_i in enumerate(nums):
for j, num_j in enumerate(nums[i + 1:]):
if num_i + num_j == target:
return [i, j +... | the_stack_v2_python_sparse | 1两数之和.py | bettyzry/leetcode | train | 0 | |
67accf3fed9388232f1475cce18f47182102ffd0 | [
"self.mount_error = mount_error\nself.mount_point = mount_point\nself.volume_name = volume_name",
"if dictionary is None:\n return None\nmount_error = cohesity_management_sdk.models.request_error.RequestError.from_dictionary(dictionary.get('mountError')) if dictionary.get('mountError') else None\nmount_point =... | <|body_start_0|>
self.mount_error = mount_error
self.mount_point = mount_point
self.volume_name = volume_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
mount_error = cohesity_management_sdk.models.request_error.RequestError.from_dictionary(di... | Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (string): Specifies the mount point where the volume is ... | MountVolumeResultDetails | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MountVolumeResultDetails:
"""Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (str... | stack_v2_sparse_classes_75kplus_train_008071 | 2,345 | permissive | [
{
"docstring": "Constructor for the MountVolumeResultDetails class",
"name": "__init__",
"signature": "def __init__(self, mount_error=None, mount_point=None, volume_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repr... | 2 | stack_v2_sparse_classes_30k_train_038380 | Implement the Python class `MountVolumeResultDetails` described below.
Class description:
Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounti... | Implement the Python class `MountVolumeResultDetails` described below.
Class description:
Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounti... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MountVolumeResultDetails:
"""Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MountVolumeResultDetails:
"""Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (string): Specifi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mount_volume_result_details.py | cohesity/management-sdk-python | train | 24 |
38c102ae9d0072801b1aa3fce012f8b4ce78fad2 | [
"super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter)\nself.nodes = nodes\nself.procs_per_node = procs_per_node\nself.reservation = reservation\nself.launcher = launcher\nself.launcher_args = launcher_args\nself.add_header_line(f'#BSUB -cwd {self.work_dir}')\nself.add_header_line(f'... | <|body_start_0|>
super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter)
self.nodes = nodes
self.procs_per_node = procs_per_node
self.reservation = reservation
self.launcher = launcher
self.launcher_args = launcher_args
self.add_heade... | Utility class to write LSF batch scripts. | LSFBatchScript | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
... | stack_v2_sparse_classes_75kplus_train_008072 | 6,308 | permissive | [
{
"docstring": "Construct LSF batch script manager. Args: script_file (str): Script file. work_dir (str, optional): Working directory (default: current working directory). nodes (int, optional): Number of compute nodes (default: 1). procs_per_node (int, optional): Parallel processes per compute node (default: 1... | 3 | stack_v2_sparse_classes_30k_train_042454 | Implement the Python class `LSFBatchScript` described below.
Class description:
Utility class to write LSF batch scripts.
Method signatures and docstrings:
- def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=... | Implement the Python class `LSFBatchScript` described below.
Class description:
Utility class to write LSF batch scripts.
Method signatures and docstrings:
- def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=... | e8cf85eed2acbd3383892bf7cb2d88b44c194f4f | <|skeleton|>
class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
"""Co... | the_stack_v2_python_sparse | python/lbann/launcher/lsf.py | LLNL/lbann | train | 225 |
074bcfad7acfb1a8f0b6042c6a37fa0f33f44261 | [
"loan = super().transform_record(pid, record, links_factory=links_factory, **kwargs)\nfield_is_overdue(loan['metadata'])\nfield_pickup_location(loan['metadata'])\nfield_transaction_location(loan['metadata'])\nfield_transaction_user(loan['metadata'])\nreturn loan",
"hit = super().transform_search_hit(pid, record_h... | <|body_start_0|>
loan = super().transform_record(pid, record, links_factory=links_factory, **kwargs)
field_is_overdue(loan['metadata'])
field_pickup_location(loan['metadata'])
field_transaction_location(loan['metadata'])
field_transaction_user(loan['metadata'])
return loa... | Serialize loan. | LoanCSVSerializer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoanCSVSerializer:
"""Serialize loan."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
<|body_0|>
def transform_search_hit(self, pid, record_hit, links_factory=None, **kwargs):
"... | stack_v2_sparse_classes_75kplus_train_008073 | 1,328 | permissive | [
{
"docstring": "Transform record into an intermediate representation.",
"name": "transform_record",
"signature": "def transform_record(self, pid, record, links_factory=None, **kwargs)"
},
{
"docstring": "Transform search result hit into an intermediate representation.",
"name": "transform_se... | 2 | stack_v2_sparse_classes_30k_train_002707 | Implement the Python class `LoanCSVSerializer` described below.
Class description:
Serialize loan.
Method signatures and docstrings:
- def transform_record(self, pid, record, links_factory=None, **kwargs): Transform record into an intermediate representation.
- def transform_search_hit(self, pid, record_hit, links_fa... | Implement the Python class `LoanCSVSerializer` described below.
Class description:
Serialize loan.
Method signatures and docstrings:
- def transform_record(self, pid, record, links_factory=None, **kwargs): Transform record into an intermediate representation.
- def transform_search_hit(self, pid, record_hit, links_fa... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class LoanCSVSerializer:
"""Serialize loan."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
<|body_0|>
def transform_search_hit(self, pid, record_hit, links_factory=None, **kwargs):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoanCSVSerializer:
"""Serialize loan."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
loan = super().transform_record(pid, record, links_factory=links_factory, **kwargs)
field_is_overdue(loan['me... | the_stack_v2_python_sparse | invenio_app_ils/circulation/serializers/csv.py | inveniosoftware/invenio-app-ils | train | 64 |
1b76d9393c7aac46d57b770dd5b641808081c0dd | [
"pickle_file = PICKLE_FOLDER + os.path.sep + user + PICKLE_EXTENSION\nprint('Using ' + pickle_file + ' as the data')\nf = open(pickle_file, 'rb').read()\ndata = pickle.loads(f)\nreturn data",
"input_path = INPUT_FOLDER + os.path.sep + user + JPG_EXTENSION\nprint('Using ' + input_path + ' as input')\nimage = cv2.i... | <|body_start_0|>
pickle_file = PICKLE_FOLDER + os.path.sep + user + PICKLE_EXTENSION
print('Using ' + pickle_file + ' as the data')
f = open(pickle_file, 'rb').read()
data = pickle.loads(f)
return data
<|end_body_0|>
<|body_start_1|>
input_path = INPUT_FOLDER + os.path.s... | A class to recognize a user's face with the corresponding encoding. | RecognizeUserFace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecognizeUserFace:
"""A class to recognize a user's face with the corresponding encoding."""
def read_pickle(self, user):
"""Reads pickle file and returns the contents. :param user: user that's being encoded :type user: string :return: data :rtype: list"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_008074 | 3,189 | no_license | [
{
"docstring": "Reads pickle file and returns the contents. :param user: user that's being encoded :type user: string :return: data :rtype: list",
"name": "read_pickle",
"signature": "def read_pickle(self, user)"
},
{
"docstring": "Turns the input image to encoding :param user: user that's being... | 4 | stack_v2_sparse_classes_30k_train_048194 | Implement the Python class `RecognizeUserFace` described below.
Class description:
A class to recognize a user's face with the corresponding encoding.
Method signatures and docstrings:
- def read_pickle(self, user): Reads pickle file and returns the contents. :param user: user that's being encoded :type user: string ... | Implement the Python class `RecognizeUserFace` described below.
Class description:
A class to recognize a user's face with the corresponding encoding.
Method signatures and docstrings:
- def read_pickle(self, user): Reads pickle file and returns the contents. :param user: user that's being encoded :type user: string ... | d5de98b225afb6ce07dae25e4734105432533830 | <|skeleton|>
class RecognizeUserFace:
"""A class to recognize a user's face with the corresponding encoding."""
def read_pickle(self, user):
"""Reads pickle file and returns the contents. :param user: user that's being encoded :type user: string :return: data :rtype: list"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecognizeUserFace:
"""A class to recognize a user's face with the corresponding encoding."""
def read_pickle(self, user):
"""Reads pickle file and returns the contents. :param user: user that's being encoded :type user: string :return: data :rtype: list"""
pickle_file = PICKLE_FOLDER + os... | the_stack_v2_python_sparse | utility/facialrecognition/recognizeuserface.py | PIoT-CSS/agent-pi | train | 0 |
21b1bf619c13b19da9f978086cdcbf5a690e4fd5 | [
"if columns is not None:\n if isinstance(columns, list) or isinstance(columns, tuple):\n self.columns = columns\n else:\n raise TypeError('Invalid type {}'.format(type(columns)))\nelse:\n self.columns = columns\nself.random_state = random_state",
"if self.columns is None:\n self.columns ... | <|body_start_0|>
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise TypeError('Invalid type {}'.format(type(columns)))
else:
self.columns = columns
self.random_... | LDA_selector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LDA_selector:
def __init__(self, columns=None, random_state=99):
"""Init log LDA_selector."""
<|body_0|>
def fit(self, X, y):
"""Selecting LDA columns from the dataset. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_samples ... | stack_v2_sparse_classes_75kplus_train_008075 | 11,211 | permissive | [
{
"docstring": "Init log LDA_selector.",
"name": "__init__",
"signature": "def __init__(self, columns=None, random_state=99)"
},
{
"docstring": "Selecting LDA columns from the dataset. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_samples is the number... | 3 | stack_v2_sparse_classes_30k_test_002147 | Implement the Python class `LDA_selector` described below.
Class description:
Implement the LDA_selector class.
Method signatures and docstrings:
- def __init__(self, columns=None, random_state=99): Init log LDA_selector.
- def fit(self, X, y): Selecting LDA columns from the dataset. Parameters ---------- X : {Datafr... | Implement the Python class `LDA_selector` described below.
Class description:
Implement the LDA_selector class.
Method signatures and docstrings:
- def __init__(self, columns=None, random_state=99): Init log LDA_selector.
- def fit(self, X, y): Selecting LDA columns from the dataset. Parameters ---------- X : {Datafr... | e768a4cad150b35fb5bf543ab28aa23764af51d9 | <|skeleton|>
class LDA_selector:
def __init__(self, columns=None, random_state=99):
"""Init log LDA_selector."""
<|body_0|>
def fit(self, X, y):
"""Selecting LDA columns from the dataset. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_samples ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LDA_selector:
def __init__(self, columns=None, random_state=99):
"""Init log LDA_selector."""
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise TypeError('Invalid type {... | the_stack_v2_python_sparse | mlearner/preprocessing/reduce_feature.py | jaisenbe58r/MLearner | train | 9 | |
2e31d4668d6585438bb138dcb7487535291e8345 | [
"if not data:\n return None\nattribute_name = data['attribute_name']\nparameter_name = data['parameter_name']\nhelp_text = data['help']\ncompletion_id_field = data.get('completion_id_field', None)\ncompletion_request_params_list = data.get('completion_request_params', [])\ncompletion_request_params = {param.get(... | <|body_start_0|>
if not data:
return None
attribute_name = data['attribute_name']
parameter_name = data['parameter_name']
help_text = data['help']
completion_id_field = data.get('completion_id_field', None)
completion_request_params_list = data.get('completion... | Configuration used to create attributes from resource parameters. | ResourceParameterAttributeConfig | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceParameterAttributeConfig:
"""Configuration used to create attributes from resource parameters."""
def FromData(cls, data):
"""Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Retu... | stack_v2_sparse_classes_75kplus_train_008076 | 31,588 | permissive | [
{
"docstring": "Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Returns: ResourceParameterAttributeConfig",
"name": "FromData",
"signature": "def FromData(cls, data)"
},
{
"docstring": "Create a res... | 2 | stack_v2_sparse_classes_30k_val_001902 | Implement the Python class `ResourceParameterAttributeConfig` described below.
Class description:
Configuration used to create attributes from resource parameters.
Method signatures and docstrings:
- def FromData(cls, data): Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict o... | Implement the Python class `ResourceParameterAttributeConfig` described below.
Class description:
Configuration used to create attributes from resource parameters.
Method signatures and docstrings:
- def FromData(cls, data): Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict o... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class ResourceParameterAttributeConfig:
"""Configuration used to create attributes from resource parameters."""
def FromData(cls, data):
"""Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceParameterAttributeConfig:
"""Configuration used to create attributes from resource parameters."""
def FromData(cls, data):
"""Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Returns: Resource... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/calliope/concepts/concepts.py | bopopescu/socialliteapp | train | 0 |
56c242688c94729e28e0bb4c48b6d75c35941991 | [
"self.SRQ = SRQ\nself.RFC = RFC\nself.Site = Site\nself.Client = Client\nself.Requestor = Requestor\nself.Description = Description.replace(':', '').replace('>', '2').replace('!', '')\nself.__folder__ = None",
"vDir = '%s_%s [%s.%s] %s' % (self.RFC, self.SRQ, self.Site, self.Client, self.Description)\ntry:\n s... | <|body_start_0|>
self.SRQ = SRQ
self.RFC = RFC
self.Site = Site
self.Client = Client
self.Requestor = Requestor
self.Description = Description.replace(':', '').replace('>', '2').replace('!', '')
self.__folder__ = None
<|end_body_0|>
<|body_start_1|>
vDir ... | Represents all the data connected to the project: SRQ number, RFC number, Site, Client, Requestor, Description can create folder structure for a given project. | SRQProject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SRQProject:
"""Represents all the data connected to the project: SRQ number, RFC number, Site, Client, Requestor, Description can create folder structure for a given project."""
def __init__(self, SRQ=0, RFC=0, Site='NLCWIT', Client='None', Requestor='None', Description='None'):
"""I... | stack_v2_sparse_classes_75kplus_train_008077 | 2,701 | no_license | [
{
"docstring": "Initialise default values for SRQProject object",
"name": "__init__",
"signature": "def __init__(self, SRQ=0, RFC=0, Site='NLCWIT', Client='None', Requestor='None', Description='None')"
},
{
"docstring": "Creates workfolder with name created from SRQ parameters, subfolders for wo... | 2 | stack_v2_sparse_classes_30k_train_024817 | Implement the Python class `SRQProject` described below.
Class description:
Represents all the data connected to the project: SRQ number, RFC number, Site, Client, Requestor, Description can create folder structure for a given project.
Method signatures and docstrings:
- def __init__(self, SRQ=0, RFC=0, Site='NLCWIT'... | Implement the Python class `SRQProject` described below.
Class description:
Represents all the data connected to the project: SRQ number, RFC number, Site, Client, Requestor, Description can create folder structure for a given project.
Method signatures and docstrings:
- def __init__(self, SRQ=0, RFC=0, Site='NLCWIT'... | fdb5eaf3465f93c14b9f835e7fc8222605eb14ec | <|skeleton|>
class SRQProject:
"""Represents all the data connected to the project: SRQ number, RFC number, Site, Client, Requestor, Description can create folder structure for a given project."""
def __init__(self, SRQ=0, RFC=0, Site='NLCWIT', Client='None', Requestor='None', Description='None'):
"""I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SRQProject:
"""Represents all the data connected to the project: SRQ number, RFC number, Site, Client, Requestor, Description can create folder structure for a given project."""
def __init__(self, SRQ=0, RFC=0, Site='NLCWIT', Client='None', Requestor='None', Description='None'):
"""Initialise def... | the_stack_v2_python_sparse | 003/func.py | gmgray/dsvpug | train | 0 |
ab8b6ef9fd6e00180f28a32f8a9d401ecb4c9d68 | [
"super().__init__(*args, **kwargs)\nself.helper = FormHelper()\nself.helper.form_method = 'post'\nself.helper.layout = Layout('email', 'first_name', 'last_name', 'user_type', 'password1', 'password2', HTML(render_to_string('account/signup-declarations.html')), 'captcha', HTML(render_to_string('account/recaptcha-dec... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.layout = Layout('email', 'first_name', 'last_name', 'user_type', 'password1', 'password2', HTML(render_to_string('account/signup-declarations.html')), 'captcha', HTM... | Sign up for user registration. | SignupForm | [
"MIT",
"AGPL-3.0-only",
"ISC",
"LGPL-2.1-or-later",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupForm:
"""Sign up for user registration."""
def __init__(self, *args, **kwargs):
"""Add crispyform helper to form."""
<|body_0|>
def signup(self, request, user):
"""Extra logic when a user signs up. Required by django-allauth."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_008078 | 7,234 | permissive | [
{
"docstring": "Add crispyform helper to form.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Extra logic when a user signs up. Required by django-allauth.",
"name": "signup",
"signature": "def signup(self, request, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048808 | Implement the Python class `SignupForm` described below.
Class description:
Sign up for user registration.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add crispyform helper to form.
- def signup(self, request, user): Extra logic when a user signs up. Required by django-allauth. | Implement the Python class `SignupForm` described below.
Class description:
Sign up for user registration.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add crispyform helper to form.
- def signup(self, request, user): Extra logic when a user signs up. Required by django-allauth.
<|skeleto... | 5b668eb66449e2ebaeb2177237b9a55a14d69efb | <|skeleton|>
class SignupForm:
"""Sign up for user registration."""
def __init__(self, *args, **kwargs):
"""Add crispyform helper to form."""
<|body_0|>
def signup(self, request, user):
"""Extra logic when a user signs up. Required by django-allauth."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignupForm:
"""Sign up for user registration."""
def __init__(self, *args, **kwargs):
"""Add crispyform helper to form."""
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.layout = Layout('email', 'first_name... | the_stack_v2_python_sparse | codewof/users/forms.py | uccser/codewof | train | 7 |
8c543d33c6500bdd96f6404b8fd23c2a8caf78dc | [
"self.lowest_new_price = lowest_new_price\nself.lowest_used_price = lowest_used_price\nself.lowest_collectible_price = lowest_collectible_price\nself.lowest_refurbished_price = lowest_refurbished_price\nself.total_new = total_new\nself.total_used = total_used\nself.total_collectible = total_collectible\nself.total_... | <|body_start_0|>
self.lowest_new_price = lowest_new_price
self.lowest_used_price = lowest_used_price
self.lowest_collectible_price = lowest_collectible_price
self.lowest_refurbished_price = lowest_refurbished_price
self.total_new = total_new
self.total_used = total_used
... | Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbished_price (Price): TODO: type descriptio... | OfferSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfferSummary:
"""Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbis... | stack_v2_sparse_classes_75kplus_train_008079 | 4,010 | permissive | [
{
"docstring": "Constructor for the OfferSummary class",
"name": "__init__",
"signature": "def __init__(self, lowest_new_price=None, lowest_used_price=None, lowest_collectible_price=None, lowest_refurbished_price=None, total_new=None, total_used=None, total_collectible=None, total_refurbished=None)"
}... | 2 | stack_v2_sparse_classes_30k_train_006677 | Implement the Python class `OfferSummary` described below.
Class description:
Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO:... | Implement the Python class `OfferSummary` described below.
Class description:
Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO:... | 26ea1019115a1de3b1b37a4b830525e164ac55ce | <|skeleton|>
class OfferSummary:
"""Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfferSummary:
"""Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbished_price (Pr... | the_stack_v2_python_sparse | awsecommerceservice/models/offer_summary.py | nidaizamir/Test-PY | train | 0 |
536301cfe8a733afa52a49a5b7773f1e2620fb69 | [
"super(ImageEncoding, self).__init__()\nself.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1)\nself.batchNorm1 = nn.BatchNorm2d(32)\nself.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1)\nself.batchNorm2 = nn.BatchNorm2d(64)\nself.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=2)\nself.batchNorm3 = nn.BatchNor... | <|body_start_0|>
super(ImageEncoding, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1)
self.batchNorm1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1)
self.batchNorm2 = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(64, 128, ... | Image encoding using 4 convolutional layers with batch normalization, it was designed specifically for sort of clevr https://arxiv.org/abs/1706.01427. | ImageEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageEncoding:
"""Image encoding using 4 convolutional layers with batch normalization, it was designed specifically for sort of clevr https://arxiv.org/abs/1706.01427."""
def __init__(self):
"""Constructor of ImageEncoding class."""
<|body_0|>
def forward(self, img):
... | stack_v2_sparse_classes_75kplus_train_008080 | 2,474 | permissive | [
{
"docstring": "Constructor of ImageEncoding class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Apply 4 convolutional layers over the image. :param img: input image [batch_size, num_channels, height, width] :return: x: feature map with flattening the width and heig... | 2 | null | Implement the Python class `ImageEncoding` described below.
Class description:
Image encoding using 4 convolutional layers with batch normalization, it was designed specifically for sort of clevr https://arxiv.org/abs/1706.01427.
Method signatures and docstrings:
- def __init__(self): Constructor of ImageEncoding cla... | Implement the Python class `ImageEncoding` described below.
Class description:
Image encoding using 4 convolutional layers with batch normalization, it was designed specifically for sort of clevr https://arxiv.org/abs/1706.01427.
Method signatures and docstrings:
- def __init__(self): Constructor of ImageEncoding cla... | c655c88cc6aec4d0724c19ea95209f1c2dd6770d | <|skeleton|>
class ImageEncoding:
"""Image encoding using 4 convolutional layers with batch normalization, it was designed specifically for sort of clevr https://arxiv.org/abs/1706.01427."""
def __init__(self):
"""Constructor of ImageEncoding class."""
<|body_0|>
def forward(self, img):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageEncoding:
"""Image encoding using 4 convolutional layers with batch normalization, it was designed specifically for sort of clevr https://arxiv.org/abs/1706.01427."""
def __init__(self):
"""Constructor of ImageEncoding class."""
super(ImageEncoding, self).__init__()
self.conv... | the_stack_v2_python_sparse | models/multi_hops_attention/image_encoding.py | aasseman/mi-prometheus | train | 0 |
5827fed1667d31683d8f8ebadb796e2b2c64520f | [
"self.is_mixup = args.mixup\nself.mixup_ratio = args.mixup_ratio\nself.mixup_alpha = args.mixup_alpha\nself.num_classes = args.num_classes",
"if not self.is_mixup or np.random.rand() > self.mixup_ratio:\n return (inputs, targets, None, 1.0)\nbatch_size, num_channel, image_height, image_width = inputs.shape\nif... | <|body_start_0|>
self.is_mixup = args.mixup
self.mixup_ratio = args.mixup_ratio
self.mixup_alpha = args.mixup_alpha
self.num_classes = args.num_classes
<|end_body_0|>
<|body_start_1|>
if not self.is_mixup or np.random.rand() > self.mixup_ratio:
return (inputs, target... | MixUp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixUp:
def __init__(self, args: argparse.Namespace):
"""数据增强 mixup,ref: https://github.com/facebookresearch/mixup-cifar10 :param args: 超参"""
<|body_0|>
def __call__(self, inputs: torch.FloatTensor, targets: typing.Union[torch.IntTensor, torch.FloatTensor]) -> (torch.FloatTen... | stack_v2_sparse_classes_75kplus_train_008081 | 2,039 | no_license | [
{
"docstring": "数据增强 mixup,ref: https://github.com/facebookresearch/mixup-cifar10 :param args: 超参",
"name": "__init__",
"signature": "def __init__(self, args: argparse.Namespace)"
},
{
"docstring": "对图像和标签进行线性插值混合 :param inputs: 图像pytorch数组,NCHW :param targets: 标签pytorch数组,(N,) 或 (N, num_classes... | 2 | stack_v2_sparse_classes_30k_train_031759 | Implement the Python class `MixUp` described below.
Class description:
Implement the MixUp class.
Method signatures and docstrings:
- def __init__(self, args: argparse.Namespace): 数据增强 mixup,ref: https://github.com/facebookresearch/mixup-cifar10 :param args: 超参
- def __call__(self, inputs: torch.FloatTensor, targets:... | Implement the Python class `MixUp` described below.
Class description:
Implement the MixUp class.
Method signatures and docstrings:
- def __init__(self, args: argparse.Namespace): 数据增强 mixup,ref: https://github.com/facebookresearch/mixup-cifar10 :param args: 超参
- def __call__(self, inputs: torch.FloatTensor, targets:... | 13030bd157a499b80d1860b8b654a66224eaf475 | <|skeleton|>
class MixUp:
def __init__(self, args: argparse.Namespace):
"""数据增强 mixup,ref: https://github.com/facebookresearch/mixup-cifar10 :param args: 超参"""
<|body_0|>
def __call__(self, inputs: torch.FloatTensor, targets: typing.Union[torch.IntTensor, torch.FloatTensor]) -> (torch.FloatTen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MixUp:
def __init__(self, args: argparse.Namespace):
"""数据增强 mixup,ref: https://github.com/facebookresearch/mixup-cifar10 :param args: 超参"""
self.is_mixup = args.mixup
self.mixup_ratio = args.mixup_ratio
self.mixup_alpha = args.mixup_alpha
self.num_classes = args.num_cl... | the_stack_v2_python_sparse | dataloader/enhancement/mixup.py | zheng-yuwei/PyTorch-Image-Classification | train | 63 | |
f9ed8f83a0d82562a1d844fd3a66d5071a6e7bdb | [
"table = Annotation.__table__\nwhere_clauses = [table.c.collection_key == collection.key, table.c.deleted is not True]\nquery = table.select().where(and_(*where_clauses))\nexec_opts = dict(stream_results=True)\nres = db.session.connection(execution_options=exec_opts).execute(query)\nwhile True:\n chunk = res.fet... | <|body_start_0|>
table = Annotation.__table__
where_clauses = [table.c.collection_key == collection.key, table.c.deleted is not True]
query = table.select().where(and_(*where_clauses))
exec_opts = dict(stream_results=True)
res = db.session.connection(execution_options=exec_opts).... | Exporter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exporter:
def _stream_annotation_data(self, collection):
"""Stream the contents of an AnnotationCollection from the database."""
<|body_0|>
def generate_data(self, collection_id):
"""Return all Annotations as JSON-LD."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_008082 | 1,631 | permissive | [
{
"docstring": "Stream the contents of an AnnotationCollection from the database.",
"name": "_stream_annotation_data",
"signature": "def _stream_annotation_data(self, collection)"
},
{
"docstring": "Return all Annotations as JSON-LD.",
"name": "generate_data",
"signature": "def generate_... | 2 | stack_v2_sparse_classes_30k_train_035519 | Implement the Python class `Exporter` described below.
Class description:
Implement the Exporter class.
Method signatures and docstrings:
- def _stream_annotation_data(self, collection): Stream the contents of an AnnotationCollection from the database.
- def generate_data(self, collection_id): Return all Annotations ... | Implement the Python class `Exporter` described below.
Class description:
Implement the Exporter class.
Method signatures and docstrings:
- def _stream_annotation_data(self, collection): Stream the contents of an AnnotationCollection from the database.
- def generate_data(self, collection_id): Return all Annotations ... | bc504498ef330fab46f2334f96631457d520ec90 | <|skeleton|>
class Exporter:
def _stream_annotation_data(self, collection):
"""Stream the contents of an AnnotationCollection from the database."""
<|body_0|>
def generate_data(self, collection_id):
"""Return all Annotations as JSON-LD."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Exporter:
def _stream_annotation_data(self, collection):
"""Stream the contents of an AnnotationCollection from the database."""
table = Annotation.__table__
where_clauses = [table.c.collection_key == collection.key, table.c.deleted is not True]
query = table.select().where(and... | the_stack_v2_python_sparse | explicates/exporter.py | alexandermendes/explicates | train | 8 | |
580e1a0dd65a2bbce049763df2bf6e131fc666c7 | [
"self.db = db\nself.subscribe = sub\nself.strategy_pool = strategies\nself.col = MongoClient('localhost', 27017)[self.db][self.subscribe]\nself.consumer = KafkaConsumer(self.subscribe, bootstrap_servers='kafka-28:9092', value_deserializer=lambda v: json.loads(v.decode('utf-8')))\nself.df = pd.DataFrame(list(self.co... | <|body_start_0|>
self.db = db
self.subscribe = sub
self.strategy_pool = strategies
self.col = MongoClient('localhost', 27017)[self.db][self.subscribe]
self.consumer = KafkaConsumer(self.subscribe, bootstrap_servers='kafka-28:9092', value_deserializer=lambda v: json.loads(v.decode... | 主程序,用来分主题运行策略池,方便管理维护 | Main | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Main:
"""主程序,用来分主题运行策略池,方便管理维护"""
def __init__(self, sub, db='websocket1mindata', strategies=(Bollingerband, Cci, Kdj, Ma, Macd, Rbreakday, Rbreakweek, Rsi, Turtle4hour, Turtle2hour)):
""":param sub: 订阅主题 :param db: MongoDB 数据库名称 :param strategies: 策略(多个策略)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_008083 | 2,986 | no_license | [
{
"docstring": ":param sub: 订阅主题 :param db: MongoDB 数据库名称 :param strategies: 策略(多个策略)",
"name": "__init__",
"signature": "def __init__(self, sub, db='websocket1mindata', strategies=(Bollingerband, Cci, Kdj, Ma, Macd, Rbreakday, Rbreakweek, Rsi, Turtle4hour, Turtle2hour))"
},
{
"docstring": "运行策略... | 2 | null | Implement the Python class `Main` described below.
Class description:
主程序,用来分主题运行策略池,方便管理维护
Method signatures and docstrings:
- def __init__(self, sub, db='websocket1mindata', strategies=(Bollingerband, Cci, Kdj, Ma, Macd, Rbreakday, Rbreakweek, Rsi, Turtle4hour, Turtle2hour)): :param sub: 订阅主题 :param db: MongoDB 数据库... | Implement the Python class `Main` described below.
Class description:
主程序,用来分主题运行策略池,方便管理维护
Method signatures and docstrings:
- def __init__(self, sub, db='websocket1mindata', strategies=(Bollingerband, Cci, Kdj, Ma, Macd, Rbreakday, Rbreakweek, Rsi, Turtle4hour, Turtle2hour)): :param sub: 订阅主题 :param db: MongoDB 数据库... | ab0e4d114bcaf445a596d53889bbe79df323b27f | <|skeleton|>
class Main:
"""主程序,用来分主题运行策略池,方便管理维护"""
def __init__(self, sub, db='websocket1mindata', strategies=(Bollingerband, Cci, Kdj, Ma, Macd, Rbreakday, Rbreakweek, Rsi, Turtle4hour, Turtle2hour)):
""":param sub: 订阅主题 :param db: MongoDB 数据库名称 :param strategies: 策略(多个策略)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Main:
"""主程序,用来分主题运行策略池,方便管理维护"""
def __init__(self, sub, db='websocket1mindata', strategies=(Bollingerband, Cci, Kdj, Ma, Macd, Rbreakday, Rbreakweek, Rsi, Turtle4hour, Turtle2hour)):
""":param sub: 订阅主题 :param db: MongoDB 数据库名称 :param strategies: 策略(多个策略)"""
self.db = db
self.su... | the_stack_v2_python_sparse | main/mainscript.py | sylinuxhy/SignalPool | train | 0 |
90758b2bd5a82925d1ec25cd203e5e900b461ad6 | [
"post_body = {'servicechain_spec': {'name': name}}\nif kwargs.get('description'):\n post_body['servicechain_spec']['description'] = kwargs.get('description')\npost_body = json.dumps(post_body)\nresp, body = self.post(self.get_uri(self.resource), post_body)\nbody = json.loads(body)\nself.expected_success(http_cli... | <|body_start_0|>
post_body = {'servicechain_spec': {'name': name}}
if kwargs.get('description'):
post_body['servicechain_spec']['description'] = kwargs.get('description')
post_body = json.dumps(post_body)
resp, body = self.post(self.get_uri(self.resource), post_body)
... | API V2 Tempest REST client for GBP Servicechain Spec API | ServicechainSpecClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicechainSpecClient:
"""API V2 Tempest REST client for GBP Servicechain Spec API"""
def create_servicechain_spec(self, name, **kwargs):
"""Create a Servicechain Spec"""
<|body_0|>
def list_servicechain_specs(self):
"""List Servicechain Specs"""
<|body_... | stack_v2_sparse_classes_75kplus_train_008084 | 2,134 | no_license | [
{
"docstring": "Create a Servicechain Spec",
"name": "create_servicechain_spec",
"signature": "def create_servicechain_spec(self, name, **kwargs)"
},
{
"docstring": "List Servicechain Specs",
"name": "list_servicechain_specs",
"signature": "def list_servicechain_specs(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_033480 | Implement the Python class `ServicechainSpecClient` described below.
Class description:
API V2 Tempest REST client for GBP Servicechain Spec API
Method signatures and docstrings:
- def create_servicechain_spec(self, name, **kwargs): Create a Servicechain Spec
- def list_servicechain_specs(self): List Servicechain Spe... | Implement the Python class `ServicechainSpecClient` described below.
Class description:
API V2 Tempest REST client for GBP Servicechain Spec API
Method signatures and docstrings:
- def create_servicechain_spec(self, name, **kwargs): Create a Servicechain Spec
- def list_servicechain_specs(self): List Servicechain Spe... | 8b7640e82aa9b12ebee49177da0f7fe7ed2f699f | <|skeleton|>
class ServicechainSpecClient:
"""API V2 Tempest REST client for GBP Servicechain Spec API"""
def create_servicechain_spec(self, name, **kwargs):
"""Create a Servicechain Spec"""
<|body_0|>
def list_servicechain_specs(self):
"""List Servicechain Specs"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServicechainSpecClient:
"""API V2 Tempest REST client for GBP Servicechain Spec API"""
def create_servicechain_spec(self, name, **kwargs):
"""Create a Servicechain Spec"""
post_body = {'servicechain_spec': {'name': name}}
if kwargs.get('description'):
post_body['servic... | the_stack_v2_python_sparse | gbp_tempest_plugin/services/gbp/v2/json/servicechain_spec_client.py | noironetworks/gbp-tempest-plugin | train | 0 |
ffd98d0ea0d4e0fd5ce5ab24acb9f7645ad087b2 | [
"super().__init__(service_name, u_context)\nif u_context:\n self.user_context = u_context\n self.username = u_context.user\n if u_context.context == u_context.ChoicesOfView.COMMON:\n self.use_user = None\n else:\n self.use_user = u_context.user",
"context = self.user_context\nfw = contex... | <|body_start_0|>
super().__init__(service_name, u_context)
if u_context:
self.user_context = u_context
self.username = u_context.user
if u_context.context == u_context.ChoicesOfView.COMMON:
self.use_user = None
else:
self.us... | Data reading class for Source objects with associated data. - Returns a Result object which includes the tems and eventuel error object. | SourceReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceReader:
"""Data reading class for Source objects with associated data. - Returns a Result object which includes the tems and eventuel error object."""
def __init__(self, service_name: str, u_context=None):
"""Create a reader object with db driver and user context."""
<|... | stack_v2_sparse_classes_75kplus_train_008085 | 8,517 | no_license | [
{
"docstring": "Create a reader object with db driver and user context.",
"name": "__init__",
"signature": "def __init__(self, service_name: str, u_context=None)"
},
{
"docstring": "Get junk of Source objects for Sources list.",
"name": "get_source_list",
"signature": "def get_source_lis... | 3 | stack_v2_sparse_classes_30k_test_001906 | Implement the Python class `SourceReader` described below.
Class description:
Data reading class for Source objects with associated data. - Returns a Result object which includes the tems and eventuel error object.
Method signatures and docstrings:
- def __init__(self, service_name: str, u_context=None): Create a rea... | Implement the Python class `SourceReader` described below.
Class description:
Data reading class for Source objects with associated data. - Returns a Result object which includes the tems and eventuel error object.
Method signatures and docstrings:
- def __init__(self, service_name: str, u_context=None): Create a rea... | 0f8d6ba035e3cca8dc756531b7cc51029a549a4f | <|skeleton|>
class SourceReader:
"""Data reading class for Source objects with associated data. - Returns a Result object which includes the tems and eventuel error object."""
def __init__(self, service_name: str, u_context=None):
"""Create a reader object with db driver and user context."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SourceReader:
"""Data reading class for Source objects with associated data. - Returns a Result object which includes the tems and eventuel error object."""
def __init__(self, service_name: str, u_context=None):
"""Create a reader object with db driver and user context."""
super().__init_... | the_stack_v2_python_sparse | bl/source.py | kkujansuu/stk | train | 0 |
ce22feb12eb00bab9a46204ad60c56592f9080f7 | [
"self.flag = False\nself.ultrasonic_sensor = ev3.UltrasonicSensor('in2')\nself.robot = robot",
"distance = self.ultrasonic_sensor.distance_centimeters\nif distance > 15:\n self.robot.runforever(0.1)\nelif distance > 10:\n self.robot.stop()\nelse:\n self.robot.backwardforever(0.1)"
] | <|body_start_0|>
self.flag = False
self.ultrasonic_sensor = ev3.UltrasonicSensor('in2')
self.robot = robot
<|end_body_0|>
<|body_start_1|>
distance = self.ultrasonic_sensor.distance_centimeters
if distance > 15:
self.robot.runforever(0.1)
elif distance > 10:
... | Wary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wary:
def __init__(self, robot=None):
"""Set up motors/robot and sensors here"""
<|body_0|>
def run(self):
"""One cycle of feedback loop: read sensors, choose movement, set movement."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.flag = False
... | stack_v2_sparse_classes_75kplus_train_008086 | 4,473 | no_license | [
{
"docstring": "Set up motors/robot and sensors here",
"name": "__init__",
"signature": "def __init__(self, robot=None)"
},
{
"docstring": "One cycle of feedback loop: read sensors, choose movement, set movement.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026412 | Implement the Python class `Wary` described below.
Class description:
Implement the Wary class.
Method signatures and docstrings:
- def __init__(self, robot=None): Set up motors/robot and sensors here
- def run(self): One cycle of feedback loop: read sensors, choose movement, set movement. | Implement the Python class `Wary` described below.
Class description:
Implement the Wary class.
Method signatures and docstrings:
- def __init__(self, robot=None): Set up motors/robot and sensors here
- def run(self): One cycle of feedback loop: read sensors, choose movement, set movement.
<|skeleton|>
class Wary:
... | 01732d90d5099a3ac3b723ff05376d27208d534a | <|skeleton|>
class Wary:
def __init__(self, robot=None):
"""Set up motors/robot and sensors here"""
<|body_0|>
def run(self):
"""One cycle of feedback loop: read sensors, choose movement, set movement."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Wary:
def __init__(self, robot=None):
"""Set up motors/robot and sensors here"""
self.flag = False
self.ultrasonic_sensor = ev3.UltrasonicSensor('in2')
self.robot = robot
def run(self):
"""One cycle of feedback loop: read sensors, choose movement, set movement."""
... | the_stack_v2_python_sparse | Activity3/reactiveCode.py | tianyoul/AI-Robotics | train | 0 | |
cf2c02595365efd00b1628a9c11ab5e178f75920 | [
"if getattr(spec, 'project_id', None) and getattr(spec, 'labels', None):\n raise exceptions.ApiValueError(\"Can't set labels to a task inside a project. Tasks inside a project use project's labels.\", ['labels'])\ntask = self.create(spec=spec)\nself._client.logger.info('Created task ID: %s NAME: %s', task.id, ta... | <|body_start_0|>
if getattr(spec, 'project_id', None) and getattr(spec, 'labels', None):
raise exceptions.ApiValueError("Can't set labels to a task inside a project. Tasks inside a project use project's labels.", ['labels'])
task = self.create(spec=spec)
self._client.logger.info('Cre... | TasksRepo | [
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TasksRepo:
def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]]=None, annotation_path: str='', annotation_format: str='CVAT XML 1.1', status_check_period: int=None, datase... | stack_v2_sparse_classes_75kplus_train_008087 | 14,269 | permissive | [
{
"docstring": "Create a new task with the given name and labels JSON and add the files to it. Returns: id of the created task",
"name": "create_from_data",
"signature": "def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.... | 3 | stack_v2_sparse_classes_30k_train_049295 | Implement the Python class `TasksRepo` described below.
Class description:
Implement the TasksRepo class.
Method signatures and docstrings:
- def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]... | Implement the Python class `TasksRepo` described below.
Class description:
Implement the TasksRepo class.
Method signatures and docstrings:
- def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]... | 899c9fd75146744def061efd7ab1b1c6c9f6942f | <|skeleton|>
class TasksRepo:
def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]]=None, annotation_path: str='', annotation_format: str='CVAT XML 1.1', status_check_period: int=None, datase... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TasksRepo:
def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]]=None, annotation_path: str='', annotation_format: str='CVAT XML 1.1', status_check_period: int=None, dataset_repository_u... | the_stack_v2_python_sparse | cvat-sdk/cvat_sdk/core/proxies/tasks.py | opencv/cvat | train | 6,558 | |
146d462a72095d86e1ef793dfafdd92e3e074e6e | [
"Pool = self.pool\nwebsite_obj = Pool.get('magento.instance.website')\nwebsite = website_obj.browse(cursor, user, context['active_id'], context)\nself.import_category_tree(cursor, user, website, context)\nproduct_ids = self.import_products(cursor, user, website, context)\nreturn self.open_products(cursor, user, ids... | <|body_start_0|>
Pool = self.pool
website_obj = Pool.get('magento.instance.website')
website = website_obj.browse(cursor, user, context['active_id'], context)
self.import_category_tree(cursor, user, website, context)
product_ids = self.import_products(cursor, user, website, conte... | Import catalog | ImportCatalog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportCatalog:
"""Import catalog"""
def import_catalog(self, cursor, user, ids, context):
"""Import the product categories and products :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records for this model :param context: Application context... | stack_v2_sparse_classes_75kplus_train_008088 | 4,443 | no_license | [
{
"docstring": "Import the product categories and products :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records for this model :param context: Application context",
"name": "import_catalog",
"signature": "def import_catalog(self, cursor, user, ids, context)"
... | 4 | stack_v2_sparse_classes_30k_train_027937 | Implement the Python class `ImportCatalog` described below.
Class description:
Import catalog
Method signatures and docstrings:
- def import_catalog(self, cursor, user, ids, context): Import the product categories and products :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of r... | Implement the Python class `ImportCatalog` described below.
Class description:
Import catalog
Method signatures and docstrings:
- def import_catalog(self, cursor, user, ids, context): Import the product categories and products :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of r... | f661c776973868c0414007791ae6a0b069b1038f | <|skeleton|>
class ImportCatalog:
"""Import catalog"""
def import_catalog(self, cursor, user, ids, context):
"""Import the product categories and products :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records for this model :param context: Application context... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImportCatalog:
"""Import catalog"""
def import_catalog(self, cursor, user, ids, context):
"""Import the product categories and products :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records for this model :param context: Application context"""
P... | the_stack_v2_python_sparse | wizard/import_catalog.py | openlabs/magento_integration | train | 23 |
83f192731d62023c66f138cf41ea68fc83143f70 | [
"dynamic = kwargs.pop('dynamic', True)\nsuper(Conv2dODEFunc, self).__init__(**kwargs, dynamic=dynamic)\nself.num_filters = num_filters\nself.augment_dim = augment_dim\nself.time_dependent = time_dependent\nself.nfe = tf.Variable(0.0, trainable=False)\nself.groups = groups if groups is not None else self.num_filters... | <|body_start_0|>
dynamic = kwargs.pop('dynamic', True)
super(Conv2dODEFunc, self).__init__(**kwargs, dynamic=dynamic)
self.num_filters = num_filters
self.augment_dim = augment_dim
self.time_dependent = time_dependent
self.nfe = tf.Variable(0.0, trainable=False)
se... | Conv2dODEFunc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2dODEFunc:
def __init__(self, num_filters, augment_dim=0, time_dependent=False, activation=None, groups=None, **kwargs):
"""Convolutional block modeling the derivative of ODE system. # Arguments: num_filters : int Number of convolutional filters. augment_dim: int Number of augmentati... | stack_v2_sparse_classes_75kplus_train_008089 | 29,308 | no_license | [
{
"docstring": "Convolutional block modeling the derivative of ODE system. # Arguments: num_filters : int Number of convolutional filters. augment_dim: int Number of augmentation channels to add. If 0 does not augment ODE. time_dependent : bool If True adds time as input, making ODE time dependent. activation :... | 2 | null | Implement the Python class `Conv2dODEFunc` described below.
Class description:
Implement the Conv2dODEFunc class.
Method signatures and docstrings:
- def __init__(self, num_filters, augment_dim=0, time_dependent=False, activation=None, groups=None, **kwargs): Convolutional block modeling the derivative of ODE system.... | Implement the Python class `Conv2dODEFunc` described below.
Class description:
Implement the Conv2dODEFunc class.
Method signatures and docstrings:
- def __init__(self, num_filters, augment_dim=0, time_dependent=False, activation=None, groups=None, **kwargs): Convolutional block modeling the derivative of ODE system.... | 0ed551ac82885a692fcd6e6faa29682583e77937 | <|skeleton|>
class Conv2dODEFunc:
def __init__(self, num_filters, augment_dim=0, time_dependent=False, activation=None, groups=None, **kwargs):
"""Convolutional block modeling the derivative of ODE system. # Arguments: num_filters : int Number of convolutional filters. augment_dim: int Number of augmentati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Conv2dODEFunc:
def __init__(self, num_filters, augment_dim=0, time_dependent=False, activation=None, groups=None, **kwargs):
"""Convolutional block modeling the derivative of ODE system. # Arguments: num_filters : int Number of convolutional filters. augment_dim: int Number of augmentation channels to... | the_stack_v2_python_sparse | experiments/mnist/mnist_neuralode.py | pkmtum/NeuralODE_PhysicalProblems_Tensorflow | train | 1 | |
921dcd021a8caaf231e1c03cc513c97845c439ac | [
"users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}\nusers2 = {'2': 'Sam', '6': 'Kate'}\nusers.update(users2)\nkey = '2'\nprint(TestDict.test7_dict_update.__doc__)\nassert users.get(key) == 'Sam'\nprint('test7_dict_update passed')",
"users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}\nkey = '5'\nuser = users.pop(key, 'No... | <|body_start_0|>
users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}
users2 = {'2': 'Sam', '6': 'Kate'}
users.update(users2)
key = '2'
print(TestDict.test7_dict_update.__doc__)
assert users.get(key) == 'Sam'
print('test7_dict_update passed')
<|end_body_0|>
<|body_star... | TestDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDict:
def test7_dict_update(self):
"""Тест 'test7_dict_update' проверяет объединение двух словарей"""
<|body_0|>
def test8_dict_pop(self):
"""Тест 'test8_dict_pop' проверяет удаление элементе из словаря"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008090 | 928 | no_license | [
{
"docstring": "Тест 'test7_dict_update' проверяет объединение двух словарей",
"name": "test7_dict_update",
"signature": "def test7_dict_update(self)"
},
{
"docstring": "Тест 'test8_dict_pop' проверяет удаление элементе из словаря",
"name": "test8_dict_pop",
"signature": "def test8_dict_... | 2 | stack_v2_sparse_classes_30k_val_001060 | Implement the Python class `TestDict` described below.
Class description:
Implement the TestDict class.
Method signatures and docstrings:
- def test7_dict_update(self): Тест 'test7_dict_update' проверяет объединение двух словарей
- def test8_dict_pop(self): Тест 'test8_dict_pop' проверяет удаление элементе из словаря | Implement the Python class `TestDict` described below.
Class description:
Implement the TestDict class.
Method signatures and docstrings:
- def test7_dict_update(self): Тест 'test7_dict_update' проверяет объединение двух словарей
- def test8_dict_pop(self): Тест 'test8_dict_pop' проверяет удаление элементе из словаря... | 49fd8e5b4da76b1ab9c21e34ce89d0082bed5e56 | <|skeleton|>
class TestDict:
def test7_dict_update(self):
"""Тест 'test7_dict_update' проверяет объединение двух словарей"""
<|body_0|>
def test8_dict_pop(self):
"""Тест 'test8_dict_pop' проверяет удаление элементе из словаря"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDict:
def test7_dict_update(self):
"""Тест 'test7_dict_update' проверяет объединение двух словарей"""
users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}
users2 = {'2': 'Sam', '6': 'Kate'}
users.update(users2)
key = '2'
print(TestDict.test7_dict_update.__doc__)
... | the_stack_v2_python_sparse | Homework_1_3/test_dict.py | Kyanty/qa_automation | train | 0 | |
c0556db27156afc71adaf281f915ca315b6cb3ba | [
"super(MKCNN, self).__init__()\nself.input_size = input_size\nself.conv1_in, self.conv1_out, self.conv1_kernel = (num_input_frames, 9, 3)\nself.conv1_max_kernel = 3\nself.conv2_in, self.conv2_out, self.conv2_kernel = (self.conv1_out, 6, 3)\nself.fc_hidden1 = self.conv2_out * 5 * 5\nself.fc_hidden2 = 64\nself.fc_hid... | <|body_start_0|>
super(MKCNN, self).__init__()
self.input_size = input_size
self.conv1_in, self.conv1_out, self.conv1_kernel = (num_input_frames, 9, 3)
self.conv1_max_kernel = 3
self.conv2_in, self.conv2_out, self.conv2_kernel = (self.conv1_out, 6, 3)
self.fc_hidden1 = se... | MKCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MKCNN:
def __init__(self):
"""Convolutional neural network (CNN) architecture of Mario Kart AI agent."""
<|body_0|>
def forward(self, x):
"""Forward pass of the neural network. Accepts a tensor of size input_size*input_size."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_008091 | 5,117 | permissive | [
{
"docstring": "Convolutional neural network (CNN) architecture of Mario Kart AI agent.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Forward pass of the neural network. Accepts a tensor of size input_size*input_size.",
"name": "forward",
"signature": "def fo... | 2 | stack_v2_sparse_classes_30k_train_020150 | Implement the Python class `MKCNN` described below.
Class description:
Implement the MKCNN class.
Method signatures and docstrings:
- def __init__(self): Convolutional neural network (CNN) architecture of Mario Kart AI agent.
- def forward(self, x): Forward pass of the neural network. Accepts a tensor of size input_s... | Implement the Python class `MKCNN` described below.
Class description:
Implement the MKCNN class.
Method signatures and docstrings:
- def __init__(self): Convolutional neural network (CNN) architecture of Mario Kart AI agent.
- def forward(self, x): Forward pass of the neural network. Accepts a tensor of size input_s... | c8a7d0f84ca39b41ebd3acb3791dd19cd7907264 | <|skeleton|>
class MKCNN:
def __init__(self):
"""Convolutional neural network (CNN) architecture of Mario Kart AI agent."""
<|body_0|>
def forward(self, x):
"""Forward pass of the neural network. Accepts a tensor of size input_size*input_size."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MKCNN:
def __init__(self):
"""Convolutional neural network (CNN) architecture of Mario Kart AI agent."""
super(MKCNN, self).__init__()
self.input_size = input_size
self.conv1_in, self.conv1_out, self.conv1_kernel = (num_input_frames, 9, 3)
self.conv1_max_kernel = 3
... | the_stack_v2_python_sparse | src/agents/mk_cnn_train.py | adriendod/dolphin-env-api | train | 0 | |
e223b7720b40dbf89be1618c31a14fd44756d6d2 | [
"cls.tool = feature(name, feature('name', sub=True), feature('version', sub=True))\nfor k, v in dict.items():\n if isinstance(v, action):\n v._cls = cls\n v.name = k",
"a = type.__getattribute__(cls, name)\nif isinstance(a, action) and a._cls is not cls:\n a = deepcopy(a)\n a._cls = cls\nre... | <|body_start_0|>
cls.tool = feature(name, feature('name', sub=True), feature('version', sub=True))
for k, v in dict.items():
if isinstance(v, action):
v._cls = cls
v.name = k
<|end_body_0|>
<|body_start_1|>
a = type.__getattribute__(cls, name)
... | tool_type | [
"BSL-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tool_type:
def __init__(cls, name, bases, dict):
"""For any attribute of type 'action', set the action's name to the attribute name. Further, set the action's 'tool' attribute to be cls. This provides a means to look up virtual overloads. For example, if a rule refers to 'compiler.link',... | stack_v2_sparse_classes_75kplus_train_008092 | 6,408 | permissive | [
{
"docstring": "For any attribute of type 'action', set the action's name to the attribute name. Further, set the action's 'tool' attribute to be cls. This provides a means to look up virtual overloads. For example, if a rule refers to 'compiler.link', and the build is invoked with 'compiler=gcc', we can substi... | 2 | stack_v2_sparse_classes_30k_train_001124 | Implement the Python class `tool_type` described below.
Class description:
Implement the tool_type class.
Method signatures and docstrings:
- def __init__(cls, name, bases, dict): For any attribute of type 'action', set the action's name to the attribute name. Further, set the action's 'tool' attribute to be cls. Thi... | Implement the Python class `tool_type` described below.
Class description:
Implement the tool_type class.
Method signatures and docstrings:
- def __init__(cls, name, bases, dict): For any attribute of type 'action', set the action's name to the attribute name. Further, set the action's 'tool' attribute to be cls. Thi... | 0f369a8a9e4de305e5379d9662b2e79bffd43910 | <|skeleton|>
class tool_type:
def __init__(cls, name, bases, dict):
"""For any attribute of type 'action', set the action's name to the attribute name. Further, set the action's 'tool' attribute to be cls. This provides a means to look up virtual overloads. For example, if a rule refers to 'compiler.link',... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class tool_type:
def __init__(cls, name, bases, dict):
"""For any attribute of type 'action', set the action's name to the attribute name. Further, set the action's 'tool' attribute to be cls. This provides a means to look up virtual overloads. For example, if a rule refers to 'compiler.link', and the build... | the_stack_v2_python_sparse | src/faber/tool.py | stefanseefeld/faber | train | 15 | |
2a4ebd99704eb4578a81bb9c4c9b506e58ada242 | [
"for n, f in enumerate(filters):\n dc = odict(DIMENSIONS)\n if isinstance(f, (str, unicode)):\n filters[n] = eval(f)\nfact_aliases = facts[:]\nfacts = []\nfor f in fact_aliases:\n if f not in FACTS:\n raise ValueError('Unknown fact: %s' % f)\n facts.append(FACTS[f])\ndim_aliases = dimensio... | <|body_start_0|>
for n, f in enumerate(filters):
dc = odict(DIMENSIONS)
if isinstance(f, (str, unicode)):
filters[n] = eval(f)
fact_aliases = facts[:]
facts = []
for f in fact_aliases:
if f not in FACTS:
raise ValueError... | DataCube | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCube:
def getData(self, session, facts, dimensions, filters=[]):
"""General purpose summary data generator."""
<|body_0|>
def _gatherConds(self, attrs, conds):
"""Gather the conditions required to do the appropriate joins for the selected columns filters requeste... | stack_v2_sparse_classes_75kplus_train_008093 | 7,349 | no_license | [
{
"docstring": "General purpose summary data generator.",
"name": "getData",
"signature": "def getData(self, session, facts, dimensions, filters=[])"
},
{
"docstring": "Gather the conditions required to do the appropriate joins for the selected columns filters requested if any.",
"name": "_g... | 2 | null | Implement the Python class `DataCube` described below.
Class description:
Implement the DataCube class.
Method signatures and docstrings:
- def getData(self, session, facts, dimensions, filters=[]): General purpose summary data generator.
- def _gatherConds(self, attrs, conds): Gather the conditions required to do th... | Implement the Python class `DataCube` described below.
Class description:
Implement the DataCube class.
Method signatures and docstrings:
- def getData(self, session, facts, dimensions, filters=[]): General purpose summary data generator.
- def _gatherConds(self, attrs, conds): Gather the conditions required to do th... | a0edcc220f5c950838c0d0a5e42ee06bb7f2c6ad | <|skeleton|>
class DataCube:
def getData(self, session, facts, dimensions, filters=[]):
"""General purpose summary data generator."""
<|body_0|>
def _gatherConds(self, attrs, conds):
"""Gather the conditions required to do the appropriate joins for the selected columns filters requeste... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataCube:
def getData(self, session, facts, dimensions, filters=[]):
"""General purpose summary data generator."""
for n, f in enumerate(filters):
dc = odict(DIMENSIONS)
if isinstance(f, (str, unicode)):
filters[n] = eval(f)
fact_aliases = facts[... | the_stack_v2_python_sparse | datacube.py | ryanlowe0/misc-python | train | 0 | |
8ddae3bf5fe99f8205fa68ef0a40023f39467441 | [
"self.screen_width = 600\nself.screen_height = 400\nself.bg_color = (230, 30, 230)\nself.plane_limit = 3\nself.missle_width = 15\nself.missle_height = 3\nself.missle_color = (60, 60, 60)\nself.missles_allowed = 3\nself.fleet_drop_speed = 10\nself.speedup_scale = 2\nself.initialize_dynamic_settings()",
"self.plane... | <|body_start_0|>
self.screen_width = 600
self.screen_height = 400
self.bg_color = (230, 30, 230)
self.plane_limit = 3
self.missle_width = 15
self.missle_height = 3
self.missle_color = (60, 60, 60)
self.missles_allowed = 3
self.fleet_drop_speed = 10... | Класс для хранения всех настроек игры Alien Invasion | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует настройки игры"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры"""
<|body_1|>
def inc... | stack_v2_sparse_classes_75kplus_train_008094 | 1,225 | no_license | [
{
"docstring": "Инициализирует настройки игры",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Инициализирует настройки, изменяющиеся в ходе игры",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_025057 | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры
- def increas... | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры
- def increas... | 355d117ae48f78d331ef2cfc2f92551dc857cb58 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует настройки игры"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры"""
<|body_1|>
def inc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует настройки игры"""
self.screen_width = 600
self.screen_height = 400
self.bg_color = (230, 30, 230)
self.plane_limit = 3
self.missle_width = 15
... | the_stack_v2_python_sparse | Eric_Matthes/chapter_2/games/vertical/settings.py | rvdmtr/python | train | 0 |
bf39ff7a8923716007dba8836708fa272d543c38 | [
"this = cls()\nfor key, value in data.items():\n this[key] = [val['value'] for val in value]\nreturn this",
"norm_data = {}\nfor key, values in data.items():\n if isinstance(values, list):\n strings = []\n for value in values:\n if isinstance(value, str):\n strings.ap... | <|body_start_0|>
this = cls()
for key, value in data.items():
this[key] = [val['value'] for val in value]
return this
<|end_body_0|>
<|body_start_1|>
norm_data = {}
for key, values in data.items():
if isinstance(values, list):
strings = []... | A structure holding aliases for a Wikibase entity. It is a mapping from a language to a list of strings. | AliasesDict | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliasesDict:
"""A structure holding aliases for a Wikibase entity. It is a mapping from a language to a list of strings."""
def fromJSON(cls, data, repo=None):
"""Construct a new AliasesDict from JSON."""
<|body_0|>
def normalizeData(cls, data: dict) -> dict:
"""... | stack_v2_sparse_classes_75kplus_train_008095 | 18,327 | permissive | [
{
"docstring": "Construct a new AliasesDict from JSON.",
"name": "fromJSON",
"signature": "def fromJSON(cls, data, repo=None)"
},
{
"docstring": "Helper function to expand data into the Wikibase API structure. .. versionchanged:: 7.7 raises TypeError if *data* value is not a list. :param data: D... | 3 | stack_v2_sparse_classes_30k_train_046717 | Implement the Python class `AliasesDict` described below.
Class description:
A structure holding aliases for a Wikibase entity. It is a mapping from a language to a list of strings.
Method signatures and docstrings:
- def fromJSON(cls, data, repo=None): Construct a new AliasesDict from JSON.
- def normalizeData(cls, ... | Implement the Python class `AliasesDict` described below.
Class description:
A structure holding aliases for a Wikibase entity. It is a mapping from a language to a list of strings.
Method signatures and docstrings:
- def fromJSON(cls, data, repo=None): Construct a new AliasesDict from JSON.
- def normalizeData(cls, ... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class AliasesDict:
"""A structure holding aliases for a Wikibase entity. It is a mapping from a language to a list of strings."""
def fromJSON(cls, data, repo=None):
"""Construct a new AliasesDict from JSON."""
<|body_0|>
def normalizeData(cls, data: dict) -> dict:
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AliasesDict:
"""A structure holding aliases for a Wikibase entity. It is a mapping from a language to a list of strings."""
def fromJSON(cls, data, repo=None):
"""Construct a new AliasesDict from JSON."""
this = cls()
for key, value in data.items():
this[key] = [val['v... | the_stack_v2_python_sparse | pywikibot/page/_collections.py | wikimedia/pywikibot | train | 432 |
91f05379ee2aa8d2bc7eb8a68fabaa1321ae72d5 | [
"columns, substitutions, params_dict = QueryHelper.get_insert_strings_and_dict(ExpenditureMapping, expenditure, fields_to_exclude=['id'])\nquery = text('INSERT INTO {expenditures_table} ({columns}) VALUES ({substitutions}) RETURNING *'.format(expenditures_table=ExpenditureMapping.description, columns=columns, subst... | <|body_start_0|>
columns, substitutions, params_dict = QueryHelper.get_insert_strings_and_dict(ExpenditureMapping, expenditure, fields_to_exclude=['id'])
query = text('INSERT INTO {expenditures_table} ({columns}) VALUES ({substitutions}) RETURNING *'.format(expenditures_table=ExpenditureMapping.descript... | ExpenditureRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpenditureRepository:
def add_new_expenditure(cls, expenditure: Expenditure):
"""Add new expenditure to the database"""
<|body_0|>
def update_expenditure(cls, expenditure: Expenditure):
"""Updates existing expenditure"""
<|body_1|>
def get_expenditure_b... | stack_v2_sparse_classes_75kplus_train_008096 | 8,215 | no_license | [
{
"docstring": "Add new expenditure to the database",
"name": "add_new_expenditure",
"signature": "def add_new_expenditure(cls, expenditure: Expenditure)"
},
{
"docstring": "Updates existing expenditure",
"name": "update_expenditure",
"signature": "def update_expenditure(cls, expenditure... | 3 | stack_v2_sparse_classes_30k_train_032526 | Implement the Python class `ExpenditureRepository` described below.
Class description:
Implement the ExpenditureRepository class.
Method signatures and docstrings:
- def add_new_expenditure(cls, expenditure: Expenditure): Add new expenditure to the database
- def update_expenditure(cls, expenditure: Expenditure): Upd... | Implement the Python class `ExpenditureRepository` described below.
Class description:
Implement the ExpenditureRepository class.
Method signatures and docstrings:
- def add_new_expenditure(cls, expenditure: Expenditure): Add new expenditure to the database
- def update_expenditure(cls, expenditure: Expenditure): Upd... | d5e383a3a703c973d038627f35d405e716cfd25c | <|skeleton|>
class ExpenditureRepository:
def add_new_expenditure(cls, expenditure: Expenditure):
"""Add new expenditure to the database"""
<|body_0|>
def update_expenditure(cls, expenditure: Expenditure):
"""Updates existing expenditure"""
<|body_1|>
def get_expenditure_b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExpenditureRepository:
def add_new_expenditure(cls, expenditure: Expenditure):
"""Add new expenditure to the database"""
columns, substitutions, params_dict = QueryHelper.get_insert_strings_and_dict(ExpenditureMapping, expenditure, fields_to_exclude=['id'])
query = text('INSERT INTO {e... | the_stack_v2_python_sparse | app/events/finance/repository.py | Innodogs/Innodogs | train | 0 | |
aee5f921b197272216abd6db0f4c73ae10077b7f | [
"for j in range(len(nums)):\n for k in range(j + 1, len(nums)):\n if nums[j] + nums[k] == target:\n return (j, k)",
"memo = {}\nfor i in range(len(nums)):\n if nums[i] in memo:\n return (memo[nums[i]], i)\n elif target - nums[i] not in memo:\n memo[target - nums[i]] = i"
] | <|body_start_0|>
for j in range(len(nums)):
for k in range(j + 1, len(nums)):
if nums[j] + nums[k] == target:
return (j, k)
<|end_body_0|>
<|body_start_1|>
memo = {}
for i in range(len(nums)):
if nums[i] in memo:
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_008097 | 1,211 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
}... | 2 | stack_v2_sparse_classes_30k_train_029793 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | af3b19adefb31ea17fa8096eb03a77634795a807 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for j in range(len(nums)):
for k in range(j + 1, len(nums)):
if nums[j] + nums[k] == target:
return (j, k)
def twoSum2(self, nums, targ... | the_stack_v2_python_sparse | ib/5.Hashing/LC001. Two Sum.py | qq279585876/algorithm | train | 0 | |
a2d690ee93c06ff051f58facaa6be11a8a9a0596 | [
"self.logger = logger.SecureTeaLogger(__name__, debug=debug)\nself.rts_count = 0\nself.cts_count = 0\nself.rts_start_time = None\nself.cts_start_time = None\nself._THRESHOLD = 5",
"if pkt.haslayer(scapy.Dot11):\n subtype = int(pkt[scapy.Dot11].subtype)\n if subtype == 11:\n self.rts_count = self.rts_... | <|body_start_0|>
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self.rts_count = 0
self.cts_count = 0
self.rts_start_time = None
self.cts_start_time = None
self._THRESHOLD = 5
<|end_body_0|>
<|body_start_1|>
if pkt.haslayer(scapy.Dot11):
... | HiddenNode Class. | HiddenNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiddenNode:
"""HiddenNode Class."""
def __init__(self, debug=False):
"""Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect_hidden_node(self, pkt):
"""Count RTS & CTS packet threshold ratio t... | stack_v2_sparse_classes_75kplus_train_008098 | 3,487 | permissive | [
{
"docstring": "Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Count RTS & CTS packet threshold ratio to detect hidden node attack. Generally, they should b... | 3 | stack_v2_sparse_classes_30k_train_022212 | Implement the Python class `HiddenNode` described below.
Class description:
HiddenNode Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect_hidden_node(self, pkt): Count RTS & CTS pac... | Implement the Python class `HiddenNode` described below.
Class description:
HiddenNode Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect_hidden_node(self, pkt): Count RTS & CTS pac... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class HiddenNode:
"""HiddenNode Class."""
def __init__(self, debug=False):
"""Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect_hidden_node(self, pkt):
"""Count RTS & CTS packet threshold ratio t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HiddenNode:
"""HiddenNode Class."""
def __init__(self, debug=False):
"""Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self.rts_count = 0
self.cts_count = 0
... | the_stack_v2_python_sparse | securetea/lib/ids/r2l_rules/wireless/hidden_node.py | rejahrehim/SecureTea-Project | train | 1 |
b221bdfc6076c89845c73d36b8bbc78e055507c9 | [
"self.callback = callback\nself.port = port\nrfid_loop = threading.Thread(target=self.read_rfid)\nrfid_loop.start()",
"reader = RFIDTagReader.TagReader(self.port)\ntaginfo = ''\nwhile True:\n try:\n taginfo = str(reader.readTag())\n if taginfo is not None:\n print('Read RFID Tag:', tag... | <|body_start_0|>
self.callback = callback
self.port = port
rfid_loop = threading.Thread(target=self.read_rfid)
rfid_loop.start()
<|end_body_0|>
<|body_start_1|>
reader = RFIDTagReader.TagReader(self.port)
taginfo = ''
while True:
try:
... | loops and checks to see if the RFID tag has been read, then calls | RFIDReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RFIDReader:
"""loops and checks to see if the RFID tag has been read, then calls"""
def __init__(self, callback, port='/dev/ttyUSB0'):
""":param callback: function to call when tag is read :type callback: :param port: USB port for the RFID reader. I think is is always /dev/ttyUSB0 :t... | stack_v2_sparse_classes_75kplus_train_008099 | 40,088 | no_license | [
{
"docstring": ":param callback: function to call when tag is read :type callback: :param port: USB port for the RFID reader. I think is is always /dev/ttyUSB0 :type port: str",
"name": "__init__",
"signature": "def __init__(self, callback, port='/dev/ttyUSB0')"
},
{
"docstring": "polls the rfid... | 2 | stack_v2_sparse_classes_30k_train_009860 | Implement the Python class `RFIDReader` described below.
Class description:
loops and checks to see if the RFID tag has been read, then calls
Method signatures and docstrings:
- def __init__(self, callback, port='/dev/ttyUSB0'): :param callback: function to call when tag is read :type callback: :param port: USB port ... | Implement the Python class `RFIDReader` described below.
Class description:
loops and checks to see if the RFID tag has been read, then calls
Method signatures and docstrings:
- def __init__(self, callback, port='/dev/ttyUSB0'): :param callback: function to call when tag is read :type callback: :param port: USB port ... | 622cc666019753c4736c03be0d41308212c84291 | <|skeleton|>
class RFIDReader:
"""loops and checks to see if the RFID tag has been read, then calls"""
def __init__(self, callback, port='/dev/ttyUSB0'):
""":param callback: function to call when tag is read :type callback: :param port: USB port for the RFID reader. I think is is always /dev/ttyUSB0 :t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RFIDReader:
"""loops and checks to see if the RFID tag has been read, then calls"""
def __init__(self, callback, port='/dev/ttyUSB0'):
""":param callback: function to call when tag is read :type callback: :param port: USB port for the RFID reader. I think is is always /dev/ttyUSB0 :type port: str... | the_stack_v2_python_sparse | SonosHW.py | gshorten/SonosController | train | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.