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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
56dac7da66f25a02a1fd3c3c9535e3d6a453a9db | [
"i = len(nums) - 2\nwhile i >= 0 and nums[i] >= nums[i + 1]:\n i -= 1\nif i < 0:\n nums.reverse()\nelse:\n j = len(nums) - 1\n while j > i and nums[j] <= nums[i]:\n j -= 1\n nums[i], nums[j] = (nums[j], nums[i])\n self.reverse(nums, i + 1)",
"end = len(nums) - 1\nwhile begin < end:\n n... | <|body_start_0|>
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i < 0:
nums.reverse()
else:
j = len(nums) - 1
while j > i and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = (nums[j], nums[i])... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def reverse(self, nums, begin):
""":type nums: List[int] :type begin: int :rtype: void"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_000300 | 1,044 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "nextPermutation",
"signature": "def nextPermutation(self, nums)"
},
{
"docstring": ":type nums: List[int] :type begin: int :rtype: void",
"name": "reverse",
"signature": "d... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def reverse(self, nums, begin): :type nums: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def reverse(self, nums, begin): :type nums: List[int] ... | cb70ca87aa4604d1aec83d4224b3489eacebba75 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def reverse(self, nums, begin):
""":type nums: List[int] :type begin: int :rtype: void"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i < 0:
nums.reverse()
else:
... | the_stack_v2_python_sparse | LeetCode/Python3/0031._Next_Permutation.py | icgw/practice | train | 1 | |
9e322cc30a5eddaa844808e4aab15742eaf2c06a | [
"N, W, H, C = images_ph.get_shape().as_list()\nself.conv_layers = config.conv_layers\nself.original_size = config.new_size\nself.num_channels = C\nself.sensor_size = config.sensor_size\nself.n_patches = config.n_patches\nself.glimpse_size = config.glimpse_size\nself.scale = config.scale\nself.minRadius = config.min... | <|body_start_0|>
N, W, H, C = images_ph.get_shape().as_list()
self.conv_layers = config.conv_layers
self.original_size = config.new_size
self.num_channels = C
self.sensor_size = config.sensor_size
self.n_patches = config.n_patches
self.glimpse_size = config.glimps... | Takes image and previous glimpse location and outputs feature vector. | GlimpseNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlimpseNetwork:
"""Takes image and previous glimpse location and outputs feature vector."""
def __init__(self, config, images_ph):
""":param config: (object) hyperparams :param images_ph: (placeholder) 4D tensor, format 'NHWC'"""
<|body_0|>
def init_weights(self):
... | stack_v2_sparse_classes_75kplus_train_000301 | 8,856 | no_license | [
{
"docstring": ":param config: (object) hyperparams :param images_ph: (placeholder) 4D tensor, format 'NHWC'",
"name": "__init__",
"signature": "def __init__(self, config, images_ph)"
},
{
"docstring": "Initialize all trainable weights.",
"name": "init_weights",
"signature": "def init_we... | 4 | stack_v2_sparse_classes_30k_train_027095 | Implement the Python class `GlimpseNetwork` described below.
Class description:
Takes image and previous glimpse location and outputs feature vector.
Method signatures and docstrings:
- def __init__(self, config, images_ph): :param config: (object) hyperparams :param images_ph: (placeholder) 4D tensor, format 'NHWC'
... | Implement the Python class `GlimpseNetwork` described below.
Class description:
Takes image and previous glimpse location and outputs feature vector.
Method signatures and docstrings:
- def __init__(self, config, images_ph): :param config: (object) hyperparams :param images_ph: (placeholder) 4D tensor, format 'NHWC'
... | 05cb7eb519e7feebaf818f5e7aa401ae9b4d70d8 | <|skeleton|>
class GlimpseNetwork:
"""Takes image and previous glimpse location and outputs feature vector."""
def __init__(self, config, images_ph):
""":param config: (object) hyperparams :param images_ph: (placeholder) 4D tensor, format 'NHWC'"""
<|body_0|>
def init_weights(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GlimpseNetwork:
"""Takes image and previous glimpse location and outputs feature vector."""
def __init__(self, config, images_ph):
""":param config: (object) hyperparams :param images_ph: (placeholder) 4D tensor, format 'NHWC'"""
N, W, H, C = images_ph.get_shape().as_list()
self.c... | the_stack_v2_python_sparse | ConvNet.py | amobiny/Recurrent_Attention_Model | train | 10 |
230d32d35cea9666b2ea89f931cad91fe0034d46 | [
"new_head = ListNode(0)\nnew_head.next = head\nwhile head.next != None:\n p = head.next\n head.next = p.next\n p.next = new_head.next\n new_head.next = p\nreturn new_head.next",
"if n == 1:\n return head\nprev = ListNode(0)\nprev.next = head\ncur = head\nhead = prev\nfor i in range(1, n):\n if i... | <|body_start_0|>
new_head = ListNode(0)
new_head.next = head
while head.next != None:
p = head.next
head.next = p.next
p.next = new_head.next
new_head.next = p
return new_head.next
<|end_body_0|>
<|body_start_1|>
if n == 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
"""反转一个单链表。 :param head: :return:"""
<|body_0|>
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
"""反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 :param head: :param m: :param n: :return:"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_000302 | 1,905 | no_license | [
{
"docstring": "反转一个单链表。 :param head: :return:",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": "反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 :param head: :param m: :param n: :return:",
"name": "reverseBetween",
"signature": "def reverseBetween(self, head: ListNode, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): 反转一个单链表。 :param head: :return:
- def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 :param head: :par... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): 反转一个单链表。 :param head: :return:
- def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 :param head: :par... | ed4c984b5527c0b208c8fd66ce6bce19b344e4dd | <|skeleton|>
class Solution:
def reverseList(self, head):
"""反转一个单链表。 :param head: :return:"""
<|body_0|>
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
"""反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 :param head: :param m: :param n: :return:"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head):
"""反转一个单链表。 :param head: :return:"""
new_head = ListNode(0)
new_head.next = head
while head.next != None:
p = head.next
head.next = p.next
p.next = new_head.next
new_head.next = p
ret... | the_stack_v2_python_sparse | 92-206-reverse-list.py | jankin3/project-leetcode | train | 1 | |
41b12966141c87aa2c88530b85f41e378eb7a2d1 | [
"if self.field:\n return 'Top filtered results for \"{0:s}\"'.format(self.field)\nreturn 'Top results for an unknown field after filtering'",
"if not (query_string or query_dsl):\n raise ValueError('Both query_string and query_dsl are missing')\nself.field = field\nformatted_field_name = self.format_field_b... | <|body_start_0|>
if self.field:
return 'Top filtered results for "{0:s}"'.format(self.field)
return 'Top results for an unknown field after filtering'
<|end_body_0|>
<|body_start_1|>
if not (query_string or query_dsl):
raise ValueError('Both query_string and query_dsl ar... | Query Filter Term Aggregation. | FilteredTermsAggregation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilteredTermsAggregation:
"""Query Filter Term Aggregation."""
def chart_title(self):
"""Returns a title for the chart."""
<|body_0|>
def run(self, field, query_string='', query_dsl='', supported_charts='table', start_time='', end_time='', limit=10):
"""Run the a... | stack_v2_sparse_classes_75kplus_train_000303 | 7,686 | permissive | [
{
"docstring": "Returns a title for the chart.",
"name": "chart_title",
"signature": "def chart_title(self)"
},
{
"docstring": "Run the aggregation. Args: field (str): this denotes the event attribute that is used for aggregation. query_string (str): the query field to run on all documents prior... | 2 | stack_v2_sparse_classes_30k_train_002860 | Implement the Python class `FilteredTermsAggregation` described below.
Class description:
Query Filter Term Aggregation.
Method signatures and docstrings:
- def chart_title(self): Returns a title for the chart.
- def run(self, field, query_string='', query_dsl='', supported_charts='table', start_time='', end_time='',... | Implement the Python class `FilteredTermsAggregation` described below.
Class description:
Query Filter Term Aggregation.
Method signatures and docstrings:
- def chart_title(self): Returns a title for the chart.
- def run(self, field, query_string='', query_dsl='', supported_charts='table', start_time='', end_time='',... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class FilteredTermsAggregation:
"""Query Filter Term Aggregation."""
def chart_title(self):
"""Returns a title for the chart."""
<|body_0|>
def run(self, field, query_string='', query_dsl='', supported_charts='table', start_time='', end_time='', limit=10):
"""Run the a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilteredTermsAggregation:
"""Query Filter Term Aggregation."""
def chart_title(self):
"""Returns a title for the chart."""
if self.field:
return 'Top filtered results for "{0:s}"'.format(self.field)
return 'Top results for an unknown field after filtering'
def run... | the_stack_v2_python_sparse | timesketch/lib/aggregators/term.py | google/timesketch | train | 2,263 |
435b2f192cd22e0af748734c701b465bcc46ee9f | [
"agent = request.user.userinfo.agent\ndata = ModelMessage.get_msg_info(agent_id=agent.id)\ndata['password'] = ''\ncontext = {'status': 200, 'msg': '获取数据成功', 'data': data}\nreturn Response(context)",
"agent = request.user.userinfo.agent\nobj = ModelMessage.objects.get_or_create(agent=agent, type=2)[0]\nmsg_seriali... | <|body_start_0|>
agent = request.user.userinfo.agent
data = ModelMessage.get_msg_info(agent_id=agent.id)
data['password'] = ''
context = {'status': 200, 'msg': '获取数据成功', 'data': data}
return Response(context)
<|end_body_0|>
<|body_start_1|>
agent = request.user.userinfo.... | 短信设置 | Message | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""短信设置"""
def get(self, request):
"""获取短信设置信息"""
<|body_0|>
def put(self, request):
"""修改短信设置信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
agent = request.user.userinfo.agent
data = ModelMessage.get_msg_info(agent_id=agent... | stack_v2_sparse_classes_75kplus_train_000304 | 32,690 | no_license | [
{
"docstring": "获取短信设置信息",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改短信设置信息",
"name": "put",
"signature": "def put(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011758 | Implement the Python class `Message` described below.
Class description:
短信设置
Method signatures and docstrings:
- def get(self, request): 获取短信设置信息
- def put(self, request): 修改短信设置信息 | Implement the Python class `Message` described below.
Class description:
短信设置
Method signatures and docstrings:
- def get(self, request): 获取短信设置信息
- def put(self, request): 修改短信设置信息
<|skeleton|>
class Message:
"""短信设置"""
def get(self, request):
"""获取短信设置信息"""
<|body_0|>
def put(self, re... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class Message:
"""短信设置"""
def get(self, request):
"""获取短信设置信息"""
<|body_0|>
def put(self, request):
"""修改短信设置信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Message:
"""短信设置"""
def get(self, request):
"""获取短信设置信息"""
agent = request.user.userinfo.agent
data = ModelMessage.get_msg_info(agent_id=agent.id)
data['password'] = ''
context = {'status': 200, 'msg': '获取数据成功', 'data': data}
return Response(context)
d... | the_stack_v2_python_sparse | soc_system/views/set_views.py | sundw2015/841 | train | 4 |
1fa915d0ef6be4fd3441a7d1497ac0fe9d037676 | [
"query = db.session.query(manager.group_permission_model.permission_id).filter(manager.group_permission_model.group_id == group_id)\nresult = cls.query.filter_by(soft=True, mount=True).filter(cls.id.in_(query))\npermissions = result.all()\nreturn permissions",
"query = db.session.query(manager.group_permission_mo... | <|body_start_0|>
query = db.session.query(manager.group_permission_model.permission_id).filter(manager.group_permission_model.group_id == group_id)
result = cls.query.filter_by(soft=True, mount=True).filter(cls.id.in_(query))
permissions = result.all()
return permissions
<|end_body_0|>
... | Permission | [
"MIT",
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Permission:
def select_by_group_id(cls, group_id) -> list:
"""传入用户组Id ,根据 Group-Permission关联表 获取 权限列表"""
<|body_0|>
def select_by_group_ids(cls, group_ids: list) -> list:
"""传入用户组Id列表 ,根据 Group-Permission关联表 获取 权限列表"""
<|body_1|>
def select_by_group_ids_... | stack_v2_sparse_classes_75kplus_train_000305 | 1,653 | permissive | [
{
"docstring": "传入用户组Id ,根据 Group-Permission关联表 获取 权限列表",
"name": "select_by_group_id",
"signature": "def select_by_group_id(cls, group_id) -> list"
},
{
"docstring": "传入用户组Id列表 ,根据 Group-Permission关联表 获取 权限列表",
"name": "select_by_group_ids",
"signature": "def select_by_group_ids(cls, gr... | 3 | stack_v2_sparse_classes_30k_train_043202 | Implement the Python class `Permission` described below.
Class description:
Implement the Permission class.
Method signatures and docstrings:
- def select_by_group_id(cls, group_id) -> list: 传入用户组Id ,根据 Group-Permission关联表 获取 权限列表
- def select_by_group_ids(cls, group_ids: list) -> list: 传入用户组Id列表 ,根据 Group-Permission... | Implement the Python class `Permission` described below.
Class description:
Implement the Permission class.
Method signatures and docstrings:
- def select_by_group_id(cls, group_id) -> list: 传入用户组Id ,根据 Group-Permission关联表 获取 权限列表
- def select_by_group_ids(cls, group_ids: list) -> list: 传入用户组Id列表 ,根据 Group-Permission... | ae4a649a678e9e57d537d92c9a634648d6985e2d | <|skeleton|>
class Permission:
def select_by_group_id(cls, group_id) -> list:
"""传入用户组Id ,根据 Group-Permission关联表 获取 权限列表"""
<|body_0|>
def select_by_group_ids(cls, group_ids: list) -> list:
"""传入用户组Id列表 ,根据 Group-Permission关联表 获取 权限列表"""
<|body_1|>
def select_by_group_ids_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Permission:
def select_by_group_id(cls, group_id) -> list:
"""传入用户组Id ,根据 Group-Permission关联表 获取 权限列表"""
query = db.session.query(manager.group_permission_model.permission_id).filter(manager.group_permission_model.group_id == group_id)
result = cls.query.filter_by(soft=True, mount=True... | the_stack_v2_python_sparse | app/api/cms/model/permission.py | TaleLin/lin-cms-flask | train | 881 | |
d005558ccb96764cc0a13447a44630ba80046cd9 | [
"super().__init__(unique_id, model)\nself.pos = np.array(pos)\nself.speed = speed\nself.velocity = velocity\nself.vision = vision\nself.separation = separation\nself.cohere_factor = cohere\nself.separate_factor = separate\nself.match_factor = match",
"cohere = np.zeros(2)\nif neighbors:\n for neighbor in neigh... | <|body_start_0|>
super().__init__(unique_id, model)
self.pos = np.array(pos)
self.speed = speed
self.velocity = velocity
self.vision = vision
self.separation = separation
self.cohere_factor = cohere
self.separate_factor = separate
self.match_factor... | A Boid-style flocker agent. The agent follows three behaviors to flock: - Cohesion: steering towards neighboring agents. - Separation: avoiding getting too close to any other agent. - Alignment: try to fly in the same direction as the neighbors. Boids have a vision that defines the radius in which they look for their n... | Boid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Boid:
"""A Boid-style flocker agent. The agent follows three behaviors to flock: - Cohesion: steering towards neighboring agents. - Separation: avoiding getting too close to any other agent. - Alignment: try to fly in the same direction as the neighbors. Boids have a vision that defines the radiu... | stack_v2_sparse_classes_75kplus_train_000306 | 7,183 | no_license | [
{
"docstring": "Create a new Boid flocker agent. Args: unique_id: Unique agent identifyer. pos: Starting position speed: Distance to move per step. vision: Radius to look around for nearby Boids. separation: Minimum distance to maintain from other Boids. cohere: the relative importance of matching neighbors' po... | 5 | stack_v2_sparse_classes_30k_test_001933 | Implement the Python class `Boid` described below.
Class description:
A Boid-style flocker agent. The agent follows three behaviors to flock: - Cohesion: steering towards neighboring agents. - Separation: avoiding getting too close to any other agent. - Alignment: try to fly in the same direction as the neighbors. Boi... | Implement the Python class `Boid` described below.
Class description:
A Boid-style flocker agent. The agent follows three behaviors to flock: - Cohesion: steering towards neighboring agents. - Separation: avoiding getting too close to any other agent. - Alignment: try to fly in the same direction as the neighbors. Boi... | 18166af285d2a40f903bc178f5c37b7d758fb0bd | <|skeleton|>
class Boid:
"""A Boid-style flocker agent. The agent follows three behaviors to flock: - Cohesion: steering towards neighboring agents. - Separation: avoiding getting too close to any other agent. - Alignment: try to fly in the same direction as the neighbors. Boids have a vision that defines the radiu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Boid:
"""A Boid-style flocker agent. The agent follows three behaviors to flock: - Cohesion: steering towards neighboring agents. - Separation: avoiding getting too close to any other agent. - Alignment: try to fly in the same direction as the neighbors. Boids have a vision that defines the radius in which th... | the_stack_v2_python_sparse | alternative_models/boids.py | sowasser/fish-shoaling-model | train | 1 |
9ff6fa0689df07d762130982cb388ce431bd6447 | [
"def get_class_arguments(class_):\n \"\"\"\n :param class_: the class to check\n :return: a list containing the arguments from `class_`\n \"\"\"\n signature = inspect.signature(class_.__init__)\n class_arguments = [p.name for p in signature.parameters.values()]\n return ... | <|body_start_0|>
def get_class_arguments(class_):
"""
:param class_: the class to check
:return: a list containing the arguments from `class_`
"""
signature = inspect.signature(class_.__init__)
class_arguments = [p.n... | Legacy parser for executor. | LegacyParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegacyParser:
"""Legacy parser for executor."""
def _get_all_arguments(class_):
""":param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits"""
<|body_0|>
def parse(self, cls: Type['Bas... | stack_v2_sparse_classes_75kplus_train_000307 | 5,038 | permissive | [
{
"docstring": ":param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits",
"name": "_get_all_arguments",
"signature": "def _get_all_arguments(class_)"
},
{
"docstring": ":param cls: target class type to parse ... | 4 | stack_v2_sparse_classes_30k_train_034969 | Implement the Python class `LegacyParser` described below.
Class description:
Legacy parser for executor.
Method signatures and docstrings:
- def _get_all_arguments(class_): :param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits
... | Implement the Python class `LegacyParser` described below.
Class description:
Legacy parser for executor.
Method signatures and docstrings:
- def _get_all_arguments(class_): :param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits
... | 4265163fafe499f80dc52be4a437087bf3c1799f | <|skeleton|>
class LegacyParser:
"""Legacy parser for executor."""
def _get_all_arguments(class_):
""":param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits"""
<|body_0|>
def parse(self, cls: Type['Bas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LegacyParser:
"""Legacy parser for executor."""
def _get_all_arguments(class_):
""":param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits"""
def get_class_arguments(class_):
"""
... | the_stack_v2_python_sparse | jina/jaml/parsers/executor/legacy.py | VenusTokyo/jina | train | 1 |
6a8d51385bc02d017f1e248dc33e066d50abc2d2 | [
"self.nodes_count = n\nself.graph = [[] for _ in range(n)]\nfor rib, rib_weight in pairs:\n self.graph[rib[0] - 1].append((rib[1] - 1, rib_weight))",
"cur_node = [np.inf, 0]\nfor i in range(self.nodes_count):\n if d[i] < cur_node[0] and (not used[i]):\n cur_node = [d[i], i]\nreturn (cur_node, d, used... | <|body_start_0|>
self.nodes_count = n
self.graph = [[] for _ in range(n)]
for rib, rib_weight in pairs:
self.graph[rib[0] - 1].append((rib[1] - 1, rib_weight))
<|end_body_0|>
<|body_start_1|>
cur_node = [np.inf, 0]
for i in range(self.nodes_count):
if d[i... | Dijkstra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dijkstra:
def __init__(self, pairs, n):
"""Create graph for dijkstra algorithm :param pairs: :return:"""
<|body_0|>
def __find_next_node(self, d, used):
"""Find next node with min weight :param d: :param used: :return:"""
<|body_1|>
def solve(self, start... | stack_v2_sparse_classes_75kplus_train_000308 | 2,687 | no_license | [
{
"docstring": "Create graph for dijkstra algorithm :param pairs: :return:",
"name": "__init__",
"signature": "def __init__(self, pairs, n)"
},
{
"docstring": "Find next node with min weight :param d: :param used: :return:",
"name": "__find_next_node",
"signature": "def __find_next_node(... | 3 | stack_v2_sparse_classes_30k_train_034733 | Implement the Python class `Dijkstra` described below.
Class description:
Implement the Dijkstra class.
Method signatures and docstrings:
- def __init__(self, pairs, n): Create graph for dijkstra algorithm :param pairs: :return:
- def __find_next_node(self, d, used): Find next node with min weight :param d: :param us... | Implement the Python class `Dijkstra` described below.
Class description:
Implement the Dijkstra class.
Method signatures and docstrings:
- def __init__(self, pairs, n): Create graph for dijkstra algorithm :param pairs: :return:
- def __find_next_node(self, d, used): Find next node with min weight :param d: :param us... | e672e0232ba7978107ab9fac2624e5bccf5f6a46 | <|skeleton|>
class Dijkstra:
def __init__(self, pairs, n):
"""Create graph for dijkstra algorithm :param pairs: :return:"""
<|body_0|>
def __find_next_node(self, d, used):
"""Find next node with min weight :param d: :param used: :return:"""
<|body_1|>
def solve(self, start... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dijkstra:
def __init__(self, pairs, n):
"""Create graph for dijkstra algorithm :param pairs: :return:"""
self.nodes_count = n
self.graph = [[] for _ in range(n)]
for rib, rib_weight in pairs:
self.graph[rib[0] - 1].append((rib[1] - 1, rib_weight))
def __find_ne... | the_stack_v2_python_sparse | SAiIO/src/dijkstra.py | qqpoltergeist/BSUIR-IITP-2016-2020 | train | 0 | |
580f6996e5d90cbce11380ce7de04ceefbf2d2cd | [
"DATA_PATH = os.path.join(path, f'{project_name}.yaml') if project_name else path\ntry:\n with open(DATA_PATH, encoding='utf-8') as temp:\n datas = yaml.safe_load(temp)\n data = datas.get(module_name, None)\n return data if data else datas\nexcept:\n logger.error(f'此文件{DATA_PATH}不存在')",
"browse... | <|body_start_0|>
DATA_PATH = os.path.join(path, f'{project_name}.yaml') if project_name else path
try:
with open(DATA_PATH, encoding='utf-8') as temp:
datas = yaml.safe_load(temp)
data = datas.get(module_name, None)
return data if data else datas
... | 固定参数 | Constants | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Constants:
"""固定参数"""
def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR):
"""加载配置文件"""
<|body_0|>
def driver(self, broswer, runenv=None):
"""获取浏览器驱动"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
DATA_PATH = os.path.joi... | stack_v2_sparse_classes_75kplus_train_000309 | 2,257 | no_license | [
{
"docstring": "加载配置文件",
"name": "load_yaml",
"signature": "def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR)"
},
{
"docstring": "获取浏览器驱动",
"name": "driver",
"signature": "def driver(self, broswer, runenv=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042742 | Implement the Python class `Constants` described below.
Class description:
固定参数
Method signatures and docstrings:
- def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR): 加载配置文件
- def driver(self, broswer, runenv=None): 获取浏览器驱动 | Implement the Python class `Constants` described below.
Class description:
固定参数
Method signatures and docstrings:
- def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR): 加载配置文件
- def driver(self, broswer, runenv=None): 获取浏览器驱动
<|skeleton|>
class Constants:
"""固定参数"""
def load_yaml(sel... | 70eaa3872b56374709cda890df0438b8dcd8ee13 | <|skeleton|>
class Constants:
"""固定参数"""
def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR):
"""加载配置文件"""
<|body_0|>
def driver(self, broswer, runenv=None):
"""获取浏览器驱动"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Constants:
"""固定参数"""
def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR):
"""加载配置文件"""
DATA_PATH = os.path.join(path, f'{project_name}.yaml') if project_name else path
try:
with open(DATA_PATH, encoding='utf-8') as temp:
datas =... | the_stack_v2_python_sparse | WebFrameWork/BasePage/Constant.py | Mozziy/UIAutoFrameWork | train | 0 |
8a957a0179a6f3d2d6fdfad9685781dc245fb966 | [
"if self._instance is None:\n raise SpotifyError('Spotify client not created. Call SpotifyClient.init(client_id, client_secret, user_auth, cache_path, no_cache, open_browser) first.')\nreturn self._instance",
"if isinstance(self._instance, self):\n raise SpotifyError('A spotify client has already been initi... | <|body_start_0|>
if self._instance is None:
raise SpotifyError('Spotify client not created. Call SpotifyClient.init(client_id, client_secret, user_auth, cache_path, no_cache, open_browser) first.')
return self._instance
<|end_body_0|>
<|body_start_1|>
if isinstance(self._instance, s... | Singleton metaclass for SpotifyClient. Ensures that SpotifyClient is not instantiated without prior initialization. Every other instantiation of SpotifyClient will return the same instance. | Singleton | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Singleton:
"""Singleton metaclass for SpotifyClient. Ensures that SpotifyClient is not instantiated without prior initialization. Every other instantiation of SpotifyClient will return the same instance."""
def __call__(self):
"""Call method for Singleton metaclass. ### Returns - The... | stack_v2_sparse_classes_75kplus_train_000310 | 5,127 | permissive | [
{
"docstring": "Call method for Singleton metaclass. ### Returns - The instance of the SpotifyClient.",
"name": "__call__",
"signature": "def __call__(self)"
},
{
"docstring": "Initializes the SpotifyClient. ### Arguments - client_id: The client ID of the application. - client_secret: The client... | 2 | stack_v2_sparse_classes_30k_train_027127 | Implement the Python class `Singleton` described below.
Class description:
Singleton metaclass for SpotifyClient. Ensures that SpotifyClient is not instantiated without prior initialization. Every other instantiation of SpotifyClient will return the same instance.
Method signatures and docstrings:
- def __call__(self... | Implement the Python class `Singleton` described below.
Class description:
Singleton metaclass for SpotifyClient. Ensures that SpotifyClient is not instantiated without prior initialization. Every other instantiation of SpotifyClient will return the same instance.
Method signatures and docstrings:
- def __call__(self... | 44692213ab45b2fa80299d5c6048dabe0bfad402 | <|skeleton|>
class Singleton:
"""Singleton metaclass for SpotifyClient. Ensures that SpotifyClient is not instantiated without prior initialization. Every other instantiation of SpotifyClient will return the same instance."""
def __call__(self):
"""Call method for Singleton metaclass. ### Returns - The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Singleton:
"""Singleton metaclass for SpotifyClient. Ensures that SpotifyClient is not instantiated without prior initialization. Every other instantiation of SpotifyClient will return the same instance."""
def __call__(self):
"""Call method for Singleton metaclass. ### Returns - The instance of ... | the_stack_v2_python_sparse | spotdl/utils/spotify.py | savasaurusrexx/spotify-downloader | train | 0 |
d025e3e3aa2d1e2b8199363c88632f70d4731c80 | [
"self._hass = hass\nself._base_url = f'https://openapi.tuya{region_code}.com'\nself._client_id = client_id\nself._secret = secret\nself._user_id = user_id\nself._access_token = ''\nself.device_list = {}",
"payload = self._client_id + self._access_token + timestamp\npayload += method + '\\n'\npayload += hashlib.sh... | <|body_start_0|>
self._hass = hass
self._base_url = f'https://openapi.tuya{region_code}.com'
self._client_id = client_id
self._secret = secret
self._user_id = user_id
self._access_token = ''
self.device_list = {}
<|end_body_0|>
<|body_start_1|>
payload = ... | Class to send API calls. | TuyaCloudApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TuyaCloudApi:
"""Class to send API calls."""
def __init__(self, hass, region_code, client_id, secret, user_id):
"""Initialize the class."""
<|body_0|>
def generate_payload(self, method, timestamp, url, headers, body=None):
"""Generate signed payload for requests.... | stack_v2_sparse_classes_75kplus_train_000311 | 4,359 | permissive | [
{
"docstring": "Initialize the class.",
"name": "__init__",
"signature": "def __init__(self, hass, region_code, client_id, secret, user_id)"
},
{
"docstring": "Generate signed payload for requests.",
"name": "generate_payload",
"signature": "def generate_payload(self, method, timestamp, ... | 5 | stack_v2_sparse_classes_30k_test_002056 | Implement the Python class `TuyaCloudApi` described below.
Class description:
Class to send API calls.
Method signatures and docstrings:
- def __init__(self, hass, region_code, client_id, secret, user_id): Initialize the class.
- def generate_payload(self, method, timestamp, url, headers, body=None): Generate signed ... | Implement the Python class `TuyaCloudApi` described below.
Class description:
Class to send API calls.
Method signatures and docstrings:
- def __init__(self, hass, region_code, client_id, secret, user_id): Initialize the class.
- def generate_payload(self, method, timestamp, url, headers, body=None): Generate signed ... | 796afdf7552c7798fc6a2a238537a36fa1073efe | <|skeleton|>
class TuyaCloudApi:
"""Class to send API calls."""
def __init__(self, hass, region_code, client_id, secret, user_id):
"""Initialize the class."""
<|body_0|>
def generate_payload(self, method, timestamp, url, headers, body=None):
"""Generate signed payload for requests.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TuyaCloudApi:
"""Class to send API calls."""
def __init__(self, hass, region_code, client_id, secret, user_id):
"""Initialize the class."""
self._hass = hass
self._base_url = f'https://openapi.tuya{region_code}.com'
self._client_id = client_id
self._secret = secret... | the_stack_v2_python_sparse | home-assistant/custom_components/localtuya/cloud_api.py | macbury/SmartHouse | train | 166 |
156febbc5a6b3493713a4af2045458929936bf0d | [
"self.klej_type = klej_type\nself.validation_size = validation_size\nself.random_state = random_state\nsuper().__init__(tokenizer, possible_labels)",
"klej_in = read_klej(self.klej_type, self._possible_labels)\ntrain_data, test_data = (klej_in['train'], klej_in['dev'])\ntrain_data, val_data = train_test_split(tra... | <|body_start_0|>
self.klej_type = klej_type
self.validation_size = validation_size
self.random_state = random_state
super().__init__(tokenizer, possible_labels)
<|end_body_0|>
<|body_start_1|>
klej_in = read_klej(self.klej_type, self._possible_labels)
train_data, test_da... | KlejDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KlejDataset:
def __init__(self, tokenizer: PreTrainedTokenizer, klej_type: KlejType, possible_labels: Tuple[str, ...]=DEFAULT_POSSIBLE_LABELS, validation_size: float=0.1, random_state: int=42):
""":param tokenizer: Transformers tokenizer. :param klej_type: One of KlejType values. :param ... | stack_v2_sparse_classes_75kplus_train_000312 | 8,417 | no_license | [
{
"docstring": ":param tokenizer: Transformers tokenizer. :param klej_type: One of KlejType values. :param possible_labels: Tuple of klej type labels that will be used for the training / eval. :param validation_size: A part of training dataset that will be used as validation set. :param random_state: random sta... | 2 | null | Implement the Python class `KlejDataset` described below.
Class description:
Implement the KlejDataset class.
Method signatures and docstrings:
- def __init__(self, tokenizer: PreTrainedTokenizer, klej_type: KlejType, possible_labels: Tuple[str, ...]=DEFAULT_POSSIBLE_LABELS, validation_size: float=0.1, random_state: ... | Implement the Python class `KlejDataset` described below.
Class description:
Implement the KlejDataset class.
Method signatures and docstrings:
- def __init__(self, tokenizer: PreTrainedTokenizer, klej_type: KlejType, possible_labels: Tuple[str, ...]=DEFAULT_POSSIBLE_LABELS, validation_size: float=0.1, random_state: ... | 5f5d1688a75e2815fb6363a8cd5986c5d4871775 | <|skeleton|>
class KlejDataset:
def __init__(self, tokenizer: PreTrainedTokenizer, klej_type: KlejType, possible_labels: Tuple[str, ...]=DEFAULT_POSSIBLE_LABELS, validation_size: float=0.1, random_state: int=42):
""":param tokenizer: Transformers tokenizer. :param klej_type: One of KlejType values. :param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KlejDataset:
def __init__(self, tokenizer: PreTrainedTokenizer, klej_type: KlejType, possible_labels: Tuple[str, ...]=DEFAULT_POSSIBLE_LABELS, validation_size: float=0.1, random_state: int=42):
""":param tokenizer: Transformers tokenizer. :param klej_type: One of KlejType values. :param possible_label... | the_stack_v2_python_sparse | src/models/datasets.py | 2021L-ZZSN/2-Ostoja-Lniski-Brzozowski | train | 0 | |
d92f46d1023c2b91e32cbe82ab07c61bfb614667 | [
"print('Making autoaligner from reference %s' % reference)\nfrom riglib.stereo_opengl import xfm\nself._quat = xfm.Quaternion\nself.ref = np.load(reference)['reference']\nself.xfm = xfm.Quaternion()\nself.off1 = np.array([0, 0, 0])\nself.off2 = np.array([0, 0, 0])",
"mdata = data.mean(0)[:, :3]\navail = (data[:, ... | <|body_start_0|>
print('Making autoaligner from reference %s' % reference)
from riglib.stereo_opengl import xfm
self._quat = xfm.Quaternion
self.ref = np.load(reference)['reference']
self.xfm = xfm.Quaternion()
self.off1 = np.array([0, 0, 0])
self.off2 = np.array(... | Runs the autoalignment filter to center everything into the chair coordinates | AutoAlign | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoAlign:
"""Runs the autoalignment filter to center everything into the chair coordinates"""
def __init__(self, reference):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def __call__(self, data):
"""Docstring Parameters ---------- Returns ---... | stack_v2_sparse_classes_75kplus_train_000313 | 6,997 | permissive | [
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "__init__",
"signature": "def __init__(self, reference)"
},
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "__call__",
"signature": "def __call__(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028065 | Implement the Python class `AutoAlign` described below.
Class description:
Runs the autoalignment filter to center everything into the chair coordinates
Method signatures and docstrings:
- def __init__(self, reference): Docstring Parameters ---------- Returns -------
- def __call__(self, data): Docstring Parameters -... | Implement the Python class `AutoAlign` described below.
Class description:
Runs the autoalignment filter to center everything into the chair coordinates
Method signatures and docstrings:
- def __init__(self, reference): Docstring Parameters ---------- Returns -------
- def __call__(self, data): Docstring Parameters -... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class AutoAlign:
"""Runs the autoalignment filter to center everything into the chair coordinates"""
def __init__(self, reference):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def __call__(self, data):
"""Docstring Parameters ---------- Returns ---... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoAlign:
"""Runs the autoalignment filter to center everything into the chair coordinates"""
def __init__(self, reference):
"""Docstring Parameters ---------- Returns -------"""
print('Making autoaligner from reference %s' % reference)
from riglib.stereo_opengl import xfm
... | the_stack_v2_python_sparse | riglib/calibrations.py | carmenalab/brain-python-interface | train | 9 |
34d35f0c80c9909be9550bcd9aebd32189f9a9ba | [
"def encode(node):\n if node:\n vals.append(str(node.val))\n encode(node.left)\n encode(node.right)\n else:\n vals.append('#')\nvals = []\nencode(root)\nreturn ' '.join(vals)",
"def decode():\n val = next(vals)\n if val == '#':\n return None\n node = TreeNode(int(... | <|body_start_0|>
def encode(node):
if node:
vals.append(str(node.val))
encode(node.left)
encode(node.right)
else:
vals.append('#')
vals = []
encode(root)
return ' '.join(vals)
<|end_body_0|>
<|body_s... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_000314 | 9,842 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_025487 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def encode(node):
if node:
vals.append(str(node.val))
encode(node.left)
encode(node.right)
else:
v... | the_stack_v2_python_sparse | cs15211/SerializeandDeserializeBinaryTree.py | JulyKikuAkita/PythonPrac | train | 1 | |
69a33f32a3bb2a0a631309beb1935daf471d148f | [
"if data_dir is None:\n data_dir = ''\nif self.train_file is None and filename is None:\n raise ValueError('Must specify either train_filename or filename.')\ninput_file = os.path.join(data_dir, self.train_file if filename is None else filename)\nreturn utils_mewslix.load_jsonl(input_file, utils_mewslix.Menti... | <|body_start_0|>
if data_dir is None:
data_dir = ''
if self.train_file is None and filename is None:
raise ValueError('Must specify either train_filename or filename.')
input_file = os.path.join(data_dir, self.train_file if filename is None else filename)
return u... | Processor for the Wikipedia portion of Mewsli-X entity linking task. | WikiELProcessor | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiELProcessor:
"""Processor for the Wikipedia portion of Mewsli-X entity linking task."""
def get_train_examples(self, data_dir, filename=None):
"""Returns the training examples from the data directory. Args: data_dir: Directory containing the data files used for training and evalu... | stack_v2_sparse_classes_75kplus_train_000315 | 7,929 | permissive | [
{
"docstring": "Returns the training examples from the data directory. Args: data_dir: Directory containing the data files used for training and evaluating. filename: None by default, specify this if the training file has a different name than the original one defined by this class.",
"name": "get_train_exa... | 2 | stack_v2_sparse_classes_30k_train_001242 | Implement the Python class `WikiELProcessor` described below.
Class description:
Processor for the Wikipedia portion of Mewsli-X entity linking task.
Method signatures and docstrings:
- def get_train_examples(self, data_dir, filename=None): Returns the training examples from the data directory. Args: data_dir: Direct... | Implement the Python class `WikiELProcessor` described below.
Class description:
Processor for the Wikipedia portion of Mewsli-X entity linking task.
Method signatures and docstrings:
- def get_train_examples(self, data_dir, filename=None): Returns the training examples from the data directory. Args: data_dir: Direct... | 838c13b69daafb9328785d16caae2711e4012123 | <|skeleton|>
class WikiELProcessor:
"""Processor for the Wikipedia portion of Mewsli-X entity linking task."""
def get_train_examples(self, data_dir, filename=None):
"""Returns the training examples from the data directory. Args: data_dir: Directory containing the data files used for training and evalu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WikiELProcessor:
"""Processor for the Wikipedia portion of Mewsli-X entity linking task."""
def get_train_examples(self, data_dir, filename=None):
"""Returns the training examples from the data directory. Args: data_dir: Directory containing the data files used for training and evaluating. filena... | the_stack_v2_python_sparse | third_party/processors/mewslix.py | google-research/xtreme | train | 615 |
e9dd5414c79fe2c1af226754edf527487c9469c7 | [
"context = super().get_context_data(*args, **kwargs)\nif self.root:\n category = '{}_root'.format(settings.SITE_ID)\nelse:\n category = context['category']\ncontext['flat_page'] = get_object_or_404(FlatPageModel, category=category, url=context['page'])\nreturn context",
"context = self.get_context_data(**kw... | <|body_start_0|>
context = super().get_context_data(*args, **kwargs)
if self.root:
category = '{}_root'.format(settings.SITE_ID)
else:
category = context['category']
context['flat_page'] = get_object_or_404(FlatPageModel, category=category, url=context['page'])
... | View for all root and non-root flat pages. | FlatPage | [
"MIT",
"CC-BY-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlatPage:
"""View for all root and non-root flat pages."""
def get_context_data(self, *args, **kwargs):
"""Customized method: Adds flat page instance to the context and sends HTTP 404 if page does not exist."""
<|body_0|>
def get(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_000316 | 5,093 | permissive | [
{
"docstring": "Customized method: Adds flat page instance to the context and sends HTTP 404 if page does not exist.",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
},
{
"docstring": "Overridden method. Returns HTTP 301 if flat page is only for redirect."... | 2 | stack_v2_sparse_classes_30k_train_011051 | Implement the Python class `FlatPage` described below.
Class description:
View for all root and non-root flat pages.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Customized method: Adds flat page instance to the context and sends HTTP 404 if page does not exist.
- def get(self, req... | Implement the Python class `FlatPage` described below.
Class description:
View for all root and non-root flat pages.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Customized method: Adds flat page instance to the context and sends HTTP 404 if page does not exist.
- def get(self, req... | 1db622a9fb0eb883ef90c8436def3ec419590c5a | <|skeleton|>
class FlatPage:
"""View for all root and non-root flat pages."""
def get_context_data(self, *args, **kwargs):
"""Customized method: Adds flat page instance to the context and sends HTTP 404 if page does not exist."""
<|body_0|>
def get(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlatPage:
"""View for all root and non-root flat pages."""
def get_context_data(self, *args, **kwargs):
"""Customized method: Adds flat page instance to the context and sends HTTP 404 if page does not exist."""
context = super().get_context_data(*args, **kwargs)
if self.root:
... | the_stack_v2_python_sparse | dreifaltigkeit/views.py | normanjaeckel/Dreifaltigkeit2 | train | 0 |
29fb92fea72b57ffec209da8be14747c69eede46 | [
"self.hhsearch_pdb70_runner = HHSearch(binary_path=hhsearch_binary_path, databases=[pdb70_database_path])\nself.template_featurizer = template_featurizer\nself.result_path = result_path\nself.use_env = use_env",
"with open(input_fasta_path) as f:\n input_fasta_str = f.read()\ninput_seqs, input_descs = parse_fa... | <|body_start_0|>
self.hhsearch_pdb70_runner = HHSearch(binary_path=hhsearch_binary_path, databases=[pdb70_database_path])
self.template_featurizer = template_featurizer
self.result_path = result_path
self.use_env = use_env
<|end_body_0|>
<|body_start_1|>
with open(input_fasta_pa... | Runs the alignment tools and assembles the input features. | DataPipeline | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataPipeline:
"""Runs the alignment tools and assembles the input features."""
def __init__(self, hhsearch_binary_path: str, pdb70_database_path: str, template_featurizer: TemplateHitFeaturizer, result_path, use_env=False):
"""Constructs a feature dict for a given FASTA file."""
... | stack_v2_sparse_classes_75kplus_train_000317 | 8,009 | permissive | [
{
"docstring": "Constructs a feature dict for a given FASTA file.",
"name": "__init__",
"signature": "def __init__(self, hhsearch_binary_path: str, pdb70_database_path: str, template_featurizer: TemplateHitFeaturizer, result_path, use_env=False)"
},
{
"docstring": "Runs alignment tools on the in... | 2 | stack_v2_sparse_classes_30k_train_028378 | Implement the Python class `DataPipeline` described below.
Class description:
Runs the alignment tools and assembles the input features.
Method signatures and docstrings:
- def __init__(self, hhsearch_binary_path: str, pdb70_database_path: str, template_featurizer: TemplateHitFeaturizer, result_path, use_env=False): ... | Implement the Python class `DataPipeline` described below.
Class description:
Runs the alignment tools and assembles the input features.
Method signatures and docstrings:
- def __init__(self, hhsearch_binary_path: str, pdb70_database_path: str, template_featurizer: TemplateHitFeaturizer, result_path, use_env=False): ... | c72ce898482419117550ad16d93b38298f4306a1 | <|skeleton|>
class DataPipeline:
"""Runs the alignment tools and assembles the input features."""
def __init__(self, hhsearch_binary_path: str, pdb70_database_path: str, template_featurizer: TemplateHitFeaturizer, result_path, use_env=False):
"""Constructs a feature dict for a given FASTA file."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataPipeline:
"""Runs the alignment tools and assembles the input features."""
def __init__(self, hhsearch_binary_path: str, pdb70_database_path: str, template_featurizer: TemplateHitFeaturizer, result_path, use_env=False):
"""Constructs a feature dict for a given FASTA file."""
self.hhse... | the_stack_v2_python_sparse | reproduce/AlphaFold2-Chinese/data/tools/data_process.py | mindspore-ai/community | train | 193 |
05250288d534bf7dd82b7478cddbf836e36b767f | [
"if samples is None or lines is None:\n msg = 'Samples and lines are required inputs! Samples: {ns} Lines: {nl}'.format(ns=samples, nl=lines)\n raise TypeError(msg)\ndriver = gdal.GetDriverByName(fmt)\nself.outds = driver.Create(out_fname, samples, lines, bands, dtype)\nself.nodata = nodata\nself.geobox = geo... | <|body_start_0|>
if samples is None or lines is None:
msg = 'Samples and lines are required inputs! Samples: {ns} Lines: {nl}'.format(ns=samples, nl=lines)
raise TypeError(msg)
driver = gdal.GetDriverByName(fmt)
self.outds = driver.Create(out_fname, samples, lines, bands,... | TiledOutput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TiledOutput:
def __init__(self, out_fname, samples=None, lines=None, bands=1, geobox=None, fmt='ENVI', nodata=None, dtype=gdal.GDT_Byte):
"""A class to aid in data processing using a tiling scheme. The `TiledOutput` class takes care of writing each tile/chunk of data to disk. :param out_... | stack_v2_sparse_classes_75kplus_train_000318 | 10,754 | permissive | [
{
"docstring": "A class to aid in data processing using a tiling scheme. The `TiledOutput` class takes care of writing each tile/chunk of data to disk. :param out_fname: A string containing the full filepath name used for creating the image on disk. :param samples: An integer indicating the number of samples/co... | 6 | stack_v2_sparse_classes_30k_train_033055 | Implement the Python class `TiledOutput` described below.
Class description:
Implement the TiledOutput class.
Method signatures and docstrings:
- def __init__(self, out_fname, samples=None, lines=None, bands=1, geobox=None, fmt='ENVI', nodata=None, dtype=gdal.GDT_Byte): A class to aid in data processing using a tilin... | Implement the Python class `TiledOutput` described below.
Class description:
Implement the TiledOutput class.
Method signatures and docstrings:
- def __init__(self, out_fname, samples=None, lines=None, bands=1, geobox=None, fmt='ENVI', nodata=None, dtype=gdal.GDT_Byte): A class to aid in data processing using a tilin... | 4ae3670681b872530f59c57ab537a45d1b09c009 | <|skeleton|>
class TiledOutput:
def __init__(self, out_fname, samples=None, lines=None, bands=1, geobox=None, fmt='ENVI', nodata=None, dtype=gdal.GDT_Byte):
"""A class to aid in data processing using a tiling scheme. The `TiledOutput` class takes care of writing each tile/chunk of data to disk. :param out_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TiledOutput:
def __init__(self, out_fname, samples=None, lines=None, bands=1, geobox=None, fmt='ENVI', nodata=None, dtype=gdal.GDT_Byte):
"""A class to aid in data processing using a tiling scheme. The `TiledOutput` class takes care of writing each tile/chunk of data to disk. :param out_fname: A strin... | the_stack_v2_python_sparse | wagl/tiling.py | GeoscienceAustralia/wagl | train | 25 | |
c360dac1acdd63fd48f7468ea07e094b8f01bdb5 | [
"self.obj_ids = []\nself.threshold = threshold\nself.client = None",
"self.obj_ids.append(pointer.id_at_location)\nnr_objs_client = len(self.obj_ids)\nif nr_objs_client >= self.threshold:\n msg = GarbageCollectBatchedAction(ids_at_location=self.obj_ids, address=pointer.client.address)\n pointer.client.send_... | <|body_start_0|>
self.obj_ids = []
self.threshold = threshold
self.client = None
<|end_body_0|>
<|body_start_1|>
self.obj_ids.append(pointer.id_at_location)
nr_objs_client = len(self.obj_ids)
if nr_objs_client >= self.threshold:
msg = GarbageCollectBatchedAct... | The GCBatched Strategy. | GCBatched | [
"Python-2.0",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCBatched:
"""The GCBatched Strategy."""
def __init__(self, threshold: int=10) -> None:
"""Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_000319 | 2,439 | permissive | [
{
"docstring": "Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None",
"name": "__init__",
"signature": "def __init__(self, threshold: int=10) -> None"
},
{
"docstring": "Check if we pas... | 3 | stack_v2_sparse_classes_30k_train_019729 | Implement the Python class `GCBatched` described below.
Class description:
The GCBatched Strategy.
Method signatures and docstrings:
- def __init__(self, threshold: int=10) -> None: Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects tha... | Implement the Python class `GCBatched` described below.
Class description:
The GCBatched Strategy.
Method signatures and docstrings:
- def __init__(self, threshold: int=10) -> None: Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects tha... | 6477f64b63dc285059c3766deab3993653cead2e | <|skeleton|>
class GCBatched:
"""The GCBatched Strategy."""
def __init__(self, threshold: int=10) -> None:
"""Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GCBatched:
"""The GCBatched Strategy."""
def __init__(self, threshold: int=10) -> None:
"""Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None"""
self.obj_ids = []
self.t... | the_stack_v2_python_sparse | packages/syft/src/syft/core/pointer/garbage_collection/gc_batched.py | Metrix1010/PySyft | train | 2 |
5788fd7eb470bb7cb88c71a92c87591929c8a81a | [
"res = []\n\ndef preorder(root):\n if not root:\n return\n res.append(str(root.val))\n for child in root.children:\n preorder(child)\n res.append('#')\npreorder(root)\nreturn ' '.join(res)",
"arr = collections.deque(data.split())\nif not arr:\n return None\n\ndef dfs(arr):\n val = ... | <|body_start_0|>
res = []
def preorder(root):
if not root:
return
res.append(str(root.val))
for child in root.children:
preorder(child)
res.append('#')
preorder(root)
return ' '.join(res)
<|end_body_0|>
<|b... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_000320 | 2,843 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | stack_v2_sparse_classes_30k_train_047029 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 188befbfb7080ba1053ee1f7187b177b64cf42d2 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
def preorder(root):
if not root:
return
res.append(str(root.val))
for child in root.children:
preorder(c... | the_stack_v2_python_sparse | 0428. Serialize and Deserialize N-ary Tree.py | pwang867/LeetCode-Solutions-Python | train | 0 | |
1968a46a67377fed112b685c22fb731f81742e33 | [
"base_url = 'https://github.com/IATI/IATI-Guidance/commits/main/en/'\nfile_path = '/'.join(self.ssot_path.split('/')[1:]) + '.rst'\nreturn base_url + file_path",
"related = []\nsoup = BeautifulSoup(self.data, 'html.parser')\nanchors = soup.findAll('a')\nfor anchor in anchors:\n anchor_href = anchor['href']\n ... | <|body_start_0|>
base_url = 'https://github.com/IATI/IATI-Guidance/commits/main/en/'
file_path = '/'.join(self.ssot_path.split('/')[1:]) + '.rst'
return base_url + file_path
<|end_body_0|>
<|body_start_1|>
related = []
soup = BeautifulSoup(self.data, 'html.parser')
ancho... | A model for the Standard Guidance Page, an IATI reference page. | StandardGuidancePage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardGuidancePage:
"""A model for the Standard Guidance Page, an IATI reference page."""
def github_url(self):
"""Calculate a Github changelog url."""
<|body_0|>
def related_guidance(self):
"""Extract related_guidance."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_000321 | 14,810 | permissive | [
{
"docstring": "Calculate a Github changelog url.",
"name": "github_url",
"signature": "def github_url(self)"
},
{
"docstring": "Extract related_guidance.",
"name": "related_guidance",
"signature": "def related_guidance(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001544 | Implement the Python class `StandardGuidancePage` described below.
Class description:
A model for the Standard Guidance Page, an IATI reference page.
Method signatures and docstrings:
- def github_url(self): Calculate a Github changelog url.
- def related_guidance(self): Extract related_guidance. | Implement the Python class `StandardGuidancePage` described below.
Class description:
A model for the Standard Guidance Page, an IATI reference page.
Method signatures and docstrings:
- def github_url(self): Calculate a Github changelog url.
- def related_guidance(self): Extract related_guidance.
<|skeleton|>
class ... | 4cf7be72b6b3d0c46dcadcc9d9904b471215ea81 | <|skeleton|>
class StandardGuidancePage:
"""A model for the Standard Guidance Page, an IATI reference page."""
def github_url(self):
"""Calculate a Github changelog url."""
<|body_0|>
def related_guidance(self):
"""Extract related_guidance."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StandardGuidancePage:
"""A model for the Standard Guidance Page, an IATI reference page."""
def github_url(self):
"""Calculate a Github changelog url."""
base_url = 'https://github.com/IATI/IATI-Guidance/commits/main/en/'
file_path = '/'.join(self.ssot_path.split('/')[1:]) + '.rst... | the_stack_v2_python_sparse | iati_standard/models.py | IATI/IATI-Standard-Website | train | 4 |
2ee6934ca62df61de3e7037d1919c699f8793af3 | [
"super(RNNLM, self).__init__()\nwith self.init_scope():\n self.embed = DL.EmbedID(n_vocab, n_units)\n self.rnn = chainer.ChainList(*[L.StatelessLSTM(n_units, n_units) for _ in range(n_layers)]) if typ == 'lstm' else chainer.ChainList(*[L.StatelessGRU(n_units, n_units) for _ in range(n_layers)])\n self.lo =... | <|body_start_0|>
super(RNNLM, self).__init__()
with self.init_scope():
self.embed = DL.EmbedID(n_vocab, n_units)
self.rnn = chainer.ChainList(*[L.StatelessLSTM(n_units, n_units) for _ in range(n_layers)]) if typ == 'lstm' else chainer.ChainList(*[L.StatelessGRU(n_units, n_units) ... | A chainer RNNLM. | RNNLM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNLM:
"""A chainer RNNLM."""
def __init__(self, n_vocab, n_layers, n_units, typ='lstm', dropout_rate=0.5):
"""Initialize class. :param int n_vocab: The size of the vocabulary :param int n_layers: The number of layers to create :param int n_units: The number of units per layer :param... | stack_v2_sparse_classes_75kplus_train_000322 | 11,092 | no_license | [
{
"docstring": "Initialize class. :param int n_vocab: The size of the vocabulary :param int n_layers: The number of layers to create :param int n_units: The number of units per layer :param str typ: The RNN type",
"name": "__init__",
"signature": "def __init__(self, n_vocab, n_layers, n_units, typ='lstm... | 2 | stack_v2_sparse_classes_30k_val_000326 | Implement the Python class `RNNLM` described below.
Class description:
A chainer RNNLM.
Method signatures and docstrings:
- def __init__(self, n_vocab, n_layers, n_units, typ='lstm', dropout_rate=0.5): Initialize class. :param int n_vocab: The size of the vocabulary :param int n_layers: The number of layers to create... | Implement the Python class `RNNLM` described below.
Class description:
A chainer RNNLM.
Method signatures and docstrings:
- def __init__(self, n_vocab, n_layers, n_units, typ='lstm', dropout_rate=0.5): Initialize class. :param int n_vocab: The size of the vocabulary :param int n_layers: The number of layers to create... | 433fd1e8339bf00f66c397d4aad0b0d59e9e93aa | <|skeleton|>
class RNNLM:
"""A chainer RNNLM."""
def __init__(self, n_vocab, n_layers, n_units, typ='lstm', dropout_rate=0.5):
"""Initialize class. :param int n_vocab: The size of the vocabulary :param int n_layers: The number of layers to create :param int n_units: The number of units per layer :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNLM:
"""A chainer RNNLM."""
def __init__(self, n_vocab, n_layers, n_units, typ='lstm', dropout_rate=0.5):
"""Initialize class. :param int n_vocab: The size of the vocabulary :param int n_layers: The number of layers to create :param int n_units: The number of units per layer :param str typ: The... | the_stack_v2_python_sparse | unsupervised/espnet/nets/chainer_backend/lm/default.py | pfnet-research/unsupervised_segmental_empirical_ODM | train | 2 |
d156937663b12c26df506b5478f43845b6c1ddd2 | [
"if self.raw_content is not None and self.normalized_content is None:\n return False\nreturn self.has_usual_file_name_extension",
"try:\n data = json.loads(self.raw_content.decode())\n return normalize_data(data)\nexcept (TypeError, ValueError):\n return None"
] | <|body_start_0|>
if self.raw_content is not None and self.normalized_content is None:
return False
return self.has_usual_file_name_extension
<|end_body_0|>
<|body_start_1|>
try:
data = json.loads(self.raw_content.decode())
return normalize_data(data)
... | A JSON file. | JsonFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonFile:
"""A JSON file."""
def matches_file_type(self) -> bool:
"""Whether the current instance is a static file of this type."""
<|body_0|>
def normalized_content(self) -> Union[bytes, None]:
"""The content of this static file normalized for this file type."""... | stack_v2_sparse_classes_75kplus_train_000323 | 927 | permissive | [
{
"docstring": "Whether the current instance is a static file of this type.",
"name": "matches_file_type",
"signature": "def matches_file_type(self) -> bool"
},
{
"docstring": "The content of this static file normalized for this file type.",
"name": "normalized_content",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_041954 | Implement the Python class `JsonFile` described below.
Class description:
A JSON file.
Method signatures and docstrings:
- def matches_file_type(self) -> bool: Whether the current instance is a static file of this type.
- def normalized_content(self) -> Union[bytes, None]: The content of this static file normalized f... | Implement the Python class `JsonFile` described below.
Class description:
A JSON file.
Method signatures and docstrings:
- def matches_file_type(self) -> bool: Whether the current instance is a static file of this type.
- def normalized_content(self) -> Union[bytes, None]: The content of this static file normalized f... | d53433de80a10c02ca1a71c0fa47d371739a4859 | <|skeleton|>
class JsonFile:
"""A JSON file."""
def matches_file_type(self) -> bool:
"""Whether the current instance is a static file of this type."""
<|body_0|>
def normalized_content(self) -> Union[bytes, None]:
"""The content of this static file normalized for this file type."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonFile:
"""A JSON file."""
def matches_file_type(self) -> bool:
"""Whether the current instance is a static file of this type."""
if self.raw_content is not None and self.normalized_content is None:
return False
return self.has_usual_file_name_extension
def norm... | the_stack_v2_python_sparse | files/json_file.py | wichmannpas/VersionInferrer | train | 5 |
ae2791bab378134a037d6b6ce64ebcb0d59f39fe | [
"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. | NodeServiceServicer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SendHeartbeat(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_75kplus_train_000324 | 8,700 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Register",
"signature": "def Register(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "SendHeartbeat",
"signature": "def SendHeartbeat(self, ... | 5 | stack_v2_sparse_classes_30k_train_033387 | Implement the Python class `NodeServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Register(self, request, context): Missing associated documentation comment in .proto file.
- def SendHeartbeat(self, request, context): ... | Implement the Python class `NodeServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Register(self, request, context): Missing associated documentation comment in .proto file.
- def SendHeartbeat(self, request, context): ... | 2efb7e0c6830b341274d5b7d337dd1ad07b452ae | <|skeleton|>
class NodeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SendHeartbeat(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | _ext/python/crawlab/grpc/services/node_service_pb2_grpc.py | crawlab-team/crawlab-sdk | train | 44 |
13f1dae172e74011ee8b8753226b2054ee328631 | [
"assert isinstance(decoding, Decoding), 'Invalid decoding %s' % decoding\nif not decoding.validations:\n return\nlength, validations = (None, [])\nfor validation in decoding.validations:\n if isinstance(validation, MaxLen):\n assert isinstance(validation, MaxLen)\n if length is None:\n ... | <|body_start_0|>
assert isinstance(decoding, Decoding), 'Invalid decoding %s' % decoding
if not decoding.validations:
return
length, validations = (None, [])
for validation in decoding.validations:
if isinstance(validation, MaxLen):
assert isinstan... | Implementation for a handler that provides the maximum length validation. | ValidateMaxLen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidateMaxLen:
"""Implementation for a handler that provides the maximum length validation."""
def process(self, chain, decoding: Decoding, **keyargs):
"""@see: HandlerProcessor.process Process the maximum length validation."""
<|body_0|>
def createSet(self, wrapped, pr... | stack_v2_sparse_classes_75kplus_train_000325 | 2,796 | no_license | [
{
"docstring": "@see: HandlerProcessor.process Process the maximum length validation.",
"name": "process",
"signature": "def process(self, chain, decoding: Decoding, **keyargs)"
},
{
"docstring": "Create the do set to use with validation.",
"name": "createSet",
"signature": "def createSe... | 2 | null | Implement the Python class `ValidateMaxLen` described below.
Class description:
Implementation for a handler that provides the maximum length validation.
Method signatures and docstrings:
- def process(self, chain, decoding: Decoding, **keyargs): @see: HandlerProcessor.process Process the maximum length validation.
-... | Implement the Python class `ValidateMaxLen` described below.
Class description:
Implementation for a handler that provides the maximum length validation.
Method signatures and docstrings:
- def process(self, chain, decoding: Decoding, **keyargs): @see: HandlerProcessor.process Process the maximum length validation.
-... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class ValidateMaxLen:
"""Implementation for a handler that provides the maximum length validation."""
def process(self, chain, decoding: Decoding, **keyargs):
"""@see: HandlerProcessor.process Process the maximum length validation."""
<|body_0|>
def createSet(self, wrapped, pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidateMaxLen:
"""Implementation for a handler that provides the maximum length validation."""
def process(self, chain, decoding: Decoding, **keyargs):
"""@see: HandlerProcessor.process Process the maximum length validation."""
assert isinstance(decoding, Decoding), 'Invalid decoding %s'... | the_stack_v2_python_sparse | components/ally-core/ally/core/impl/processor/decoder/validation/max_len.py | cristidomsa/Ally-Py | train | 0 |
c1bce218f52678372c242fa2bdade9fdd4d33d68 | [
"n = len(s)\ndp = [[0] * n for _ in range(n)]\nans = ''\nfor i in range(n):\n for j in range(i, -1, -1):\n if s[i] == s[j] and (i - j <= 2 or dp[i - 1][j + 1] == 1):\n dp[i][j] = 1\n ans = max(ans, s[j:i + 1], key=len)\nreturn ans",
"n = len(s)\nres = ''\n\ndef _helper(s, l, r):\n ... | <|body_start_0|>
n = len(s)
dp = [[0] * n for _ in range(n)]
ans = ''
for i in range(n):
for j in range(i, -1, -1):
if s[i] == s[j] and (i - j <= 2 or dp[i - 1][j + 1] == 1):
dp[i][j] = 1
ans = max(ans, s[j:i + 1], key=l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s: str) -> str:
"""动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1"""
<|body_0|>
def longestPalindrome(self, s:... | stack_v2_sparse_classes_75kplus_train_000326 | 2,295 | no_license | [
{
"docstring": "动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1",
"name": "longestPalindrome_1",
"signature": "def longestPalindrome_1(self, s: str) -> str"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_047927 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s: str) -> str: 动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s: str) -> str: 动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i... | 2b7f4a9fefbfd358f8ff31362d60e2007641ca29 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s: str) -> str:
"""动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1"""
<|body_0|>
def longestPalindrome(self, s:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome_1(self, s: str) -> str:
"""动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1"""
n = len(s)
dp = [[0] * n for _ in range(n)]
... | the_stack_v2_python_sparse | Week_08/G20190343020242/LeetCode_5_0242.py | algorithm005-class01/algorithm005-class01 | train | 27 | |
8cf82579b9009fbccb5335b99d74f667b681244d | [
"super(TextSubNet, self).__init__()\nif num_layers == 1:\n dropout = 0.0\nself.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True)\nself.dropout = nn.Dropout(dropout)\nself.linear_1 = nn.Linear(hidden_size, out_size)",
"_, final_states = se... | <|body_start_0|>
super(TextSubNet, self).__init__()
if num_layers == 1:
dropout = 0.0
self.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True)
self.dropout = nn.Dropout(dropout)
self.linear_1 = nn.... | The LSTM-based subnetwork that is used in TFN for text | TextSubNet | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextSubNet:
"""The LSTM-based subnetwork that is used in TFN for text"""
def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):
"""Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers ... | stack_v2_sparse_classes_75kplus_train_000327 | 3,873 | permissive | [
{
"docstring": "Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dropout: dropout probability bidirectional: specify usage of bidirectional LSTM Output: (return value in forward) a tensor of shape (batch_size, out_size)",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_047780 | Implement the Python class `TextSubNet` described below.
Class description:
The LSTM-based subnetwork that is used in TFN for text
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): Args: in_size: input dimension hidden_size: hidden ... | Implement the Python class `TextSubNet` described below.
Class description:
The LSTM-based subnetwork that is used in TFN for text
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): Args: in_size: input dimension hidden_size: hidden ... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class TextSubNet:
"""The LSTM-based subnetwork that is used in TFN for text"""
def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):
"""Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextSubNet:
"""The LSTM-based subnetwork that is used in TFN for text"""
def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):
"""Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dro... | the_stack_v2_python_sparse | PyTorch/contrib/others/MMSA_ID2979_for_PyTorch/models/subNets/FeatureNets.py | Ascend/ModelZoo-PyTorch | train | 23 |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\nself.frequency = frequency\nself.length = length\nself.type = type",
"mother_wavelet = self.type\nspread = np.arange(1, self.length + 1, 1)\nscales = central_frequency(mother_wavelet) * self.frequency / spread\ncoeffs, _ = cwt(signal, scales, mother_wavelet, 1.0 / self.frequency)\ncoeffs = np... | <|body_start_0|>
super().__init__()
self.frequency = frequency
self.length = length
self.type = type
<|end_body_0|>
<|body_start_1|>
mother_wavelet = self.type
spread = np.arange(1, self.length + 1, 1)
scales = central_frequency(mother_wavelet) * self.frequency /... | Generate continuous wavelet transform of a signal | SignalContinuousWavelet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalContinuousWavelet:
"""Generate continuous wavelet transform of a signal"""
def __init__(self, type: str='mexh', length: float=125.0, frequency: float=500.0) -> None:
"""Args: type: mother wavelet type. Available options are: {``"mexh"``, ``"morl"``, ``"cmorB-C"``, , ``"gausP"``... | stack_v2_sparse_classes_75kplus_train_000328 | 16,322 | permissive | [
{
"docstring": "Args: type: mother wavelet type. Available options are: {``\"mexh\"``, ``\"morl\"``, ``\"cmorB-C\"``, , ``\"gausP\"``} see : https://pywavelets.readthedocs.io/en/latest/ref/cwt.html length: expected length, default ``125.0`` frequency: signal frequency, default ``500.0``",
"name": "__init__"... | 2 | stack_v2_sparse_classes_30k_val_000073 | Implement the Python class `SignalContinuousWavelet` described below.
Class description:
Generate continuous wavelet transform of a signal
Method signatures and docstrings:
- def __init__(self, type: str='mexh', length: float=125.0, frequency: float=500.0) -> None: Args: type: mother wavelet type. Available options a... | Implement the Python class `SignalContinuousWavelet` described below.
Class description:
Generate continuous wavelet transform of a signal
Method signatures and docstrings:
- def __init__(self, type: str='mexh', length: float=125.0, frequency: float=500.0) -> None: Args: type: mother wavelet type. Available options a... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalContinuousWavelet:
"""Generate continuous wavelet transform of a signal"""
def __init__(self, type: str='mexh', length: float=125.0, frequency: float=500.0) -> None:
"""Args: type: mother wavelet type. Available options are: {``"mexh"``, ``"morl"``, ``"cmorB-C"``, , ``"gausP"``... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignalContinuousWavelet:
"""Generate continuous wavelet transform of a signal"""
def __init__(self, type: str='mexh', length: float=125.0, frequency: float=500.0) -> None:
"""Args: type: mother wavelet type. Available options are: {``"mexh"``, ``"morl"``, ``"cmorB-C"``, , ``"gausP"``} see : https... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
286caddc8ba113a8be35db66b21ab619292fcbf9 | [
"img_shape = image.shape[:2]\nempty_shape = (img_shape[0], img_shape[1], 3)\ntext_image = np.full(empty_shape, 255, dtype=np.uint8)\nif texts:\n text_image = self.get_labels_image(text_image, labels=texts, bboxes=bboxes, font_families=self.font_families, font_properties=self.font_properties)\nif polygons:\n p... | <|body_start_0|>
img_shape = image.shape[:2]
empty_shape = (img_shape[0], img_shape[1], 3)
text_image = np.full(empty_shape, 255, dtype=np.uint8)
if texts:
text_image = self.get_labels_image(text_image, labels=texts, bboxes=bboxes, font_families=self.font_families, font_prope... | TextSpottingLocalVisualizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextSpottingLocalVisualizer:
def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) -> np.ndarray:
"""Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB... | stack_v2_sparse_classes_75kplus_train_000329 | 6,362 | permissive | [
{
"docstring": "Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB. bboxes (np.ndarray, torch.Tensor): The bboxes to draw. The shape of bboxes should be (N, 4), where N is the number of texts. polygons (Sequence[np.ndarray]): The polygons to draw. The length of... | 2 | stack_v2_sparse_classes_30k_train_018923 | Implement the Python class `TextSpottingLocalVisualizer` described below.
Class description:
Implement the TextSpottingLocalVisualizer class.
Method signatures and docstrings:
- def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) ... | Implement the Python class `TextSpottingLocalVisualizer` described below.
Class description:
Implement the TextSpottingLocalVisualizer class.
Method signatures and docstrings:
- def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) ... | 9551af6e5a2482e72a2af1e3b8597fd54b999d69 | <|skeleton|>
class TextSpottingLocalVisualizer:
def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) -> np.ndarray:
"""Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextSpottingLocalVisualizer:
def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) -> np.ndarray:
"""Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB. bboxes (np.n... | the_stack_v2_python_sparse | mmocr/visualization/textspotting_visualizer.py | open-mmlab/mmocr | train | 3,734 | |
bbdc1a47cc11b838f782af32629dd345dadefd75 | [
"candidate = [1]\nnum = [0, 1, 2]\nfor i in range(3, n + 1):\n new_candidate = (len(candidate) + 1) ** 2\n if i >= new_candidate:\n candidate.append(new_candidate)\n subnum = 2 ** 31 - 1\n for j in candidate:\n subnum = min(1 + num[i - j], subnum)\n num.append(subnum)\nreturn num[n]",
... | <|body_start_0|>
candidate = [1]
num = [0, 1, 2]
for i in range(3, n + 1):
new_candidate = (len(candidate) + 1) ** 2
if i >= new_candidate:
candidate.append(new_candidate)
subnum = 2 ** 31 - 1
for j in candidate:
sub... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
candidate = [1]
num = [0, 1, 2]
for i in range(3, n + ... | stack_v2_sparse_classes_75kplus_train_000330 | 915 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares2",
"signature": "def numSquares2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010015 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def numSquares(self, n):
""":typ... | 2866df7587ee867a958a2b4fc02345bc3ef56999 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
candidate = [1]
num = [0, 1, 2]
for i in range(3, n + 1):
new_candidate = (len(candidate) + 1) ** 2
if i >= new_candidate:
candidate.append(new_candidate)
subnu... | the_stack_v2_python_sparse | 中级算法/numSquares.py | OrangeJessie/Fighting_Leetcode | train | 1 | |
b2f8a946bbd0e5d10eb06054850bd78eeeb350bd | [
"log.info('Updating SKIRT locally ...')\nskirt_repo_path = introspection.skirt_repo_dir\nlog.debug('Getting latest version ...')\nsubprocess.call(['git', 'pull', 'origin', 'master'], cwd=skirt_repo_path)\nlog.debug('Compiling latest version ...')\nsubprocess.call(['sh', 'makeSKIRT.sh'], cwd=skirt_repo_path)",
"lo... | <|body_start_0|>
log.info('Updating SKIRT locally ...')
skirt_repo_path = introspection.skirt_repo_dir
log.debug('Getting latest version ...')
subprocess.call(['git', 'pull', 'origin', 'master'], cwd=skirt_repo_path)
log.debug('Compiling latest version ...')
subprocess.ca... | This class ... | SKIRTUpdater | [
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SKIRTUpdater:
"""This class ..."""
def update_local(self):
"""This function ... :return:"""
<|body_0|>
def update_remote(self):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
log.info('Updating SKIRT locally ...')
... | stack_v2_sparse_classes_75kplus_train_000331 | 6,074 | permissive | [
{
"docstring": "This function ... :return:",
"name": "update_local",
"signature": "def update_local(self)"
},
{
"docstring": "This function ... :return:",
"name": "update_remote",
"signature": "def update_remote(self)"
}
] | 2 | null | Implement the Python class `SKIRTUpdater` described below.
Class description:
This class ...
Method signatures and docstrings:
- def update_local(self): This function ... :return:
- def update_remote(self): This function ... :return: | Implement the Python class `SKIRTUpdater` described below.
Class description:
This class ...
Method signatures and docstrings:
- def update_local(self): This function ... :return:
- def update_remote(self): This function ... :return:
<|skeleton|>
class SKIRTUpdater:
"""This class ..."""
def update_local(sel... | 62b2339beb2eb956565e1605d44d92f934361ad7 | <|skeleton|>
class SKIRTUpdater:
"""This class ..."""
def update_local(self):
"""This function ... :return:"""
<|body_0|>
def update_remote(self):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SKIRTUpdater:
"""This class ..."""
def update_local(self):
"""This function ... :return:"""
log.info('Updating SKIRT locally ...')
skirt_repo_path = introspection.skirt_repo_dir
log.debug('Getting latest version ...')
subprocess.call(['git', 'pull', 'origin', 'mast... | the_stack_v2_python_sparse | CAAPR/CAAPR_AstroMagic/PTS/pts/core/prep/update.py | Stargrazer82301/CAAPR | train | 8 |
060fddb0a79093ae9dd14ef4416d05a17d83b93a | [
"user = UserService.get_by_public_id(user_id)\nif user is None:\n return self.format_failure(404, 'User not found')\nreturn self.format_success(200, {'user': user.dictionary})",
"user.name = request.json.get('name') or user.name\nuser.username = request.json.get('username') or user.username\ntribe_id = request... | <|body_start_0|>
user = UserService.get_by_public_id(user_id)
if user is None:
return self.format_failure(404, 'User not found')
return self.format_success(200, {'user': user.dictionary})
<|end_body_0|>
<|body_start_1|>
user.name = request.json.get('name') or user.name
... | Resource for /user/<user_id> | UserResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserResource:
"""Resource for /user/<user_id>"""
def get(self, user_id: str):
"""GET /user/<user_id> Returns a User if found"""
<|body_0|>
def patch(self, user: User, jwt: dict, **_):
"""PATCH /user/<user_id> Edits a User"""
<|body_1|>
def delete(sel... | stack_v2_sparse_classes_75kplus_train_000332 | 2,232 | no_license | [
{
"docstring": "GET /user/<user_id> Returns a User if found",
"name": "get",
"signature": "def get(self, user_id: str)"
},
{
"docstring": "PATCH /user/<user_id> Edits a User",
"name": "patch",
"signature": "def patch(self, user: User, jwt: dict, **_)"
},
{
"docstring": "DELETE /u... | 3 | stack_v2_sparse_classes_30k_train_050064 | Implement the Python class `UserResource` described below.
Class description:
Resource for /user/<user_id>
Method signatures and docstrings:
- def get(self, user_id: str): GET /user/<user_id> Returns a User if found
- def patch(self, user: User, jwt: dict, **_): PATCH /user/<user_id> Edits a User
- def delete(self, u... | Implement the Python class `UserResource` described below.
Class description:
Resource for /user/<user_id>
Method signatures and docstrings:
- def get(self, user_id: str): GET /user/<user_id> Returns a User if found
- def patch(self, user: User, jwt: dict, **_): PATCH /user/<user_id> Edits a User
- def delete(self, u... | 8ab4034413262ff2271740d73df72b3d83ce5918 | <|skeleton|>
class UserResource:
"""Resource for /user/<user_id>"""
def get(self, user_id: str):
"""GET /user/<user_id> Returns a User if found"""
<|body_0|>
def patch(self, user: User, jwt: dict, **_):
"""PATCH /user/<user_id> Edits a User"""
<|body_1|>
def delete(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserResource:
"""Resource for /user/<user_id>"""
def get(self, user_id: str):
"""GET /user/<user_id> Returns a User if found"""
user = UserService.get_by_public_id(user_id)
if user is None:
return self.format_failure(404, 'User not found')
return self.format_su... | the_stack_v2_python_sparse | app/main/controllers/users/single_user_controller.py | Malawi-Water-Wells-project/malawi-auth-api | train | 1 |
3d7728e29ac8db37f265a9f24e071740ad30df78 | [
"super().__init__(metric_names=metric_names, seconds_between_polls=seconds_between_polls, true_objective_metric_name=true_objective_metric_name, min_progression=min_progression, max_progression=max_progression, min_curves=min_curves, trial_indices_to_ignore=trial_indices_to_ignore, normalize_progressions=normalize_... | <|body_start_0|>
super().__init__(metric_names=metric_names, seconds_between_polls=seconds_between_polls, true_objective_metric_name=true_objective_metric_name, min_progression=min_progression, max_progression=max_progression, min_curves=min_curves, trial_indices_to_ignore=trial_indices_to_ignore, normalize_pro... | Implements the strategy of stopping a trial if its performance doesn't reach a pre-specified threshold by a certain progression. | ThresholdEarlyStoppingStrategy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThresholdEarlyStoppingStrategy:
"""Implements the strategy of stopping a trial if its performance doesn't reach a pre-specified threshold by a certain progression."""
def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_between_polls: int=300, metric_threshold: float=0.2, m... | stack_v2_sparse_classes_75kplus_train_000333 | 8,574 | permissive | [
{
"docstring": "Construct a ThresholdEarlyStoppingStrategy instance. Args metric_names: A (length-one) list of name of the metric to observe. If None will default to the objective metric on the Experiment's OptimizationConfig. seconds_between_polls: How often to poll the early stopping metric to evaluate whethe... | 3 | stack_v2_sparse_classes_30k_train_045599 | Implement the Python class `ThresholdEarlyStoppingStrategy` described below.
Class description:
Implements the strategy of stopping a trial if its performance doesn't reach a pre-specified threshold by a certain progression.
Method signatures and docstrings:
- def __init__(self, metric_names: Optional[Iterable[str]]=... | Implement the Python class `ThresholdEarlyStoppingStrategy` described below.
Class description:
Implements the strategy of stopping a trial if its performance doesn't reach a pre-specified threshold by a certain progression.
Method signatures and docstrings:
- def __init__(self, metric_names: Optional[Iterable[str]]=... | 6443cee30cbf8cec290200a7420a3db08e4b5445 | <|skeleton|>
class ThresholdEarlyStoppingStrategy:
"""Implements the strategy of stopping a trial if its performance doesn't reach a pre-specified threshold by a certain progression."""
def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_between_polls: int=300, metric_threshold: float=0.2, m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThresholdEarlyStoppingStrategy:
"""Implements the strategy of stopping a trial if its performance doesn't reach a pre-specified threshold by a certain progression."""
def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_between_polls: int=300, metric_threshold: float=0.2, min_progressio... | the_stack_v2_python_sparse | ax/early_stopping/strategies/threshold.py | facebook/Ax | train | 2,207 |
4ccfc289fdeb821f73cf017ac85e177bb3af71bf | [
"self.alphabet = alphabet\nself.states = states\nself.transitions = transitions\nself.start = start\nself.final = final\nself.k = k\nself.n = n\nself.f = f\nself.depth = depth\nself.planar = planar\nself.unrStates = unrStates\nself.eqClasses = eqClasses\nif k is None:\n self.k = len(alphabet)\nif n is None:\n ... | <|body_start_0|>
self.alphabet = alphabet
self.states = states
self.transitions = transitions
self.start = start
self.final = final
self.k = k
self.n = n
self.f = f
self.depth = depth
self.planar = planar
self.unrStates = unrStates
... | DFA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DFA:
def __init__(self, alphabet, states, transitions, start, final, k=None, n=None, f=None, depth=None, planar=None, unrStates=None, eqClasses=None):
"""Initializes a DFA object. The five mandatory parameters correspond to the mathematical definition of a DFA. The remaining arguments pr... | stack_v2_sparse_classes_75kplus_train_000334 | 2,092 | no_license | [
{
"docstring": "Initializes a DFA object. The five mandatory parameters correspond to the mathematical definition of a DFA. The remaining arguments provide additional informations. k,n,f are computed from alphabet,states,final if not provided. States and alphabet symbols are preferably single characters.",
... | 2 | null | Implement the Python class `DFA` described below.
Class description:
Implement the DFA class.
Method signatures and docstrings:
- def __init__(self, alphabet, states, transitions, start, final, k=None, n=None, f=None, depth=None, planar=None, unrStates=None, eqClasses=None): Initializes a DFA object. The five mandato... | Implement the Python class `DFA` described below.
Class description:
Implement the DFA class.
Method signatures and docstrings:
- def __init__(self, alphabet, states, transitions, start, final, k=None, n=None, f=None, depth=None, planar=None, unrStates=None, eqClasses=None): Initializes a DFA object. The five mandato... | db11028bc8e3ba5006ddbb8476be28734767e022 | <|skeleton|>
class DFA:
def __init__(self, alphabet, states, transitions, start, final, k=None, n=None, f=None, depth=None, planar=None, unrStates=None, eqClasses=None):
"""Initializes a DFA object. The five mandatory parameters correspond to the mathematical definition of a DFA. The remaining arguments pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DFA:
def __init__(self, alphabet, states, transitions, start, final, k=None, n=None, f=None, depth=None, planar=None, unrStates=None, eqClasses=None):
"""Initializes a DFA object. The five mandatory parameters correspond to the mathematical definition of a DFA. The remaining arguments provide addition... | the_stack_v2_python_sparse | dfa.py | gregorhcs/Automatic-Generation-of-DFA-Minimization-Problems | train | 0 | |
97ee33229968adc10353fd571997de0e83d35f91 | [
"while head is not None:\n if hasattr(head, 'visited'):\n return True\n head.visited = True\n head = head.next\nreturn False",
"if head is None:\n return False\nn = 1\nmemo = id(head)\nhead = head.next\ncounter = 1 << n - 1\nwhile head is not None:\n if id(head) == memo:\n return True... | <|body_start_0|>
while head is not None:
if hasattr(head, 'visited'):
return True
head.visited = True
head = head.next
return False
<|end_body_0|>
<|body_start_1|>
if head is None:
return False
n = 1
memo = id(head)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycleWithMemory(self, head: ListNode) -> bool:
"""Find if the LinkedList has a cycle by assigning visited attribute to it :param head: :return: Runtime complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def hasCycleNoMemory(self, head) -> bool:
""... | stack_v2_sparse_classes_75kplus_train_000335 | 3,762 | no_license | [
{
"docstring": "Find if the LinkedList has a cycle by assigning visited attribute to it :param head: :return: Runtime complexity: O(n) Space complexity: O(n)",
"name": "hasCycleWithMemory",
"signature": "def hasCycleWithMemory(self, head: ListNode) -> bool"
},
{
"docstring": "Find if a LinkedLis... | 2 | stack_v2_sparse_classes_30k_train_054488 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycleWithMemory(self, head: ListNode) -> bool: Find if the LinkedList has a cycle by assigning visited attribute to it :param head: :return: Runtime complexity: O(n) Space... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycleWithMemory(self, head: ListNode) -> bool: Find if the LinkedList has a cycle by assigning visited attribute to it :param head: :return: Runtime complexity: O(n) Space... | ee8237b66975fb5584a3d68b311e762c0462c8aa | <|skeleton|>
class Solution:
def hasCycleWithMemory(self, head: ListNode) -> bool:
"""Find if the LinkedList has a cycle by assigning visited attribute to it :param head: :return: Runtime complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def hasCycleNoMemory(self, head) -> bool:
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasCycleWithMemory(self, head: ListNode) -> bool:
"""Find if the LinkedList has a cycle by assigning visited attribute to it :param head: :return: Runtime complexity: O(n) Space complexity: O(n)"""
while head is not None:
if hasattr(head, 'visited'):
r... | the_stack_v2_python_sparse | LC141-Linked-List-Cycle.py | kate-melnykova/LeetCode-solutions | train | 2 | |
8f08dd0d2176759d40e0510c9783633fed158b8d | [
"json_search_space = {'optimizer': {'_type': 'choice', '_value': ['Adam', 'SGD']}, 'learning_rate': {'_type': 'choice', '_value': [0.0001, 0.001, 0.002, 0.005, 0.01]}}\nsearch_space_instance = json2space(json_search_space)\nself.assertIn('root[optimizer]-choice', search_space_instance)\nself.assertIn('root[learning... | <|body_start_0|>
json_search_space = {'optimizer': {'_type': 'choice', '_value': ['Adam', 'SGD']}, 'learning_rate': {'_type': 'choice', '_value': [0.0001, 0.001, 0.002, 0.005, 0.01]}}
search_space_instance = json2space(json_search_space)
self.assertIn('root[optimizer]-choice', search_space_insta... | EvolutionTunerTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvolutionTunerTestCase:
def test_json2space(self):
"""test for json2space"""
<|body_0|>
def test_json2parameter(self):
"""test for json2parameter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_search_space = {'optimizer': {'_type': 'choice', '... | stack_v2_sparse_classes_75kplus_train_000336 | 2,940 | permissive | [
{
"docstring": "test for json2space",
"name": "test_json2space",
"signature": "def test_json2space(self)"
},
{
"docstring": "test for json2parameter",
"name": "test_json2parameter",
"signature": "def test_json2parameter(self)"
}
] | 2 | null | Implement the Python class `EvolutionTunerTestCase` described below.
Class description:
Implement the EvolutionTunerTestCase class.
Method signatures and docstrings:
- def test_json2space(self): test for json2space
- def test_json2parameter(self): test for json2parameter | Implement the Python class `EvolutionTunerTestCase` described below.
Class description:
Implement the EvolutionTunerTestCase class.
Method signatures and docstrings:
- def test_json2space(self): test for json2space
- def test_json2parameter(self): test for json2parameter
<|skeleton|>
class EvolutionTunerTestCase:
... | ce2b19405465a7c854f465a7784b77131d48ea44 | <|skeleton|>
class EvolutionTunerTestCase:
def test_json2space(self):
"""test for json2space"""
<|body_0|>
def test_json2parameter(self):
"""test for json2parameter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EvolutionTunerTestCase:
def test_json2space(self):
"""test for json2space"""
json_search_space = {'optimizer': {'_type': 'choice', '_value': ['Adam', 'SGD']}, 'learning_rate': {'_type': 'choice', '_value': [0.0001, 0.001, 0.002, 0.005, 0.01]}}
search_space_instance = json2space(json_se... | the_stack_v2_python_sparse | src/sdk/pynni/nni/evolution_tuner/test_evolution_tuner.py | Cjkkkk/nni | train | 2 | |
3ebe466b39a087faf193e6e556191f7af318a320 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AuthenticationMethodsPolicy()",
"from .authentication_method_configuration import AuthenticationMethodConfiguration\nfrom .authentication_methods_policy_migration_state import AuthenticationMethodsPolicyMigrationState\nfrom .entity imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AuthenticationMethodsPolicy()
<|end_body_0|>
<|body_start_1|>
from .authentication_method_configuration import AuthenticationMethodConfiguration
from .authentication_methods_policy_migra... | AuthenticationMethodsPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationMethodsPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_75kplus_train_000337 | 5,875 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AuthenticationMethodsPolicy",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | stack_v2_sparse_classes_30k_train_028593 | Implement the Python class `AuthenticationMethodsPolicy` described below.
Class description:
Implement the AuthenticationMethodsPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy: Creates a new instance of the appr... | Implement the Python class `AuthenticationMethodsPolicy` described below.
Class description:
Implement the AuthenticationMethodsPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AuthenticationMethodsPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthenticationMethodsPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | the_stack_v2_python_sparse | msgraph/generated/models/authentication_methods_policy.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8d30551cd625780e1ba6c7213c7e114b59a26b6d | [
"examiner = validated_data['examine']['examiner']\nnominator = validated_data.pop('nominator')\nexamine, _ = Examine.objects.get_or_create(contract=validated_data['contract'], examiner=examiner, defaults={'nominator': nominator})\nvalidated_data['examine'] = examine\nassessment: Assessment = validated_data['assessm... | <|body_start_0|>
examiner = validated_data['examine']['examiner']
nominator = validated_data.pop('nominator')
examine, _ = Examine.objects.get_or_create(contract=validated_data['contract'], examiner=examiner, defaults={'nominator': nominator})
validated_data['examine'] = examine
... | AssessmentExamineSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssessmentExamineSerializer:
def create(self, validated_data) -> AssessmentExamine:
"""Allow write for nested examiner field, automatically create missing Examine relation for new AssessmentExamine relation. Also apply constraint to forbid some contract type to have more than one examine... | stack_v2_sparse_classes_75kplus_train_000338 | 18,133 | no_license | [
{
"docstring": "Allow write for nested examiner field, automatically create missing Examine relation for new AssessmentExamine relation. Also apply constraint to forbid some contract type to have more than one examiner for each assessment. Args: validated_data: a dictionary contain the data a request sent, alre... | 2 | stack_v2_sparse_classes_30k_train_034991 | Implement the Python class `AssessmentExamineSerializer` described below.
Class description:
Implement the AssessmentExamineSerializer class.
Method signatures and docstrings:
- def create(self, validated_data) -> AssessmentExamine: Allow write for nested examiner field, automatically create missing Examine relation ... | Implement the Python class `AssessmentExamineSerializer` described below.
Class description:
Implement the AssessmentExamineSerializer class.
Method signatures and docstrings:
- def create(self, validated_data) -> AssessmentExamine: Allow write for nested examiner field, automatically create missing Examine relation ... | f9baeacb33178fcc36c6a9983bbb03994158ca4d | <|skeleton|>
class AssessmentExamineSerializer:
def create(self, validated_data) -> AssessmentExamine:
"""Allow write for nested examiner field, automatically create missing Examine relation for new AssessmentExamine relation. Also apply constraint to forbid some contract type to have more than one examine... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssessmentExamineSerializer:
def create(self, validated_data) -> AssessmentExamine:
"""Allow write for nested examiner field, automatically create missing Examine relation for new AssessmentExamine relation. Also apply constraint to forbid some contract type to have more than one examiner for each ass... | the_stack_v2_python_sparse | srpms/research_mgt/serializers.py | edwinekyang/srpms | train | 0 | |
d10a819c69ab93c29fefaaf9c9639187fc87daf7 | [
"if _debug:\n ConfigArgumentParser._debug('__init__')\nArgumentParser.__init__(self, **kwargs)\nself.add_argument('--ini', help='device object configuration file', default=BACPYPES_INI)",
"if _debug:\n ConfigArgumentParser._debug('parse_args')\nresult_args = ArgumentParser.parse_args(self, *args, **kwargs)\... | <|body_start_0|>
if _debug:
ConfigArgumentParser._debug('__init__')
ArgumentParser.__init__(self, **kwargs)
self.add_argument('--ini', help='device object configuration file', default=BACPYPES_INI)
<|end_body_0|>
<|body_start_1|>
if _debug:
ConfigArgumentParser._... | ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file | ConfigArgumentParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigArgumentParser:
"""ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file"""
def __init__(self, **kwargs):
"""Follow normal initialization and add BACpypes arguments."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_000339 | 7,777 | permissive | [
{
"docstring": "Follow normal initialization and add BACpypes arguments.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Parse the arguments as usual, then add default processing.",
"name": "parse_args",
"signature": "def parse_args(self, *args, **kwa... | 2 | stack_v2_sparse_classes_30k_train_031557 | Implement the Python class `ConfigArgumentParser` described below.
Class description:
ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file
Method signatures and docstrings:
- def __init__(self, **kwargs): Follow normal initializa... | Implement the Python class `ConfigArgumentParser` described below.
Class description:
ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file
Method signatures and docstrings:
- def __init__(self, **kwargs): Follow normal initializa... | a5be2ad5ac69821c12299716b167dd52041b5342 | <|skeleton|>
class ConfigArgumentParser:
"""ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file"""
def __init__(self, **kwargs):
"""Follow normal initialization and add BACpypes arguments."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigArgumentParser:
"""ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file"""
def __init__(self, **kwargs):
"""Follow normal initialization and add BACpypes arguments."""
if _debug:
Con... | the_stack_v2_python_sparse | py25/bacpypes/consolelogging.py | JoelBender/bacpypes | train | 284 |
6e067121fd6ab843090e64335eca4a7984db275c | [
"super().__init__(*args)\nstate = self.hass.states.get(self.entity_id)\nvalve_type = self.config[CONF_TYPE]\nself.category = VALVE_TYPE[valve_type].category\nserv_valve = self.add_preload_service(SERV_VALVE)\nself.char_active = serv_valve.configure_char(CHAR_ACTIVE, value=False, setter_callback=self.set_state)\nsel... | <|body_start_0|>
super().__init__(*args)
state = self.hass.states.get(self.entity_id)
valve_type = self.config[CONF_TYPE]
self.category = VALVE_TYPE[valve_type].category
serv_valve = self.add_preload_service(SERV_VALVE)
self.char_active = serv_valve.configure_char(CHAR_AC... | Generate a Valve accessory. | Valve | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Valve:
"""Generate a Valve accessory."""
def __init__(self, *args):
"""Initialize a Valve accessory object."""
<|body_0|>
def set_state(self, value):
"""Move value state to value if call came from HomeKit."""
<|body_1|>
def async_update_state(self, n... | stack_v2_sparse_classes_75kplus_train_000340 | 10,454 | permissive | [
{
"docstring": "Initialize a Valve accessory object.",
"name": "__init__",
"signature": "def __init__(self, *args)"
},
{
"docstring": "Move value state to value if call came from HomeKit.",
"name": "set_state",
"signature": "def set_state(self, value)"
},
{
"docstring": "Update s... | 3 | stack_v2_sparse_classes_30k_train_033089 | Implement the Python class `Valve` described below.
Class description:
Generate a Valve accessory.
Method signatures and docstrings:
- def __init__(self, *args): Initialize a Valve accessory object.
- def set_state(self, value): Move value state to value if call came from HomeKit.
- def async_update_state(self, new_s... | Implement the Python class `Valve` described below.
Class description:
Generate a Valve accessory.
Method signatures and docstrings:
- def __init__(self, *args): Initialize a Valve accessory object.
- def set_state(self, value): Move value state to value if call came from HomeKit.
- def async_update_state(self, new_s... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class Valve:
"""Generate a Valve accessory."""
def __init__(self, *args):
"""Initialize a Valve accessory object."""
<|body_0|>
def set_state(self, value):
"""Move value state to value if call came from HomeKit."""
<|body_1|>
def async_update_state(self, n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Valve:
"""Generate a Valve accessory."""
def __init__(self, *args):
"""Initialize a Valve accessory object."""
super().__init__(*args)
state = self.hass.states.get(self.entity_id)
valve_type = self.config[CONF_TYPE]
self.category = VALVE_TYPE[valve_type].category
... | the_stack_v2_python_sparse | homeassistant/components/homekit/type_switches.py | home-assistant/core | train | 35,501 |
4d4841339907518a7eeb519c4853858f6700dd29 | [
"res = []\nif root:\n res.append(root.val)\n res += self.preorderTraversal(root.left)\n res += self.preorderTraversal(root.right)\nelse:\n res.append(None)\n return res\nreturn res",
"p_res = self.preorderTraversal(p)\nq_res = self.preorderTraversal(q)\nif p_res == q_res:\n return True\nelse:\n ... | <|body_start_0|>
res = []
if root:
res.append(root.val)
res += self.preorderTraversal(root.left)
res += self.preorderTraversal(root.right)
else:
res.append(None)
return res
return res
<|end_body_0|>
<|body_start_1|>
p_r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode"""
<|body_0|>
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
if root:
... | stack_v2_sparse_classes_75kplus_train_000341 | 1,261 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047503 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
<|skeleton|>
class Solution:
def preo... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode"""
<|body_0|>
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode"""
res = []
if root:
res.append(root.val)
res += self.preorderTraversal(root.left)
res += self.preorderTraversal(root.right)
else:
res.append(None)
r... | the_stack_v2_python_sparse | leetcode/isSameTree-100.py | pittcat/Algorithm_Practice | train | 0 | |
2c94347df29165ac2a5109083de89f3ed8cec80b | [
"try:\n customer, _created = Customer.get_or_create(subscriber=subscriber_request_callback(self.request))\n serializer = SubscriptionSerializer(customer.subscription)\n return Response(serializer.data)\nexcept:\n return Response(status=status.HTTP_204_NO_CONTENT)",
"serializer = CreateSubscriptionSeri... | <|body_start_0|>
try:
customer, _created = Customer.get_or_create(subscriber=subscriber_request_callback(self.request))
serializer = SubscriptionSerializer(customer.subscription)
return Response(serializer.data)
except:
return Response(status=status.HTTP_2... | API Endpoints for the Subscription object. | SubscriptionRestView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionRestView:
"""API Endpoints for the Subscription object."""
def get(self, request, **kwargs):
"""Return the customer's valid subscriptions. Returns with status code 200."""
<|body_0|>
def post(self, request, **kwargs):
"""Create a new current subscript... | stack_v2_sparse_classes_75kplus_train_000342 | 4,950 | permissive | [
{
"docstring": "Return the customer's valid subscriptions. Returns with status code 200.",
"name": "get",
"signature": "def get(self, request, **kwargs)"
},
{
"docstring": "Create a new current subscription for the user. Returns with status code 201.",
"name": "post",
"signature": "def p... | 3 | stack_v2_sparse_classes_30k_train_021591 | Implement the Python class `SubscriptionRestView` described below.
Class description:
API Endpoints for the Subscription object.
Method signatures and docstrings:
- def get(self, request, **kwargs): Return the customer's valid subscriptions. Returns with status code 200.
- def post(self, request, **kwargs): Create a ... | Implement the Python class `SubscriptionRestView` described below.
Class description:
API Endpoints for the Subscription object.
Method signatures and docstrings:
- def get(self, request, **kwargs): Return the customer's valid subscriptions. Returns with status code 200.
- def post(self, request, **kwargs): Create a ... | 325cc11fbc28eee7507778e387714e9465880d68 | <|skeleton|>
class SubscriptionRestView:
"""API Endpoints for the Subscription object."""
def get(self, request, **kwargs):
"""Return the customer's valid subscriptions. Returns with status code 200."""
<|body_0|>
def post(self, request, **kwargs):
"""Create a new current subscript... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubscriptionRestView:
"""API Endpoints for the Subscription object."""
def get(self, request, **kwargs):
"""Return the customer's valid subscriptions. Returns with status code 200."""
try:
customer, _created = Customer.get_or_create(subscriber=subscriber_request_callback(self.... | the_stack_v2_python_sparse | djstripe/contrib/rest_framework/views.py | talpor/dj-stripe | train | 1 |
aea53894b9c03f60fcf963c291cb750fc1aded00 | [
"self._value = None\nself._lchild = None\nself._rchild = None",
"if pre_order != []:\n root = pre_order[0]\n self._value = int(root)\n index = in_order.index(root)\n if pre_order[1:index + 1] != []:\n self._lchild = BinaryTree()\n self._lchild.build_tree(pre_order[1:index + 1], in_order[... | <|body_start_0|>
self._value = None
self._lchild = None
self._rchild = None
<|end_body_0|>
<|body_start_1|>
if pre_order != []:
root = pre_order[0]
self._value = int(root)
index = in_order.index(root)
if pre_order[1:index + 1] != []:
... | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
def __init__(self):
"""Initializes a BinaryTree class object and all of its attributes. Parameters: None. Returns: None."""
<|body_0|>
def build_tree(self, pre_order, in_order):
"""Recursively creates the binary tree from the preoder and inorder list. Par... | stack_v2_sparse_classes_75kplus_train_000343 | 5,430 | no_license | [
{
"docstring": "Initializes a BinaryTree class object and all of its attributes. Parameters: None. Returns: None.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Recursively creates the binary tree from the preoder and inorder list. Parameters: pre_order and in_order a... | 5 | stack_v2_sparse_classes_30k_train_021138 | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def __init__(self): Initializes a BinaryTree class object and all of its attributes. Parameters: None. Returns: None.
- def build_tree(self, pre_order, in_order): Recursively... | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def __init__(self): Initializes a BinaryTree class object and all of its attributes. Parameters: None. Returns: None.
- def build_tree(self, pre_order, in_order): Recursively... | cde5fa9b38cf0001d0a4283e0184268be18ba2e7 | <|skeleton|>
class BinaryTree:
def __init__(self):
"""Initializes a BinaryTree class object and all of its attributes. Parameters: None. Returns: None."""
<|body_0|>
def build_tree(self, pre_order, in_order):
"""Recursively creates the binary tree from the preoder and inorder list. Par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryTree:
def __init__(self):
"""Initializes a BinaryTree class object and all of its attributes. Parameters: None. Returns: None."""
self._value = None
self._lchild = None
self._rchild = None
def build_tree(self, pre_order, in_order):
"""Recursively creates the ... | the_stack_v2_python_sparse | CSC120/Assignment 11/huffman.py | rtequida/UofA | train | 0 | |
2df5df756ce58a338d527cf8296f173414b6e2d5 | [
"if tokenizer_args is None:\n tokenizer_args = {}\ntokenizer_options = []\nif arg_separator != ' ':\n tokenizer_options = [option + arg_separator + str(tokenizer_args[option]) for option in tokenizer_args]\nelse:\n for option in tokenizer_args:\n tokenizer_options.extend([option, str(tokenizer_args[... | <|body_start_0|>
if tokenizer_args is None:
tokenizer_args = {}
tokenizer_options = []
if arg_separator != ' ':
tokenizer_options = [option + arg_separator + str(tokenizer_args[option]) for option in tokenizer_args]
else:
for option in tokenizer_args:
... | Class for arbitrary external tokenizer that accepts untokenized text to stdin and emits tokenized tezt to stdout, with passable parameters. It is assumed that in general, external tokenizers will be more efficient when run once per file, so are run as such (instead of one-execution-per-line.) Args: path tokenizer_args ... | ExternalTokenizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalTokenizer:
"""Class for arbitrary external tokenizer that accepts untokenized text to stdin and emits tokenized tezt to stdout, with passable parameters. It is assumed that in general, external tokenizers will be more efficient when run once per file, so are run as such (instead of one-ex... | stack_v2_sparse_classes_75kplus_train_000344 | 32,168 | permissive | [
{
"docstring": "Initialize the wrapper around the external tokenizer.",
"name": "__init__",
"signature": "def __init__(self, path: str, tokenizer_args: Optional[Sequence[str]]=None, arg_separator: str=' ') -> None"
},
{
"docstring": "Pass the sentence through the external tokenizer. Args: sent: ... | 2 | stack_v2_sparse_classes_30k_train_029077 | Implement the Python class `ExternalTokenizer` described below.
Class description:
Class for arbitrary external tokenizer that accepts untokenized text to stdin and emits tokenized tezt to stdout, with passable parameters. It is assumed that in general, external tokenizers will be more efficient when run once per file... | Implement the Python class `ExternalTokenizer` described below.
Class description:
Class for arbitrary external tokenizer that accepts untokenized text to stdin and emits tokenized tezt to stdout, with passable parameters. It is assumed that in general, external tokenizers will be more efficient when run once per file... | b5e6985d3bedfac102312cab030a60594bc17baf | <|skeleton|>
class ExternalTokenizer:
"""Class for arbitrary external tokenizer that accepts untokenized text to stdin and emits tokenized tezt to stdout, with passable parameters. It is assumed that in general, external tokenizers will be more efficient when run once per file, so are run as such (instead of one-ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExternalTokenizer:
"""Class for arbitrary external tokenizer that accepts untokenized text to stdin and emits tokenized tezt to stdout, with passable parameters. It is assumed that in general, external tokenizers will be more efficient when run once per file, so are run as such (instead of one-execution-per-l... | the_stack_v2_python_sparse | xnmt/preproc.py | philip30/xnmt | train | 0 |
7215d7490b2ff272d63cfe371e9e0747e87d1667 | [
"if request.auth and hasattr(request.auth, 'project'):\n return Response(status=403)\nqueryset = Team.objects.filter(organization=organization, status=TeamStatus.VISIBLE).order_by('slug')\nquery = request.GET.get('query')\nif query:\n tokens = tokenize_query(query)\n for key, value in six.iteritems(tokens)... | <|body_start_0|>
if request.auth and hasattr(request.auth, 'project'):
return Response(status=403)
queryset = Team.objects.filter(organization=organization, status=TeamStatus.VISIBLE).order_by('slug')
query = request.GET.get('query')
if query:
tokens = tokenize_qu... | OrganizationTeamsEndpoint | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationTeamsEndpoint:
def get(self, request, organization):
"""List an Organization's Teams ```````````````````````````` Return a list of teams bound to a organization. :pparam string organization_slug: the slug of the organization for which the teams should be listed. :auth: requir... | stack_v2_sparse_classes_75kplus_train_000345 | 6,332 | permissive | [
{
"docstring": "List an Organization's Teams ```````````````````````````` Return a list of teams bound to a organization. :pparam string organization_slug: the slug of the organization for which the teams should be listed. :auth: required",
"name": "get",
"signature": "def get(self, request, organizatio... | 2 | stack_v2_sparse_classes_30k_train_036984 | Implement the Python class `OrganizationTeamsEndpoint` described below.
Class description:
Implement the OrganizationTeamsEndpoint class.
Method signatures and docstrings:
- def get(self, request, organization): List an Organization's Teams ```````````````````````````` Return a list of teams bound to a organization. ... | Implement the Python class `OrganizationTeamsEndpoint` described below.
Class description:
Implement the OrganizationTeamsEndpoint class.
Method signatures and docstrings:
- def get(self, request, organization): List an Organization's Teams ```````````````````````````` Return a list of teams bound to a organization. ... | 36a02ed244c7b59ee1f2523e64e4749e404ab0f7 | <|skeleton|>
class OrganizationTeamsEndpoint:
def get(self, request, organization):
"""List an Organization's Teams ```````````````````````````` Return a list of teams bound to a organization. :pparam string organization_slug: the slug of the organization for which the teams should be listed. :auth: requir... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationTeamsEndpoint:
def get(self, request, organization):
"""List an Organization's Teams ```````````````````````````` Return a list of teams bound to a organization. :pparam string organization_slug: the slug of the organization for which the teams should be listed. :auth: required"""
... | the_stack_v2_python_sparse | src/sentry/api/endpoints/organization_teams.py | commonlims/commonlims | train | 4 | |
b4dc1fcdd1aad4db485cb445eabea1fd477eedfb | [
"input_spec = TensorSpec((10,), torch.float32)\nembedding = input_spec.ones(outer_dims=(1,))\nnet = OnehotCategoricalProjectionNetwork(input_size=input_spec.shape[0], mode=mode, action_spec=BoundedTensorSpec((1,), minimum=0, maximum=4), logits_init_output_factor=0)\ndist, _ = net(embedding)\nself.assertTrue(isinsta... | <|body_start_0|>
input_spec = TensorSpec((10,), torch.float32)
embedding = input_spec.ones(outer_dims=(1,))
net = OnehotCategoricalProjectionNetwork(input_size=input_spec.shape[0], mode=mode, action_spec=BoundedTensorSpec((1,), minimum=0, maximum=4), logits_init_output_factor=0)
dist, _ ... | TestOnehotCategoricalProjectionNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOnehotCategoricalProjectionNetwork:
def test_onehot_categorical_uniform_projection_net(self, mode):
"""A zero-weight net generates uniform actions."""
<|body_0|>
def test_onehot_samples(self, mode):
"""Samples from the projection net are onehot vectors."""
... | stack_v2_sparse_classes_75kplus_train_000346 | 19,986 | permissive | [
{
"docstring": "A zero-weight net generates uniform actions.",
"name": "test_onehot_categorical_uniform_projection_net",
"signature": "def test_onehot_categorical_uniform_projection_net(self, mode)"
},
{
"docstring": "Samples from the projection net are onehot vectors.",
"name": "test_onehot... | 4 | stack_v2_sparse_classes_30k_train_008738 | Implement the Python class `TestOnehotCategoricalProjectionNetwork` described below.
Class description:
Implement the TestOnehotCategoricalProjectionNetwork class.
Method signatures and docstrings:
- def test_onehot_categorical_uniform_projection_net(self, mode): A zero-weight net generates uniform actions.
- def tes... | Implement the Python class `TestOnehotCategoricalProjectionNetwork` described below.
Class description:
Implement the TestOnehotCategoricalProjectionNetwork class.
Method signatures and docstrings:
- def test_onehot_categorical_uniform_projection_net(self, mode): A zero-weight net generates uniform actions.
- def tes... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class TestOnehotCategoricalProjectionNetwork:
def test_onehot_categorical_uniform_projection_net(self, mode):
"""A zero-weight net generates uniform actions."""
<|body_0|>
def test_onehot_samples(self, mode):
"""Samples from the projection net are onehot vectors."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestOnehotCategoricalProjectionNetwork:
def test_onehot_categorical_uniform_projection_net(self, mode):
"""A zero-weight net generates uniform actions."""
input_spec = TensorSpec((10,), torch.float32)
embedding = input_spec.ones(outer_dims=(1,))
net = OnehotCategoricalProjectio... | the_stack_v2_python_sparse | alf/networks/projection_networks_test.py | HorizonRobotics/alf | train | 288 | |
66dbd758145613741f5fdcf907348276b1ddb6f8 | [
"logging.info('Horting Accuracy for Majors')\nm_count, m_pos, m_num = ({}, {}, {})\nindex = self.storage.student_index.student_index\nfor i in range(10000):\n student_id = random.choice(index.keys())\n major_id = index[student_id].major_id\n c, p, n = self.horting_exclude_num(num=1, student_id=student_id)\... | <|body_start_0|>
logging.info('Horting Accuracy for Majors')
m_count, m_pos, m_num = ({}, {}, {})
index = self.storage.student_index.student_index
for i in range(10000):
student_id = random.choice(index.keys())
major_id = index[student_id].major_id
c, ... | TestMajorsPrediction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMajorsPrediction:
def testHortingMajors(self):
"""Test how horting works for different majors."""
<|body_0|>
def testHortingMajorsGur(self):
"""Test how horting works for different majors for GURs."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_000347 | 3,081 | no_license | [
{
"docstring": "Test how horting works for different majors.",
"name": "testHortingMajors",
"signature": "def testHortingMajors(self)"
},
{
"docstring": "Test how horting works for different majors for GURs.",
"name": "testHortingMajorsGur",
"signature": "def testHortingMajorsGur(self)"
... | 2 | null | Implement the Python class `TestMajorsPrediction` described below.
Class description:
Implement the TestMajorsPrediction class.
Method signatures and docstrings:
- def testHortingMajors(self): Test how horting works for different majors.
- def testHortingMajorsGur(self): Test how horting works for different majors fo... | Implement the Python class `TestMajorsPrediction` described below.
Class description:
Implement the TestMajorsPrediction class.
Method signatures and docstrings:
- def testHortingMajors(self): Test how horting works for different majors.
- def testHortingMajorsGur(self): Test how horting works for different majors fo... | a5c6eb7a31ff7ed0cee133d5860108b81b916cf0 | <|skeleton|>
class TestMajorsPrediction:
def testHortingMajors(self):
"""Test how horting works for different majors."""
<|body_0|>
def testHortingMajorsGur(self):
"""Test how horting works for different majors for GURs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMajorsPrediction:
def testHortingMajors(self):
"""Test how horting works for different majors."""
logging.info('Horting Accuracy for Majors')
m_count, m_pos, m_num = ({}, {}, {})
index = self.storage.student_index.student_index
for i in range(10000):
stu... | the_stack_v2_python_sparse | TestMajorsPrediction.py | camradal/CourseRecommender | train | 0 | |
46684ea2d760d1e11dff1db3d04caeed6ff4daba | [
"try:\n netconf.set_on_net_conf(nnid)\n netconf.save_conf(nnid, str(request.body, 'utf-8'))\n return_data = {'status': '200', 'result': nnid}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n netconf.set_off_net_conf(nnid)\n return_data = {'status': '404', 'result': str(e)}\n ... | <|body_start_0|>
try:
netconf.set_on_net_conf(nnid)
netconf.save_conf(nnid, str(request.body, 'utf-8'))
return_data = {'status': '200', 'result': nnid}
return Response(json.dumps(return_data))
except Exception as e:
netconf.set_off_net_conf(nni... | 1. Name : WideDeepNetConfig (step 7) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/{ar... | WideDeepNetConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WideDeepNetConfig:
"""1. Name : WideDeepNetConfig (step 7) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/typ... | stack_v2_sparse_classes_75kplus_train_000348 | 3,261 | no_license | [
{
"docstring": "- desc : insert new neural network information - Request json data example <texfield> <font size = 1> { \"layer\":[100,50,20] } </textfield> --- parameters: - name: body paramType: body pytype: json",
"name": "post",
"signature": "def post(self, request, nnid)"
},
{
"docstring": ... | 4 | null | Implement the Python class `WideDeepNetConfig` described below.
Class description:
1. Name : WideDeepNetConfig (step 7) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{base... | Implement the Python class `WideDeepNetConfig` described below.
Class description:
1. Name : WideDeepNetConfig (step 7) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{base... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class WideDeepNetConfig:
"""1. Name : WideDeepNetConfig (step 7) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WideDeepNetConfig:
"""1. Name : WideDeepNetConfig (step 7) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/b... | the_stack_v2_python_sparse | tfmsarest/views/wdnn_config.py | TensorMSA/tensormsa_old | train | 6 |
b9d12081a454c04b079b353e5d6081e856abd85d | [
"self.t = [[float('-inf'), 0]]\nself.total = 0\nself.lock = Lock()",
"with self.lock:\n if self.t[-1][0] == timestamp:\n self.t[-1][1] += 1\n else:\n c = self.t[-1][1] + 1\n self.t.append([timestamp, c])",
"i = bisect(self.t, [timestamp - 300, float('inf')]) - 1\nj = bisect(self.t, [t... | <|body_start_0|>
self.t = [[float('-inf'), 0]]
self.total = 0
self.lock = Lock()
<|end_body_0|>
<|body_start_1|>
with self.lock:
if self.t[-1][0] == timestamp:
self.t[-1][1] += 1
else:
c = self.t[-1][1] + 1
self.t.a... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_75kplus_train_000349 | 1,540 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_049408 | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | 84b35ec9a4e4319b29eb5f0f226543c9f3f47630 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.t = [[float('-inf'), 0]]
self.total = 0
self.lock = Lock()
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
... | the_stack_v2_python_sparse | design-hit-counter.py | maomao905/algo | train | 0 | |
0a9d83bf85ceed4423b114c67361dcf32b8d3a0b | [
"super(CheckCiscoTEMP, self).define_plugin_arguments()\nself.required_args.add_argument('-w', nargs=3, metavar=('outlet', 'fex_outlet', 'fex_die'), type=int, dest='warnthr', help='Warning threshold for 5K Outlet / Catalyst, Fex Outlet and Fex Die (only on Nexus).', required=True)\nself.required_args.add_argument('-... | <|body_start_0|>
super(CheckCiscoTEMP, self).define_plugin_arguments()
self.required_args.add_argument('-w', nargs=3, metavar=('outlet', 'fex_outlet', 'fex_die'), type=int, dest='warnthr', help='Warning threshold for 5K Outlet / Catalyst, Fex Outlet and Fex Die (only on Nexus).', required=True)
... | CheckCiscoTEMP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckCiscoTEMP:
def define_plugin_arguments(self):
"""Define arguments for the plugin"""
<|body_0|>
def verify_plugin_arguments(self):
"""Do arguments checks"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CheckCiscoTEMP, self).define_plugin_a... | stack_v2_sparse_classes_75kplus_train_000350 | 6,129 | permissive | [
{
"docstring": "Define arguments for the plugin",
"name": "define_plugin_arguments",
"signature": "def define_plugin_arguments(self)"
},
{
"docstring": "Do arguments checks",
"name": "verify_plugin_arguments",
"signature": "def verify_plugin_arguments(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013814 | Implement the Python class `CheckCiscoTEMP` described below.
Class description:
Implement the CheckCiscoTEMP class.
Method signatures and docstrings:
- def define_plugin_arguments(self): Define arguments for the plugin
- def verify_plugin_arguments(self): Do arguments checks | Implement the Python class `CheckCiscoTEMP` described below.
Class description:
Implement the CheckCiscoTEMP class.
Method signatures and docstrings:
- def define_plugin_arguments(self): Define arguments for the plugin
- def verify_plugin_arguments(self): Do arguments checks
<|skeleton|>
class CheckCiscoTEMP:
d... | 4a66d26f9d2982609489eaa0f57d6afb16aca37c | <|skeleton|>
class CheckCiscoTEMP:
def define_plugin_arguments(self):
"""Define arguments for the plugin"""
<|body_0|>
def verify_plugin_arguments(self):
"""Do arguments checks"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckCiscoTEMP:
def define_plugin_arguments(self):
"""Define arguments for the plugin"""
super(CheckCiscoTEMP, self).define_plugin_arguments()
self.required_args.add_argument('-w', nargs=3, metavar=('outlet', 'fex_outlet', 'fex_die'), type=int, dest='warnthr', help='Warning threshold f... | the_stack_v2_python_sparse | plugin/plugins/network/check_cisco_temp.py | crazy-canux/zplugin | train | 0 | |
958bc90811ee3a7bb02032a522bbcce9b373d48c | [
"try:\n books = Books.objects.all()\n paginator = Paginator(books, config.PAGE_SIZE)\n page_books = paginator.get_page(page_no)\n result = {'has_next': page_books.has_next(), 'has_previous': page_books.has_previous()}\n book_list = json.dumps(BookSerializer(page_books.object_list, many=True).data)\n ... | <|body_start_0|>
try:
books = Books.objects.all()
paginator = Paginator(books, config.PAGE_SIZE)
page_books = paginator.get_page(page_no)
result = {'has_next': page_books.has_next(), 'has_previous': page_books.has_previous()}
book_list = json.dumps(Boo... | BooksService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BooksService:
def browse_books(self, page_no):
"""Functionality: Params: Response:"""
<|body_0|>
def create_book(self, data):
"""Functionality: Params: Response:"""
<|body_1|>
def update_book(self, data):
"""Functionality: Params: Response:"""
... | stack_v2_sparse_classes_75kplus_train_000351 | 9,562 | no_license | [
{
"docstring": "Functionality: Params: Response:",
"name": "browse_books",
"signature": "def browse_books(self, page_no)"
},
{
"docstring": "Functionality: Params: Response:",
"name": "create_book",
"signature": "def create_book(self, data)"
},
{
"docstring": "Functionality: Para... | 4 | stack_v2_sparse_classes_30k_train_034723 | Implement the Python class `BooksService` described below.
Class description:
Implement the BooksService class.
Method signatures and docstrings:
- def browse_books(self, page_no): Functionality: Params: Response:
- def create_book(self, data): Functionality: Params: Response:
- def update_book(self, data): Functiona... | Implement the Python class `BooksService` described below.
Class description:
Implement the BooksService class.
Method signatures and docstrings:
- def browse_books(self, page_no): Functionality: Params: Response:
- def create_book(self, data): Functionality: Params: Response:
- def update_book(self, data): Functiona... | 0845a00947c9d9fc5d57c58d984afc0f5ad1833b | <|skeleton|>
class BooksService:
def browse_books(self, page_no):
"""Functionality: Params: Response:"""
<|body_0|>
def create_book(self, data):
"""Functionality: Params: Response:"""
<|body_1|>
def update_book(self, data):
"""Functionality: Params: Response:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BooksService:
def browse_books(self, page_no):
"""Functionality: Params: Response:"""
try:
books = Books.objects.all()
paginator = Paginator(books, config.PAGE_SIZE)
page_books = paginator.get_page(page_no)
result = {'has_next': page_books.has_ne... | the_stack_v2_python_sparse | books/service.py | sshujonn/library_management | train | 0 | |
6f53ea9a20fa71b58ff321a263153bf8c35292e9 | [
"use = kwargs.pop('use', None)\nignore = kwargs.pop('ignore', None)\ncls = kwargs.pop('cls', None)\nlazy = kwargs.pop('lazy', None)\nif kwargs:\n raise TypeError('Unrecognized keywords')\nself._base = base\nself._use = dict(use or ())\nself._ignore = frozenset(ignore or ())\nself._loader = loader\nself._cls = cl... | <|body_start_0|>
use = kwargs.pop('use', None)
ignore = kwargs.pop('ignore', None)
cls = kwargs.pop('cls', None)
lazy = kwargs.pop('lazy', None)
if kwargs:
raise TypeError('Unrecognized keywords')
self._base = base
self._use = dict(use or ())
s... | Create template lists based on a start configuration :IVariables: `_base` : ``tuple`` Base template list `_use` : ``dict`` extra overlay -> filename mapping `_ignore` : ``frozenset`` Template names to ignore | Layout | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Layout:
"""Create template lists based on a start configuration :IVariables: `_base` : ``tuple`` Base template list `_use` : ``dict`` extra overlay -> filename mapping `_ignore` : ``frozenset`` Template names to ignore"""
def __init__(self, loader, *base, **kwargs):
"""Initialization... | stack_v2_sparse_classes_75kplus_train_000352 | 16,325 | permissive | [
{
"docstring": "Initialization :Parameters: `loader` : `Loader` Template loader `base` : ``tuple`` Base template list `kwargs` : ``dict`` Keywords :Keywords: `use` : ``dict`` extra overlay -> filename mapping `ignore` : ``iterable`` template names to ignore `cls` : ``callable`` template list factory. If omitted... | 3 | stack_v2_sparse_classes_30k_train_052831 | Implement the Python class `Layout` described below.
Class description:
Create template lists based on a start configuration :IVariables: `_base` : ``tuple`` Base template list `_use` : ``dict`` extra overlay -> filename mapping `_ignore` : ``frozenset`` Template names to ignore
Method signatures and docstrings:
- de... | Implement the Python class `Layout` described below.
Class description:
Create template lists based on a start configuration :IVariables: `_base` : ``tuple`` Base template list `_use` : ``dict`` extra overlay -> filename mapping `_ignore` : ``frozenset`` Template names to ignore
Method signatures and docstrings:
- de... | 65a93080281f9ce5c0379e9dbb111f14965a8613 | <|skeleton|>
class Layout:
"""Create template lists based on a start configuration :IVariables: `_base` : ``tuple`` Base template list `_use` : ``dict`` extra overlay -> filename mapping `_ignore` : ``frozenset`` Template names to ignore"""
def __init__(self, loader, *base, **kwargs):
"""Initialization... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Layout:
"""Create template lists based on a start configuration :IVariables: `_base` : ``tuple`` Base template list `_use` : ``dict`` extra overlay -> filename mapping `_ignore` : ``frozenset`` Template names to ignore"""
def __init__(self, loader, *base, **kwargs):
"""Initialization :Parameters:... | the_stack_v2_python_sparse | tdi/tools/template.py | ndparker/tdi | train | 4 |
0b4e5df216b6b06108f4be9e4d62bf2d524444a8 | [
"s = raw_input('please input node:\\n')\nif s == '#':\n node = None\nelse:\n node.val = s\n node.lchild = Node()\n self.create_tree(node.lchild)\n node.rchild = Node()\n self.create_tree(node.rchild)",
"root = Node()\nself.create_tree(root)\nreturn root"
] | <|body_start_0|>
s = raw_input('please input node:\n')
if s == '#':
node = None
else:
node.val = s
node.lchild = Node()
self.create_tree(node.lchild)
node.rchild = Node()
self.create_tree(node.rchild)
<|end_body_0|>
<|body_... | Tree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tree:
def create_tree(self, node):
"""构建树 :param node: :return: 当结点的两个孩子都是None时,停止递归,因为孩子为None的话,孩子的孩子肯定不能创建"""
<|body_0|>
def get_tree_root(self):
"""返回树的root结点 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = raw_input('please input no... | stack_v2_sparse_classes_75kplus_train_000353 | 906 | no_license | [
{
"docstring": "构建树 :param node: :return: 当结点的两个孩子都是None时,停止递归,因为孩子为None的话,孩子的孩子肯定不能创建",
"name": "create_tree",
"signature": "def create_tree(self, node)"
},
{
"docstring": "返回树的root结点 :return:",
"name": "get_tree_root",
"signature": "def get_tree_root(self)"
}
] | 2 | null | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def create_tree(self, node): 构建树 :param node: :return: 当结点的两个孩子都是None时,停止递归,因为孩子为None的话,孩子的孩子肯定不能创建
- def get_tree_root(self): 返回树的root结点 :return: | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def create_tree(self, node): 构建树 :param node: :return: 当结点的两个孩子都是None时,停止递归,因为孩子为None的话,孩子的孩子肯定不能创建
- def get_tree_root(self): 返回树的root结点 :return:
<|skeleton|>
class Tree:
def crea... | 0a5038a2e8de76a59864bcad720bd2f581d50d0f | <|skeleton|>
class Tree:
def create_tree(self, node):
"""构建树 :param node: :return: 当结点的两个孩子都是None时,停止递归,因为孩子为None的话,孩子的孩子肯定不能创建"""
<|body_0|>
def get_tree_root(self):
"""返回树的root结点 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tree:
def create_tree(self, node):
"""构建树 :param node: :return: 当结点的两个孩子都是None时,停止递归,因为孩子为None的话,孩子的孩子肯定不能创建"""
s = raw_input('please input node:\n')
if s == '#':
node = None
else:
node.val = s
node.lchild = Node()
self.create_tre... | the_stack_v2_python_sparse | DataStructures/tree/binarytree/Tree.py | huiqinwang/ReviewProject | train | 0 | |
c0b809a7c247a1f39c762fc62e0d4f045f528300 | [
"super(GroupEmbedding, self).__init__()\nself.user_embedding = nn.Embedding(user_num + 1, embedding_size)\nself.item_embedding = nn.Embedding(item_num + 1, embedding_size)\nself.user_attention = nn.Sequential(nn.Linear(embedding_size, embedding_size), nn.ReLU(), nn.Linear(embedding_size, 1))\nself.user_softmax = nn... | <|body_start_0|>
super(GroupEmbedding, self).__init__()
self.user_embedding = nn.Embedding(user_num + 1, embedding_size)
self.item_embedding = nn.Embedding(item_num + 1, embedding_size)
self.user_attention = nn.Sequential(nn.Linear(embedding_size, embedding_size), nn.ReLU(), nn.Linear(em... | Embedding Network | GroupEmbedding | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupEmbedding:
"""Embedding Network"""
def __init__(self, embedding_size: int, user_num: int, item_num: int):
"""Initialize Embedding :param embedding_size: embedding size :param user_num: number of users :param item_num: number of items"""
<|body_0|>
def forward(self, ... | stack_v2_sparse_classes_75kplus_train_000354 | 4,654 | permissive | [
{
"docstring": "Initialize Embedding :param embedding_size: embedding size :param user_num: number of users :param item_num: number of items",
"name": "__init__",
"signature": "def __init__(self, embedding_size: int, user_num: int, item_num: int)"
},
{
"docstring": "Forward :param group_members:... | 2 | stack_v2_sparse_classes_30k_train_029610 | Implement the Python class `GroupEmbedding` described below.
Class description:
Embedding Network
Method signatures and docstrings:
- def __init__(self, embedding_size: int, user_num: int, item_num: int): Initialize Embedding :param embedding_size: embedding size :param user_num: number of users :param item_num: numb... | Implement the Python class `GroupEmbedding` described below.
Class description:
Embedding Network
Method signatures and docstrings:
- def __init__(self, embedding_size: int, user_num: int, item_num: int): Initialize Embedding :param embedding_size: embedding size :param user_num: number of users :param item_num: numb... | 3bf673bb7980a2ba972241b0ba4bae7ca3af1870 | <|skeleton|>
class GroupEmbedding:
"""Embedding Network"""
def __init__(self, embedding_size: int, user_num: int, item_num: int):
"""Initialize Embedding :param embedding_size: embedding size :param user_num: number of users :param item_num: number of items"""
<|body_0|>
def forward(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupEmbedding:
"""Embedding Network"""
def __init__(self, embedding_size: int, user_num: int, item_num: int):
"""Initialize Embedding :param embedding_size: embedding size :param user_num: number of users :param item_num: number of items"""
super(GroupEmbedding, self).__init__()
... | the_stack_v2_python_sparse | recohut/models/embedding.py | recohut/recohut | train | 2 |
0af6d88466e9e15a43cd03e9e336223f53548255 | [
"if not nums:\n return []\nnums.sort()\ndp = [None] * len(nums)\ndp[0] = [nums[0]]\nfor i in range(1, len(nums)):\n max_subset = []\n for j in range(i):\n if nums[i] % nums[j] == 0:\n max_subset = max(max_subset, dp[j][:], key=len)\n max_subset.append(nums[i])\n dp[i] = max_subset\n... | <|body_start_0|>
if not nums:
return []
nums.sort()
dp = [None] * len(nums)
dp[0] = [nums[0]]
for i in range(1, len(nums)):
max_subset = []
for j in range(i):
if nums[i] % nums[j] == 0:
max_subset = max(max_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
"""Dynamic Programming: O(N^2)"""
<|body_0|>
def largest_divisible_subset(self, nums):
"""Better: O(N * sqrt(x)) where x is the number in nums"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_000355 | 1,555 | no_license | [
{
"docstring": "Dynamic Programming: O(N^2)",
"name": "largestDivisibleSubset",
"signature": "def largestDivisibleSubset(self, nums: List[int]) -> List[int]"
},
{
"docstring": "Better: O(N * sqrt(x)) where x is the number in nums",
"name": "largest_divisible_subset",
"signature": "def la... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestDivisibleSubset(self, nums: List[int]) -> List[int]: Dynamic Programming: O(N^2)
- def largest_divisible_subset(self, nums): Better: O(N * sqrt(x)) where x is the numb... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestDivisibleSubset(self, nums: List[int]) -> List[int]: Dynamic Programming: O(N^2)
- def largest_divisible_subset(self, nums): Better: O(N * sqrt(x)) where x is the numb... | 33252434f8d90b46fd2de07e257842331dcd81a8 | <|skeleton|>
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
"""Dynamic Programming: O(N^2)"""
<|body_0|>
def largest_divisible_subset(self, nums):
"""Better: O(N * sqrt(x)) where x is the number in nums"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
"""Dynamic Programming: O(N^2)"""
if not nums:
return []
nums.sort()
dp = [None] * len(nums)
dp[0] = [nums[0]]
for i in range(1, len(nums)):
max_subset = []
... | the_stack_v2_python_sparse | main/leetcode/368.py | dawnonme/Eureka | train | 0 | |
25a943b1f72d4e9d5ca6ef0f986885f3cfeaa44a | [
"parser.add_argument('source', help='Cloud SQL instance ID of the source.')\nparser.add_argument('destination', help='Cloud SQL instance ID of the clone.')\nparser.add_argument('--bin-log-file-name', required=False, help='Binary log file for the source instance.')\nparser.add_argument('--bin-log-position', type=int... | <|body_start_0|>
parser.add_argument('source', help='Cloud SQL instance ID of the source.')
parser.add_argument('destination', help='Cloud SQL instance ID of the clone.')
parser.add_argument('--bin-log-file-name', required=False, help='Binary log file for the source instance.')
parser.ad... | Clones a Cloud SQL instance. | Clone | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clone:
"""Clones a Cloud SQL instance."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed."""
... | stack_v2_sparse_classes_75kplus_train_000356 | 4,897 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_029530 | Implement the Python class `Clone` described below.
Class description:
Clones a Cloud SQL instance.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line a... | Implement the Python class `Clone` described below.
Class description:
Clones a Cloud SQL instance.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line a... | 90d87b2adb1eab7f218b075886aa620d8d6eeedb | <|skeleton|>
class Clone:
"""Clones a Cloud SQL instance."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Clone:
"""Clones a Cloud SQL instance."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed."""
parser... | the_stack_v2_python_sparse | old/google-cloud-sdk/lib/googlecloudsdk/sql/tools/instances/clone.py | altock/dev | train | 0 |
988eb1d28445be2a0215a4344594690ea17108ff | [
"if task not in self.manager.user_config.get('tasks', {}):\n raise NotFoundError(f'task `{task}` not found')\nreturn jsonify({'name': task, 'config': self.manager.user_config['tasks'][task]})",
"data = request.json\nnew_task_name = data['name']\nif task not in self.manager.user_config.get('tasks', {}):\n ra... | <|body_start_0|>
if task not in self.manager.user_config.get('tasks', {}):
raise NotFoundError(f'task `{task}` not found')
return jsonify({'name': task, 'config': self.manager.user_config['tasks'][task]})
<|end_body_0|>
<|body_start_1|>
data = request.json
new_task_name = da... | TaskAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskAPI:
def get(self, task, session: Session=None) -> Response:
"""Get task config"""
<|body_0|>
def put(self, task, session: Session=None) -> Response:
"""Update tasks config"""
<|body_1|>
def delete(self, task, session: Session=None) -> Response:
... | stack_v2_sparse_classes_75kplus_train_000357 | 22,039 | permissive | [
{
"docstring": "Get task config",
"name": "get",
"signature": "def get(self, task, session: Session=None) -> Response"
},
{
"docstring": "Update tasks config",
"name": "put",
"signature": "def put(self, task, session: Session=None) -> Response"
},
{
"docstring": "Delete a task",
... | 3 | null | Implement the Python class `TaskAPI` described below.
Class description:
Implement the TaskAPI class.
Method signatures and docstrings:
- def get(self, task, session: Session=None) -> Response: Get task config
- def put(self, task, session: Session=None) -> Response: Update tasks config
- def delete(self, task, sessi... | Implement the Python class `TaskAPI` described below.
Class description:
Implement the TaskAPI class.
Method signatures and docstrings:
- def get(self, task, session: Session=None) -> Response: Get task config
- def put(self, task, session: Session=None) -> Response: Update tasks config
- def delete(self, task, sessi... | 2b7e8314d103c94cf4552bd0152699eeca0ad159 | <|skeleton|>
class TaskAPI:
def get(self, task, session: Session=None) -> Response:
"""Get task config"""
<|body_0|>
def put(self, task, session: Session=None) -> Response:
"""Update tasks config"""
<|body_1|>
def delete(self, task, session: Session=None) -> Response:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskAPI:
def get(self, task, session: Session=None) -> Response:
"""Get task config"""
if task not in self.manager.user_config.get('tasks', {}):
raise NotFoundError(f'task `{task}` not found')
return jsonify({'name': task, 'config': self.manager.user_config['tasks'][task]})... | the_stack_v2_python_sparse | flexget/api/core/tasks.py | BrutuZ/Flexget | train | 1 | |
158a4170808b14d6834fa11fd09f319ba613d1fe | [
"self.persons = persons\nself.times = times\nself.length = len(self.persons)\nmapping = collections.defaultdict(int)\nself.status = []\nprev = [-1, 0]\nfor index, person in enumerate(self.persons):\n mapping[person] += 1\n if mapping[person] > prev[1]:\n self.status.append(person)\n prev[0], pre... | <|body_start_0|>
self.persons = persons
self.times = times
self.length = len(self.persons)
mapping = collections.defaultdict(int)
self.status = []
prev = [-1, 0]
for index, person in enumerate(self.persons):
mapping[person] += 1
if mapping[... | TopVotedCandidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.persons = persons
self.t... | stack_v2_sparse_classes_75kplus_train_000358 | 1,436 | no_license | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021224 | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
self.persons = persons
self.times = times
self.length = len(self.persons)
mapping = collections.defaultdict(int)
self.status = []
prev = [-1, 0]
... | the_stack_v2_python_sparse | problems/N911_Online_Election.py | wan-catherine/Leetcode | train | 5 | |
9e4737cc949cf4091ca46a294bfa7654fd877171 | [
"self.state = State(State.READY)\nself.process = None\nself.quantum = None\nself.max_time = max_time\nself.MAX_TIME_REF = deepcopy(self.max_time)",
"logger.info(f'SEtting new process for cpu to P{process.id} with a length of cpu_bursts of {len(process.cpu_bursts)} Quantum{process.cpu_bursts[0]}')\nself.state = St... | <|body_start_0|>
self.state = State(State.READY)
self.process = None
self.quantum = None
self.max_time = max_time
self.MAX_TIME_REF = deepcopy(self.max_time)
<|end_body_0|>
<|body_start_1|>
logger.info(f'SEtting new process for cpu to P{process.id} with a length of cpu_b... | :Class: CPU :Author: Buddy Smith :Description: Act as a CPU in a computer scheduling simulation :Remarks: None :Data Members: state: State Object (Enum) : process: Current process Object : Quantum: current cpu burst of process object : max_time: time quantum for Round Robin, default sys.maxsize : MAX_TIME_REF: constant... | CPU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPU:
""":Class: CPU :Author: Buddy Smith :Description: Act as a CPU in a computer scheduling simulation :Remarks: None :Data Members: state: State Object (Enum) : process: Current process Object : Quantum: current cpu burst of process object : max_time: time quantum for Round Robin, default sys.m... | stack_v2_sparse_classes_75kplus_train_000359 | 6,644 | no_license | [
{
"docstring": ":method constructor :params max_time: max_time quantum :description sets default values of class, state is set to ready : max_time is set, default max_time i sys.maxsize :returns na :todo: none",
"name": "__init__",
"signature": "def __init__(self, max_time)"
},
{
"docstring": ":... | 5 | null | Implement the Python class `CPU` described below.
Class description:
:Class: CPU :Author: Buddy Smith :Description: Act as a CPU in a computer scheduling simulation :Remarks: None :Data Members: state: State Object (Enum) : process: Current process Object : Quantum: current cpu burst of process object : max_time: time... | Implement the Python class `CPU` described below.
Class description:
:Class: CPU :Author: Buddy Smith :Description: Act as a CPU in a computer scheduling simulation :Remarks: None :Data Members: state: State Object (Enum) : process: Current process Object : Quantum: current cpu burst of process object : max_time: time... | 84e5304219a6d75b2b6bb1046b0a0acb2af972fb | <|skeleton|>
class CPU:
""":Class: CPU :Author: Buddy Smith :Description: Act as a CPU in a computer scheduling simulation :Remarks: None :Data Members: state: State Object (Enum) : process: Current process Object : Quantum: current cpu burst of process object : max_time: time quantum for Round Robin, default sys.m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CPU:
""":Class: CPU :Author: Buddy Smith :Description: Act as a CPU in a computer scheduling simulation :Remarks: None :Data Members: state: State Object (Enum) : process: Current process Object : Quantum: current cpu burst of process object : max_time: time quantum for Round Robin, default sys.maxsize : MAX_... | the_stack_v2_python_sparse | Assignments/A06/CPU.py | buddyjasmith/5143-OS-Smith | train | 0 |
639cfbbac0c27453260a1f1ded6aecf1805c113f | [
"super().__init__()\nself.batch_size = 0\nself.nr_input_channels = 0\nself.input_size_y = 0\nself.input_size_x = 0",
"self.original_shape = input_tensor.shape\nif len(self.original_shape) == 4:\n self.batch_size = self.original_shape[0]\n self.nr_input_channels = self.original_shape[1]\n self.input_size_... | <|body_start_0|>
super().__init__()
self.batch_size = 0
self.nr_input_channels = 0
self.input_size_y = 0
self.input_size_x = 0
<|end_body_0|>
<|body_start_1|>
self.original_shape = input_tensor.shape
if len(self.original_shape) == 4:
self.batch_size =... | Flatten | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flatten:
def __init__(self):
"""Constructor for a flatten layer object."""
<|body_0|>
def forward(self, input_tensor):
"""Flatten the input tensor for each batch to a 1D linear representation. :param input_tensor: Originally shaped input tensor. :return: Linearized b... | stack_v2_sparse_classes_75kplus_train_000360 | 2,961 | no_license | [
{
"docstring": "Constructor for a flatten layer object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Flatten the input tensor for each batch to a 1D linear representation. :param input_tensor: Originally shaped input tensor. :return: Linearized batch-wise representa... | 3 | stack_v2_sparse_classes_30k_train_028623 | Implement the Python class `Flatten` described below.
Class description:
Implement the Flatten class.
Method signatures and docstrings:
- def __init__(self): Constructor for a flatten layer object.
- def forward(self, input_tensor): Flatten the input tensor for each batch to a 1D linear representation. :param input_t... | Implement the Python class `Flatten` described below.
Class description:
Implement the Flatten class.
Method signatures and docstrings:
- def __init__(self): Constructor for a flatten layer object.
- def forward(self, input_tensor): Flatten the input tensor for each batch to a 1D linear representation. :param input_t... | 1d2d990c75bb7977d76430a50a31bd9ce31da37d | <|skeleton|>
class Flatten:
def __init__(self):
"""Constructor for a flatten layer object."""
<|body_0|>
def forward(self, input_tensor):
"""Flatten the input tensor for each batch to a 1D linear representation. :param input_tensor: Originally shaped input tensor. :return: Linearized b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Flatten:
def __init__(self):
"""Constructor for a flatten layer object."""
super().__init__()
self.batch_size = 0
self.nr_input_channels = 0
self.input_size_y = 0
self.input_size_x = 0
def forward(self, input_tensor):
"""Flatten the input tensor for... | the_stack_v2_python_sparse | Exercise 3/src_to_implement/Layers/Flatten.py | StefanFischer/Deep-Learning-Framework | train | 0 | |
9bb15028234d216c3fbbb22d843d4d08561c45a3 | [
"Parametre.__init__(self, 'actuelles', 'current')\nself.tronquer = True\nself.aide_courte = 'affiche vos locations'\nself.aide_longue = \"Cette commande vous permet de consulter la liste des chambres que vous louez actuellement ainsi que la durée restante avant l'expiration de la location, pour chacune. Notez que l... | <|body_start_0|>
Parametre.__init__(self, 'actuelles', 'current')
self.tronquer = True
self.aide_courte = 'affiche vos locations'
self.aide_longue = "Cette commande vous permet de consulter la liste des chambres que vous louez actuellement ainsi que la durée restante avant l'expiration d... | Commande 'louer actuelles' | PrmActuelles | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmActuelles:
"""Commande 'louer actuelles'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_000361 | 3,385 | permissive | [
{
"docstring": "Constructeur du paramètre.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmActuelles` described below.
Class description:
Commande 'louer actuelles'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande | Implement the Python class `PrmActuelles` described below.
Class description:
Commande 'louer actuelles'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande
<|skeleton|>
class PrmActuelles:
"""Co... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmActuelles:
"""Commande 'louer actuelles'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmActuelles:
"""Commande 'louer actuelles'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, 'actuelles', 'current')
self.tronquer = True
self.aide_courte = 'affiche vos locations'
self.aide_longue = "Cette commande vous permet de co... | the_stack_v2_python_sparse | src/secondaires/auberge/commandes/louer/actuelles.py | vincent-lg/tsunami | train | 5 |
39c6d1d1739abb4e182a12d3bdba9aa0891ad12a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EnterpriseCodeSigningCertificate()",
"from .certificate_status import CertificateStatus\nfrom .entity import Entity\nfrom .certificate_status import CertificateStatus\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EnterpriseCodeSigningCertificate()
<|end_body_0|>
<|body_start_1|>
from .certificate_status import CertificateStatus
from .entity import Entity
from .certificate_status import Ce... | EnterpriseCodeSigningCertificate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnterpriseCodeSigningCertificate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnterpriseCodeSigningCertificate:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_75kplus_train_000362 | 5,950 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: EnterpriseCodeSigningCertificate",
"name": "create_from_discriminator_value",
"signature": "def create_from_... | 3 | stack_v2_sparse_classes_30k_train_005305 | Implement the Python class `EnterpriseCodeSigningCertificate` described below.
Class description:
Implement the EnterpriseCodeSigningCertificate class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnterpriseCodeSigningCertificate: Creates a new insta... | Implement the Python class `EnterpriseCodeSigningCertificate` described below.
Class description:
Implement the EnterpriseCodeSigningCertificate class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnterpriseCodeSigningCertificate: Creates a new insta... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EnterpriseCodeSigningCertificate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnterpriseCodeSigningCertificate:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnterpriseCodeSigningCertificate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnterpriseCodeSigningCertificate:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | the_stack_v2_python_sparse | msgraph/generated/models/enterprise_code_signing_certificate.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
9416a281915edd0e510d0de1aebb4aa0bcdebe0c | [
"str = ''\nif strs == []:\n return str\nfor j in range(0, len(strs[0])):\n letter = strs[0][j]\n index = 0\n for i in range(1, len(strs)):\n word_length = len(strs[i])\n if j < word_length:\n if strs[i][j] == letter:\n index += 1\n if index == len(strs) - 1:\n ... | <|body_start_0|>
str = ''
if strs == []:
return str
for j in range(0, len(strs[0])):
letter = strs[0][j]
index = 0
for i in range(1, len(strs)):
word_length = len(strs[i])
if j < word_length:
if s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix_last(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
def longestCommonPrefix1(self, strs):
""":type strs: Li... | stack_v2_sparse_classes_75kplus_train_000363 | 1,997 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix_last",
"signature": "def longestCommonPrefix_last(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
... | 3 | stack_v2_sparse_classes_30k_train_054044 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix_last(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix1(se... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix_last(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix1(se... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def longestCommonPrefix_last(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
def longestCommonPrefix1(self, strs):
""":type strs: Li... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonPrefix_last(self, strs):
""":type strs: List[str] :rtype: str"""
str = ''
if strs == []:
return str
for j in range(0, len(strs[0])):
letter = strs[0][j]
index = 0
for i in range(1, len(strs)):
... | the_stack_v2_python_sparse | LeetCode/String/14_longest_common_prefix.py | XyK0907/for_work | train | 0 | |
f0216d2a8c7409f061f35036ea94e914d90efe20 | [
"user = UserModel.get_by_username(username)\nif user:\n return user.as_dict()\nreturn ({'message': 'user not found'}, 404)",
"data = User.parser.parse_args()\nuser = UserModel.get_by_username(username)\nif user:\n return {'message': 'user already exist'}\nuser = UserModel(username=username, email=data['emai... | <|body_start_0|>
user = UserModel.get_by_username(username)
if user:
return user.as_dict()
return ({'message': 'user not found'}, 404)
<|end_body_0|>
<|body_start_1|>
data = User.parser.parse_args()
user = UserModel.get_by_username(username)
if user:
... | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def get(self, username):
"""获取用户详细信息"""
<|body_0|>
def post(self, username):
"""创建用户"""
<|body_1|>
def delete(self, username):
"""删除用户"""
<|body_2|>
def put(self, username):
"""更新用户"""
<|body_3|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_000364 | 2,681 | no_license | [
{
"docstring": "获取用户详细信息",
"name": "get",
"signature": "def get(self, username)"
},
{
"docstring": "创建用户",
"name": "post",
"signature": "def post(self, username)"
},
{
"docstring": "删除用户",
"name": "delete",
"signature": "def delete(self, username)"
},
{
"docstring... | 4 | null | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def get(self, username): 获取用户详细信息
- def post(self, username): 创建用户
- def delete(self, username): 删除用户
- def put(self, username): 更新用户 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def get(self, username): 获取用户详细信息
- def post(self, username): 创建用户
- def delete(self, username): 删除用户
- def put(self, username): 更新用户
<|skeleton|>
class User:
def get(self, usernam... | ac248203b945281fb0d616d42afa6a66b0d4d065 | <|skeleton|>
class User:
def get(self, username):
"""获取用户详细信息"""
<|body_0|>
def post(self, username):
"""创建用户"""
<|body_1|>
def delete(self, username):
"""删除用户"""
<|body_2|>
def put(self, username):
"""更新用户"""
<|body_3|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class User:
def get(self, username):
"""获取用户详细信息"""
user = UserModel.get_by_username(username)
if user:
return user.as_dict()
return ({'message': 'user not found'}, 404)
def post(self, username):
"""创建用户"""
data = User.parser.parse_args()
user... | the_stack_v2_python_sparse | flask-rest-demo/restdemo/resource/user.py | ssgwy/learnweb | train | 1 | |
76782d495114de1f1b7006976adf26f57a44c34d | [
"Bullet.__init__(self, lifetime, alpha, beta, x, y)\nself.r = r\nself.color = color",
"self.ax = -self.alpha * self.vx - self.beta * self.vx * abs(self.vx)\nself.ay = self.g - self.alpha * self.vy - self.beta * self.vy * abs(self.vy)\nself.vx += self.ax / self.fps\nself.vy += self.ay / self.fps\nif self.r < self.... | <|body_start_0|>
Bullet.__init__(self, lifetime, alpha, beta, x, y)
self.r = r
self.color = color
<|end_body_0|>
<|body_start_1|>
self.ax = -self.alpha * self.vx - self.beta * self.vx * abs(self.vx)
self.ay = self.g - self.alpha * self.vy - self.beta * self.vy * abs(self.vy)
... | Ball | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ball:
def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta):
"""Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av ... | stack_v2_sparse_classes_75kplus_train_000365 | 9,588 | no_license | [
{
"docstring": "Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param beta: параметр b в формуле силы трения F = -av - bv^2 :param r: радиус мяча :param x: начальная координата ц... | 3 | stack_v2_sparse_classes_30k_train_050116 | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta): Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param ... | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta): Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param ... | 19d00443e953a487e762676d6682579a537f55f0 | <|skeleton|>
class Ball:
def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta):
"""Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ball:
def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta):
"""Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param ... | the_stack_v2_python_sparse | Лаба 8/modules/bullets.py | VladimirMolunov/molunov_infa_2021 | train | 0 | |
df878db7dd510848d81e27e3642e20ab691b3cc3 | [
"self.config = {}\nself.config['db'] = {}\nself.config['db']['host'] = 'web40'\nself.config['db']['port'] = 27017\nself.config['db']['db'] = 'd4dchallenge'\nself.config['db']['collection'] = 'traces'\nself.traces = self.__get_collection(self.config)",
"connection = Connection(config['db']['host'], config['db']['p... | <|body_start_0|>
self.config = {}
self.config['db'] = {}
self.config['db']['host'] = 'web40'
self.config['db']['port'] = 27017
self.config['db']['db'] = 'd4dchallenge'
self.config['db']['collection'] = 'traces'
self.traces = self.__get_collection(self.config)
<|en... | SpaceTemporalModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceTemporalModel:
def __init__(self):
"""Load and retieve collection pointer from MongoDB"""
<|body_0|>
def __get_collection(self, config):
"""Return collection from MongoDB with a specific configuration"""
<|body_1|>
def retieve_data_and_create_model(... | stack_v2_sparse_classes_75kplus_train_000366 | 5,480 | no_license | [
{
"docstring": "Load and retieve collection pointer from MongoDB",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return collection from MongoDB with a specific configuration",
"name": "__get_collection",
"signature": "def __get_collection(self, config)"
},
... | 5 | stack_v2_sparse_classes_30k_train_048272 | Implement the Python class `SpaceTemporalModel` described below.
Class description:
Implement the SpaceTemporalModel class.
Method signatures and docstrings:
- def __init__(self): Load and retieve collection pointer from MongoDB
- def __get_collection(self, config): Return collection from MongoDB with a specific conf... | Implement the Python class `SpaceTemporalModel` described below.
Class description:
Implement the SpaceTemporalModel class.
Method signatures and docstrings:
- def __init__(self): Load and retieve collection pointer from MongoDB
- def __get_collection(self, config): Return collection from MongoDB with a specific conf... | 86ebaf8382327d4e982916fc3bf83b189ecdb138 | <|skeleton|>
class SpaceTemporalModel:
def __init__(self):
"""Load and retieve collection pointer from MongoDB"""
<|body_0|>
def __get_collection(self, config):
"""Return collection from MongoDB with a specific configuration"""
<|body_1|>
def retieve_data_and_create_model(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpaceTemporalModel:
def __init__(self):
"""Load and retieve collection pointer from MongoDB"""
self.config = {}
self.config['db'] = {}
self.config['db']['host'] = 'web40'
self.config['db']['port'] = 27017
self.config['db']['db'] = 'd4dchallenge'
self.con... | the_stack_v2_python_sparse | service/space_temporal.py | sjsnjnu/d4d-challenge | train | 0 | |
25895ffe6b55a428c4dc203ffcb9ba5cf9bb50f7 | [
"random.seed()\ncls._sequence_indexes = random.sample(range(partition.num_sequences), num_sequences)\ncls._observer_path = run_dir + constants.OBSERVER_FILE\ncreate_directory(cls._observer_path)\nreturn cls",
"cls._current_epoch = epoch\ncls._current_batch = 0\ncls._current_sequence = 0\ncls._print_epoch()\nretur... | <|body_start_0|>
random.seed()
cls._sequence_indexes = random.sample(range(partition.num_sequences), num_sequences)
cls._observer_path = run_dir + constants.OBSERVER_FILE
create_directory(cls._observer_path)
return cls
<|end_body_0|>
<|body_start_1|>
cls._current_epoch =... | A singleton Observer class for observing and evaluating the predictions made by the network during training. It is a Singleton so that the object doesn't have to be passed around the training functions. | Observer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Observer:
"""A singleton Observer class for observing and evaluating the predictions made by the network during training. It is a Singleton so that the object doesn't have to be passed around the training functions."""
def init(cls, partition: DataPartition, num_sequences: int, run_dir: str)... | stack_v2_sparse_classes_75kplus_train_000367 | 4,738 | permissive | [
{
"docstring": "Figures out which sequences to observe. Does so by randomly selecting num_sequences from all sequences in the partition, and storing their indexes in sequence_indexes. Params: - partition (DataPartition): The data partition containing the sequences - num_sequences (int): The number of sequences ... | 5 | stack_v2_sparse_classes_30k_train_042379 | Implement the Python class `Observer` described below.
Class description:
A singleton Observer class for observing and evaluating the predictions made by the network during training. It is a Singleton so that the object doesn't have to be passed around the training functions.
Method signatures and docstrings:
- def i... | Implement the Python class `Observer` described below.
Class description:
A singleton Observer class for observing and evaluating the predictions made by the network during training. It is a Singleton so that the object doesn't have to be passed around the training functions.
Method signatures and docstrings:
- def i... | 23400d4deb775841a1b8aae2831c09cc043b8263 | <|skeleton|>
class Observer:
"""A singleton Observer class for observing and evaluating the predictions made by the network during training. It is a Singleton so that the object doesn't have to be passed around the training functions."""
def init(cls, partition: DataPartition, num_sequences: int, run_dir: str)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Observer:
"""A singleton Observer class for observing and evaluating the predictions made by the network during training. It is a Singleton so that the object doesn't have to be passed around the training functions."""
def init(cls, partition: DataPartition, num_sequences: int, run_dir: str) -> type:
... | the_stack_v2_python_sparse | tf_rnn/observer.py | ffrankies/tf_rnn | train | 1 |
56372b6003ecaffc555fca403c207cf95e64cf51 | [
"super().__init__()\nself.name = 'PFNLayer'\nself.last_vfe = last_layer\nif not self.last_vfe:\n out_channels = out_channels // 2\nself.units = out_channels\nself.h = height\nself.w = width\nself.z = depth\nif use_norm:\n Linear = change_default_args(bias=False)(nn.Linear)\nelse:\n Linear = change_default_... | <|body_start_0|>
super().__init__()
self.name = 'PFNLayer'
self.last_vfe = last_layer
if not self.last_vfe:
out_channels = out_channels // 2
self.units = out_channels
self.h = height
self.w = width
self.z = depth
if use_norm:
... | PFNLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PFNLayer:
def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False):
"""Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. Thi... | stack_v2_sparse_classes_75kplus_train_000368 | 7,758 | no_license | [
{
"docstring": "Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. This layer performs a similar role as second.pytorch.voxelnet.VFELayer. :param in_channels: <int>. Number of input channels. :param out_... | 2 | stack_v2_sparse_classes_30k_test_002779 | Implement the Python class `PFNLayer` described below.
Class description:
Implement the PFNLayer class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False): Pillar Feature Net Layer. The Pillar Feature Net could be composed... | Implement the Python class `PFNLayer` described below.
Class description:
Implement the PFNLayer class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False): Pillar Feature Net Layer. The Pillar Feature Net could be composed... | 43388efd911feecde588b27a753de353b8e28265 | <|skeleton|>
class PFNLayer:
def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False):
"""Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. Thi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PFNLayer:
def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False):
"""Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. This layer perfor... | the_stack_v2_python_sparse | models/backbones/pointpillars_voxel.py | dragonlong/haoi-pose | train | 0 | |
22fcc0cd69accb362d71f418cc4e41c05f9ee297 | [
"app_label = obj.category._meta.app_label\nmodel_name = obj.category._meta.model_name\nlink = reverse('admin:%s_%s_change' % (app_label, model_name), kwargs={'object_id': obj.category_id})\nreturn format_html(u'<a href=\"%s\">%s</a>' % (link, obj.category))",
"form = super().get_form(request, obj=None, change=Fal... | <|body_start_0|>
app_label = obj.category._meta.app_label
model_name = obj.category._meta.model_name
link = reverse('admin:%s_%s_change' % (app_label, model_name), kwargs={'object_id': obj.category_id})
return format_html(u'<a href="%s">%s</a>' % (link, obj.category))
<|end_body_0|>
<|b... | ArticleAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleAdmin:
def category_link(self, obj):
"""链接到文章所属分类, obj是一个文章对象"""
<|body_0|>
def get_form(self, request, obj=None, change=False, **kwargs):
"""文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class for use in the admin add view."""
<|body_1|>
def get_q... | stack_v2_sparse_classes_75kplus_train_000369 | 10,733 | permissive | [
{
"docstring": "链接到文章所属分类, obj是一个文章对象",
"name": "category_link",
"signature": "def category_link(self, obj)"
},
{
"docstring": "文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class for use in the admin add view.",
"name": "get_form",
"signature": "def get_form(self, request, obj=None, chan... | 5 | stack_v2_sparse_classes_30k_train_054319 | Implement the Python class `ArticleAdmin` described below.
Class description:
Implement the ArticleAdmin class.
Method signatures and docstrings:
- def category_link(self, obj): 链接到文章所属分类, obj是一个文章对象
- def get_form(self, request, obj=None, change=False, **kwargs): 文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class fo... | Implement the Python class `ArticleAdmin` described below.
Class description:
Implement the ArticleAdmin class.
Method signatures and docstrings:
- def category_link(self, obj): 链接到文章所属分类, obj是一个文章对象
- def get_form(self, request, obj=None, change=False, **kwargs): 文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class fo... | 0fcf3709fabeee49874343b3a4ab80582698c466 | <|skeleton|>
class ArticleAdmin:
def category_link(self, obj):
"""链接到文章所属分类, obj是一个文章对象"""
<|body_0|>
def get_form(self, request, obj=None, change=False, **kwargs):
"""文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class for use in the admin add view."""
<|body_1|>
def get_q... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArticleAdmin:
def category_link(self, obj):
"""链接到文章所属分类, obj是一个文章对象"""
app_label = obj.category._meta.app_label
model_name = obj.category._meta.model_name
link = reverse('admin:%s_%s_change' % (app_label, model_name), kwargs={'object_id': obj.category_id})
return forma... | the_stack_v2_python_sparse | blog/admin.py | enjoy-binbin/Django-blog | train | 113 | |
17180925069fc4ed68eb2ef0415c0286b12ce395 | [
"self._attr_name = f'{name} {SENSOR_TYPES[sensor_type][0]}'\nself.bme680_client = bme680_client\nself.temp_unit = temp_unit\nself.type = sensor_type\nself._attr_unit_of_measurement = SENSOR_TYPES[sensor_type][1]\nself._attr_device_class = SENSOR_TYPES[sensor_type][2]",
"await self.hass.async_add_executor_job(self... | <|body_start_0|>
self._attr_name = f'{name} {SENSOR_TYPES[sensor_type][0]}'
self.bme680_client = bme680_client
self.temp_unit = temp_unit
self.type = sensor_type
self._attr_unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._attr_device_class = SENSOR_TYPES[sensor_ty... | Implementation of the BME680 sensor. | BME680Sensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BME680Sensor:
"""Implementation of the BME680 sensor."""
def __init__(self, bme680_client, sensor_type, temp_unit, name):
"""Initialize the sensor."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the BME680 and update the states."""
... | stack_v2_sparse_classes_75kplus_train_000370 | 13,136 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, bme680_client, sensor_type, temp_unit, name)"
},
{
"docstring": "Get the latest data from the BME680 and update the states.",
"name": "async_update",
"signature": "async def async_update(self)"
... | 2 | stack_v2_sparse_classes_30k_train_003695 | Implement the Python class `BME680Sensor` described below.
Class description:
Implementation of the BME680 sensor.
Method signatures and docstrings:
- def __init__(self, bme680_client, sensor_type, temp_unit, name): Initialize the sensor.
- async def async_update(self): Get the latest data from the BME680 and update ... | Implement the Python class `BME680Sensor` described below.
Class description:
Implementation of the BME680 sensor.
Method signatures and docstrings:
- def __init__(self, bme680_client, sensor_type, temp_unit, name): Initialize the sensor.
- async def async_update(self): Get the latest data from the BME680 and update ... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class BME680Sensor:
"""Implementation of the BME680 sensor."""
def __init__(self, bme680_client, sensor_type, temp_unit, name):
"""Initialize the sensor."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the BME680 and update the states."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BME680Sensor:
"""Implementation of the BME680 sensor."""
def __init__(self, bme680_client, sensor_type, temp_unit, name):
"""Initialize the sensor."""
self._attr_name = f'{name} {SENSOR_TYPES[sensor_type][0]}'
self.bme680_client = bme680_client
self.temp_unit = temp_unit
... | the_stack_v2_python_sparse | homeassistant/components/bme680/sensor.py | BenWoodford/home-assistant | train | 11 |
5ca2838548094eff767f1163c0eb6c850c503905 | [
"BaseNeo.__init__(self, name=name, file_origin=file_origin, description=description, **annotations)\nself.file_datetime = file_datetime\nself.rec_datetime = rec_datetime\nself.index = index\nself.segments = []\nself.recordingchannelgroups = []",
"units = []\nfor rcg in self.recordingchannelgroups:\n for unit i... | <|body_start_0|>
BaseNeo.__init__(self, name=name, file_origin=file_origin, description=description, **annotations)
self.file_datetime = file_datetime
self.rec_datetime = rec_datetime
self.index = index
self.segments = []
self.recordingchannelgroups = []
<|end_body_0|>
<... | Main container for data. Main container gathering all the data, whether discrete or continous, for a given recording session. A block is not necessarily temporally homogeneous, in contrast to Segment. *Usage*:: >>> from neo.core import (Block, Segment, RecordingChannelGroup, ... AnalogSignalArray) >>> from quantities i... | Block | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Block:
"""Main container for data. Main container gathering all the data, whether discrete or continous, for a given recording session. A block is not necessarily temporally homogeneous, in contrast to Segment. *Usage*:: >>> from neo.core import (Block, Segment, RecordingChannelGroup, ... AnalogS... | stack_v2_sparse_classes_75kplus_train_000371 | 6,111 | no_license | [
{
"docstring": "Initalize a new :class:`Block` instance.",
"name": "__init__",
"signature": "def __init__(self, name=None, description=None, file_origin=None, file_datetime=None, rec_datetime=None, index=None, **annotations)"
},
{
"docstring": "Return a list of all :class:`Unit` objects in the :... | 5 | stack_v2_sparse_classes_30k_train_034187 | Implement the Python class `Block` described below.
Class description:
Main container for data. Main container gathering all the data, whether discrete or continous, for a given recording session. A block is not necessarily temporally homogeneous, in contrast to Segment. *Usage*:: >>> from neo.core import (Block, Segm... | Implement the Python class `Block` described below.
Class description:
Main container for data. Main container gathering all the data, whether discrete or continous, for a given recording session. A block is not necessarily temporally homogeneous, in contrast to Segment. *Usage*:: >>> from neo.core import (Block, Segm... | 4a942857f6756ee86ec9d36a2b01ff755227d36a | <|skeleton|>
class Block:
"""Main container for data. Main container gathering all the data, whether discrete or continous, for a given recording session. A block is not necessarily temporally homogeneous, in contrast to Segment. *Usage*:: >>> from neo.core import (Block, Segment, RecordingChannelGroup, ... AnalogS... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Block:
"""Main container for data. Main container gathering all the data, whether discrete or continous, for a given recording session. A block is not necessarily temporally homogeneous, in contrast to Segment. *Usage*:: >>> from neo.core import (Block, Segment, RecordingChannelGroup, ... AnalogSignalArray) >... | the_stack_v2_python_sparse | flytracker_tethered/muscle_analysis/neo/core/block.py | FlyRanch/flycity | train | 0 |
f9c5bcea20a8d0bdd41c3c6b3dbd4eb347316576 | [
"super().__init__()\nself.linear = LinearPolicy(inp_n, hidden_size, hidden_size, num_layers - 1, activation_fn)\nif num_layers > 1:\n self.linear = nn.Sequential(self.linear, activation_fn())\n last_in_n = hidden_size\nelse:\n last_in_n = inp_n\nself.mean = nn.Linear(last_in_n, out_n)\nself.log_std = nn.Li... | <|body_start_0|>
super().__init__()
self.linear = LinearPolicy(inp_n, hidden_size, hidden_size, num_layers - 1, activation_fn)
if num_layers > 1:
self.linear = nn.Sequential(self.linear, activation_fn())
last_in_n = hidden_size
else:
last_in_n = inp_n
... | A simple gaussian policy. | GaussianPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianPolicy:
"""A simple gaussian policy."""
def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module):
"""Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the n... | stack_v2_sparse_classes_75kplus_train_000372 | 6,947 | permissive | [
{
"docstring": "Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the network. hidden_size: The number of units in each hidden layer. num_layers: The number of layers before the gaussian layer. activation_fn: The activation function in bet... | 3 | stack_v2_sparse_classes_30k_val_000715 | Implement the Python class `GaussianPolicy` described below.
Class description:
A simple gaussian policy.
Method signatures and docstrings:
- def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): Creates the gaussian policy. Args: inp_n: The number of input units to ... | Implement the Python class `GaussianPolicy` described below.
Class description:
A simple gaussian policy.
Method signatures and docstrings:
- def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): Creates the gaussian policy. Args: inp_n: The number of input units to ... | cde3be1c69bfd76fe4a78fa529e851d0a78318c7 | <|skeleton|>
class GaussianPolicy:
"""A simple gaussian policy."""
def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module):
"""Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianPolicy:
"""A simple gaussian policy."""
def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module):
"""Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the network. hidde... | the_stack_v2_python_sparse | hlrl/torch/policies/distribution.py | Chainso/HLRL | train | 3 |
e37c7a2b403a5ea08a4c4dca7671bbb891921288 | [
"super(SelfOutput, self).__init__()\nself.connecter = nn.Linear(hidden_size, hidden_size)\nself.LayerNorm = LayerNorm(hidden_size)\nself.dropout = nn.Dropout(hidden_dropout_ratio)",
"hidden_states = self.connecter(hidden_states)\nhidden_states = self.dropout(hidden_states)\nhidden_states = self.LayerNorm(hidden_s... | <|body_start_0|>
super(SelfOutput, self).__init__()
self.connecter = nn.Linear(hidden_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout(hidden_dropout_ratio)
<|end_body_0|>
<|body_start_1|>
hidden_states = self.connecter(hidden_states)
... | Self-Output Layer | SelfOutput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfOutput:
"""Self-Output Layer"""
def __init__(self, hidden_size, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, hidden_states, input_tensor):
"""Self-output block"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_75kplus_train_000373 | 12,741 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, hidden_size, hidden_dropout_ratio)"
},
{
"docstring": "Self-output block",
"name": "forward",
"signature": "def forward(self, hidden_states, input_tensor)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001055 | Implement the Python class `SelfOutput` described below.
Class description:
Self-Output Layer
Method signatures and docstrings:
- def __init__(self, hidden_size, hidden_dropout_ratio): Initialization
- def forward(self, hidden_states, input_tensor): Self-output block | Implement the Python class `SelfOutput` described below.
Class description:
Self-Output Layer
Method signatures and docstrings:
- def __init__(self, hidden_size, hidden_dropout_ratio): Initialization
- def forward(self, hidden_states, input_tensor): Self-output block
<|skeleton|>
class SelfOutput:
"""Self-Output... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class SelfOutput:
"""Self-Output Layer"""
def __init__(self, hidden_size, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, hidden_states, input_tensor):
"""Self-output block"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfOutput:
"""Self-Output Layer"""
def __init__(self, hidden_size, hidden_dropout_ratio):
"""Initialization"""
super(SelfOutput, self).__init__()
self.connecter = nn.Linear(hidden_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout... | the_stack_v2_python_sparse | apps/drug_target_interaction/moltrans_dti/double_towers.py | PaddlePaddle/PaddleHelix | train | 771 |
87c93063155c54cd37c43f1f9723f6e8c987b1b4 | [
"self.db_file = DB_FILE\nself.include_param = False\nset_attributes(self, fw_spec, self.default_params)\nfw_env = fw_spec.get('_fw_env', {})\nif 'DISP_DB_FILE' in fw_env:\n self.db_file = fw_env['DISP_DB_FILE']\nself.logger.info(f'Using DISP_DB_FILE={self.db_file}')",
"self._init_parameters(fw_spec)\nstruct_na... | <|body_start_0|>
self.db_file = DB_FILE
self.include_param = False
set_attributes(self, fw_spec, self.default_params)
fw_env = fw_spec.get('_fw_env', {})
if 'DISP_DB_FILE' in fw_env:
self.db_file = fw_env['DISP_DB_FILE']
self.logger.info(f'Using DISP_DB_FILE={... | A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working directory. | DbRecordTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbRecordTask:
"""A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working dir... | stack_v2_sparse_classes_75kplus_train_000374 | 46,142 | permissive | [
{
"docstring": "Initialise the parameters",
"name": "_init_parameters",
"signature": "def _init_parameters(self, fw_spec)"
},
{
"docstring": "Save search results to the database Uses the information in fw_spec to read in the files and store them to the database defined under the 'db_file' entry.... | 2 | stack_v2_sparse_classes_30k_train_025419 | Implement the Python class `DbRecordTask` described below.
Class description:
A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file mus... | Implement the Python class `DbRecordTask` described below.
Class description:
A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file mus... | eb0338f5e326a41ed9aa944ee25c283fa99afa02 | <|skeleton|>
class DbRecordTask:
"""A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working dir... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DbRecordTask:
"""A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working directory."""
... | the_stack_v2_python_sparse | disp/fws/tasks.py | zhubonan/disp | train | 3 |
ef0b2001a6fcc9e6832332aa952d345c674c2056 | [
"super(SpatialNet, self).__init__()\nif arch == 's2vt':\n self.caption_net = S2VTModel(glove_loader, dropout_p, hidden_size, vid_feat_size, max_len)\nelif arch == 's2vt-att':\n self.caption_net = S2VTAttModel(glove_loader, dropout_p, hidden_size, vid_feat_size, max_len)\nelse:\n raise NotImplementedError('... | <|body_start_0|>
super(SpatialNet, self).__init__()
if arch == 's2vt':
self.caption_net = S2VTModel(glove_loader, dropout_p, hidden_size, vid_feat_size, max_len)
elif arch == 's2vt-att':
self.caption_net = S2VTAttModel(glove_loader, dropout_p, hidden_size, vid_feat_size, ... | Spatial attention networks using YOLOv3 as backbone | SpatialNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialNet:
"""Spatial attention networks using YOLOv3 as backbone"""
def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch):
"""Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size... | stack_v2_sparse_classes_75kplus_train_000375 | 5,316 | no_license | [
{
"docstring": "Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size of the intermediate linear layers vid_feat_size: Size of the video features max_len: Max length to rollout arch: video captioning network ['s2vt' | 's2vt-att']",
"name"... | 2 | stack_v2_sparse_classes_30k_train_002165 | Implement the Python class `SpatialNet` described below.
Class description:
Spatial attention networks using YOLOv3 as backbone
Method signatures and docstrings:
- def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch): Args: glove_loader: GLoVe embedding loader dropout_p: Dropout prob... | Implement the Python class `SpatialNet` described below.
Class description:
Spatial attention networks using YOLOv3 as backbone
Method signatures and docstrings:
- def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch): Args: glove_loader: GLoVe embedding loader dropout_p: Dropout prob... | 5f347de39f5583cd043c6f572178da08f7c0de94 | <|skeleton|>
class SpatialNet:
"""Spatial attention networks using YOLOv3 as backbone"""
def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch):
"""Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpatialNet:
"""Spatial attention networks using YOLOv3 as backbone"""
def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch):
"""Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size of the inter... | the_stack_v2_python_sparse | model/SpatialNet.py | AmmieQi/pytorch-video-caption-rationale | train | 0 |
290543662d28f62744074ab7de946c1664201e86 | [
"super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob)])\nch = chans\nfor i in range(num_pool_layers - 1):\n self.down_sample_... | <|body_start_0|>
super().__init__()
self.in_chans = in_chans
self.out_chans = out_chans
self.chans = chans
self.num_pool_layers = num_pool_layers
self.drop_prob = drop_prob
self.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob)])
ch... | PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015. | UnetModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. S... | stack_v2_sparse_classes_75kplus_train_000376 | 11,755 | no_license | [
{
"docstring": "Args: in_chans (int): Number of channels in the input to the U-Net model. out_chans (int): Number of channels in the output to the U-Net model. chans (int): Number of output channels of the first convolution layer. num_pool_layers (int): Number of down-sampling and up-sampling layers. drop_prob ... | 2 | stack_v2_sparse_classes_30k_train_053259 | Implement the Python class `UnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-... | Implement the Python class `UnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-... | 219652c8a08c4f2f682acd9f95a4e1b3fd36b70b | <|skeleton|>
class UnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015... | the_stack_v2_python_sparse | unetLEM/models.py | Bala93/Holistic-MRI-Reconstruction | train | 1 |
ae8a5357d5876fc7d58a95e26c3c1ccc6c59ff53 | [
"expected_checksum, checksum_object = sync_helpers._get_expected_checksum(response, self._get_headers, self.media_url, checksum_type=self.checksum)\nasync for chunk in response.content.iter_chunked(_request_helpers._SINGLE_GET_CHUNK_SIZE):\n self._stream.write(chunk)\n checksum_object.update(chunk)\nif expect... | <|body_start_0|>
expected_checksum, checksum_object = sync_helpers._get_expected_checksum(response, self._get_headers, self.media_url, checksum_type=self.checksum)
async for chunk in response.content.iter_chunked(_request_helpers._SINGLE_GET_CHUNK_SIZE):
self._stream.write(chunk)
... | Helper to manage downloading a raw resource from a Google API. "Slices" of the resource can be retrieved by specifying a range with ``start`` and / or ``end``. However, in typical usage, neither ``start`` nor ``end`` is expected to be provided. Args: media_url (str): The URL containing the media to be downloaded. strea... | RawDownload | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawDownload:
"""Helper to manage downloading a raw resource from a Google API. "Slices" of the resource can be retrieved by specifying a range with ``start`` and / or ``end``. However, in typical usage, neither ``start`` nor ``end`` is expected to be provided. Args: media_url (str): The URL conta... | stack_v2_sparse_classes_75kplus_train_000377 | 18,751 | permissive | [
{
"docstring": "Write response body to a write-able stream. .. note: This method assumes that the ``_stream`` attribute is set on the current download. Args: response (~requests.Response): The HTTP response object. Raises: ~google.resumable_media.common.DataCorruption: If the download's checksum doesn't agree w... | 2 | null | Implement the Python class `RawDownload` described below.
Class description:
Helper to manage downloading a raw resource from a Google API. "Slices" of the resource can be retrieved by specifying a range with ``start`` and / or ``end``. However, in typical usage, neither ``start`` nor ``end`` is expected to be provide... | Implement the Python class `RawDownload` described below.
Class description:
Helper to manage downloading a raw resource from a Google API. "Slices" of the resource can be retrieved by specifying a range with ``start`` and / or ``end``. However, in typical usage, neither ``start`` nor ``end`` is expected to be provide... | a02d814ed75d367f0e4047f1982bb79ea970e181 | <|skeleton|>
class RawDownload:
"""Helper to manage downloading a raw resource from a Google API. "Slices" of the resource can be retrieved by specifying a range with ``start`` and / or ``end``. However, in typical usage, neither ``start`` nor ``end`` is expected to be provided. Args: media_url (str): The URL conta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RawDownload:
"""Helper to manage downloading a raw resource from a Google API. "Slices" of the resource can be retrieved by specifying a range with ``start`` and / or ``end``. However, in typical usage, neither ``start`` nor ``end`` is expected to be provided. Args: media_url (str): The URL containing the med... | the_stack_v2_python_sparse | google/_async_resumable_media/requests/download.py | googleapis/google-resumable-media-python | train | 42 |
10fd2704b5472e5d3b854291e50df67f5b889498 | [
"user_key = request.META.get('HTTP_SESSION_KEY')\nusers = UserWechat.objects.filter(password=user_key)\nif users.exists():\n user = UserWechat.objects.get(password=user_key)\n data = request.data.copy()\n data['user'] = user.id\nelse:\n message = '请登录'\n return Response().errorMessage(error='login re... | <|body_start_0|>
user_key = request.META.get('HTTP_SESSION_KEY')
users = UserWechat.objects.filter(password=user_key)
if users.exists():
user = UserWechat.objects.get(password=user_key)
data = request.data.copy()
data['user'] = user.id
else:
... | join | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class join:
def post(self, request, format=None):
"""报名创建/修改"""
<|body_0|>
def delete(self, request, format=None):
"""报名删除"""
<|body_1|>
def get(self, request, format=None):
"""报名列表查看"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
us... | stack_v2_sparse_classes_75kplus_train_000378 | 18,444 | no_license | [
{
"docstring": "报名创建/修改",
"name": "post",
"signature": "def post(self, request, format=None)"
},
{
"docstring": "报名删除",
"name": "delete",
"signature": "def delete(self, request, format=None)"
},
{
"docstring": "报名列表查看",
"name": "get",
"signature": "def get(self, request, ... | 3 | stack_v2_sparse_classes_30k_train_011828 | Implement the Python class `join` described below.
Class description:
Implement the join class.
Method signatures and docstrings:
- def post(self, request, format=None): 报名创建/修改
- def delete(self, request, format=None): 报名删除
- def get(self, request, format=None): 报名列表查看 | Implement the Python class `join` described below.
Class description:
Implement the join class.
Method signatures and docstrings:
- def post(self, request, format=None): 报名创建/修改
- def delete(self, request, format=None): 报名删除
- def get(self, request, format=None): 报名列表查看
<|skeleton|>
class join:
def post(self, r... | ff194bc6ff7aa2f1655b42f85e3970df05752f5e | <|skeleton|>
class join:
def post(self, request, format=None):
"""报名创建/修改"""
<|body_0|>
def delete(self, request, format=None):
"""报名删除"""
<|body_1|>
def get(self, request, format=None):
"""报名列表查看"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class join:
def post(self, request, format=None):
"""报名创建/修改"""
user_key = request.META.get('HTTP_SESSION_KEY')
users = UserWechat.objects.filter(password=user_key)
if users.exists():
user = UserWechat.objects.get(password=user_key)
data = request.data.copy()
... | the_stack_v2_python_sparse | apps/wechat/views.py | GUZHIXIANG/hasbroV2 | train | 0 | |
7b65bc3832a6c0ace5648b876ebb266aa31ece16 | [
"data = self.get_json()\ngroup_id = int(group_id)\nstream_id = data.get('stream_id')\nwith self.Session() as session:\n group = session.scalars(Group.select(session.user_or_token, mode='update').where(Group.id == group_id)).first()\n if group is None:\n return self.error(f'Group with ID {group_id} not ... | <|body_start_0|>
data = self.get_json()
group_id = int(group_id)
stream_id = data.get('stream_id')
with self.Session() as session:
group = session.scalars(Group.select(session.user_or_token, mode='update').where(Group.id == group_id)).first()
if group is None:
... | GroupStreamHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupStreamHandler:
def post(self, group_id, *ignored_args):
"""--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: s... | stack_v2_sparse_classes_75kplus_train_000379 | 31,492 | permissive | [
{
"docstring": "--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: stream_id: type: integer required: - stream_id responses: 200: content: a... | 2 | stack_v2_sparse_classes_30k_train_017933 | Implement the Python class `GroupStreamHandler` described below.
Class description:
Implement the GroupStreamHandler class.
Method signatures and docstrings:
- def post(self, group_id, *ignored_args): --- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id requ... | Implement the Python class `GroupStreamHandler` described below.
Class description:
Implement the GroupStreamHandler class.
Method signatures and docstrings:
- def post(self, group_id, *ignored_args): --- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id requ... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class GroupStreamHandler:
def post(self, group_id, *ignored_args):
"""--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupStreamHandler:
def post(self, group_id, *ignored_args):
"""--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: stream_id: type... | the_stack_v2_python_sparse | skyportal/handlers/api/group.py | skyportal/skyportal | train | 80 | |
dd538e237f464863f1b28b10b6ca0d131be4e887 | [
"group_msg = \"'%s' is defined as a parameter group but got input '%s' with type '%s'.\"\nnon_group_msg = \"'%s' is defined as a parameter but got a parameter group as input.\"\nfor key, val in inputs.items():\n definition = input_definition_dict.get(key)\n val = GroupInput.custom_class_value_to_attr_dict(val... | <|body_start_0|>
group_msg = "'%s' is defined as a parameter group but got input '%s' with type '%s'."
non_group_msg = "'%s' is defined as a parameter but got a parameter group as input."
for key, val in inputs.items():
definition = input_definition_dict.get(key)
val = Gr... | This class provide build_inputs_dict for Pipeline and PipelineJob to support ParameterGroup. | PipelineNodeIOMixin | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineNodeIOMixin:
"""This class provide build_inputs_dict for Pipeline and PipelineJob to support ParameterGroup."""
def _validate_group_input_type(self, input_definition_dict: dict, inputs: Dict[str, Union[Input, str, bool, int, float]]):
"""Raise error when group input receive a... | stack_v2_sparse_classes_75kplus_train_000380 | 40,556 | permissive | [
{
"docstring": "Raise error when group input receive a value not group type.",
"name": "_validate_group_input_type",
"signature": "def _validate_group_input_type(self, input_definition_dict: dict, inputs: Dict[str, Union[Input, str, bool, int, float]])"
},
{
"docstring": "Build an input attribut... | 2 | stack_v2_sparse_classes_30k_test_002417 | Implement the Python class `PipelineNodeIOMixin` described below.
Class description:
This class provide build_inputs_dict for Pipeline and PipelineJob to support ParameterGroup.
Method signatures and docstrings:
- def _validate_group_input_type(self, input_definition_dict: dict, inputs: Dict[str, Union[Input, str, bo... | Implement the Python class `PipelineNodeIOMixin` described below.
Class description:
This class provide build_inputs_dict for Pipeline and PipelineJob to support ParameterGroup.
Method signatures and docstrings:
- def _validate_group_input_type(self, input_definition_dict: dict, inputs: Dict[str, Union[Input, str, bo... | 1c66defa502b754abcc9e5afa444ca03c609342f | <|skeleton|>
class PipelineNodeIOMixin:
"""This class provide build_inputs_dict for Pipeline and PipelineJob to support ParameterGroup."""
def _validate_group_input_type(self, input_definition_dict: dict, inputs: Dict[str, Union[Input, str, bool, int, float]]):
"""Raise error when group input receive a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipelineNodeIOMixin:
"""This class provide build_inputs_dict for Pipeline and PipelineJob to support ParameterGroup."""
def _validate_group_input_type(self, input_definition_dict: dict, inputs: Dict[str, Union[Input, str, bool, int, float]]):
"""Raise error when group input receive a value not gr... | the_stack_v2_python_sparse | sdk/ml/azure-ai-ml/azure/ai/ml/entities/_job/pipeline/_io.py | gaoyp830/azure-sdk-for-python | train | 0 |
db1c45859152c75f31452876f0b307639f78202a | [
"tmp_sum = 0\npieces = 1\nfor num in arr:\n if tmp_sum + num > largestSum:\n pieces += 1\n tmp_sum = num\n else:\n tmp_sum += num\nreturn pieces",
"lo = max(nums)\nhi = sum(nums)\nwhile lo < hi:\n mid = lo + (hi - lo) / 2\n pieces = self.split(nums, largestSum=mid)\n if pieces ... | <|body_start_0|>
tmp_sum = 0
pieces = 1
for num in arr:
if tmp_sum + num > largestSum:
pieces += 1
tmp_sum = num
else:
tmp_sum += num
return pieces
<|end_body_0|>
<|body_start_1|>
lo = max(nums)
hi =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def split(self, arr, largestSum):
"""Tells the no. of possible pieces which can make num same as largestSum"""
<|body_0|>
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_000381 | 1,421 | no_license | [
{
"docstring": "Tells the no. of possible pieces which can make num same as largestSum",
"name": "split",
"signature": "def split(self, arr, largestSum)"
},
{
"docstring": ":type nums: List[int] :type m: int :rtype: int",
"name": "splitArray",
"signature": "def splitArray(self, nums, m)"... | 2 | stack_v2_sparse_classes_30k_train_012776 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def split(self, arr, largestSum): Tells the no. of possible pieces which can make num same as largestSum
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def split(self, arr, largestSum): Tells the no. of possible pieces which can make num same as largestSum
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtyp... | 877933424e6d2c590d6ac53db18bee951a3d9de4 | <|skeleton|>
class Solution:
def split(self, arr, largestSum):
"""Tells the no. of possible pieces which can make num same as largestSum"""
<|body_0|>
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def split(self, arr, largestSum):
"""Tells the no. of possible pieces which can make num same as largestSum"""
tmp_sum = 0
pieces = 1
for num in arr:
if tmp_sum + num > largestSum:
pieces += 1
tmp_sum = num
else:... | the_stack_v2_python_sparse | leetcode/410.split-array-largest-sum.py | siddhism/leetcode | train | 0 | |
0c98c4fe76afed5eb6280a3a1fcd2f59e1f21f31 | [
"if isinstance(ksize, int):\n self.ksize = (ksize,) * 2\nelse:\n self.ksize = ksize\nif isinstance(stride, int):\n self.stride = (stride,) * 2\nelse:\n self.stride = stride\nif isinstance(pad, int):\n self.pad = (0,) + (pad,) * 2 + (0,)\nelse:\n self.pad = (0,) + tuple(pad) + (0,)\nself.istrainabl... | <|body_start_0|>
if isinstance(ksize, int):
self.ksize = (ksize,) * 2
else:
self.ksize = ksize
if isinstance(stride, int):
self.stride = (stride,) * 2
else:
self.stride = stride
if isinstance(pad, int):
self.pad = (0,) +... | MaxPooling2d | MaxPooling2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxPooling2d:
"""MaxPooling2d"""
def __init__(self, ksize, stride=1, pad=0):
"""construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width"""
<|body_0|>
def forward(self, x, training=False):
... | stack_v2_sparse_classes_75kplus_train_000382 | 2,610 | no_license | [
{
"docstring": "construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width",
"name": "__init__",
"signature": "def __init__(self, ksize, stride=1, pad=0)"
},
{
"docstring": "spatial max pooling Parameters ---------- x ... | 3 | stack_v2_sparse_classes_30k_train_029185 | Implement the Python class `MaxPooling2d` described below.
Class description:
MaxPooling2d
Method signatures and docstrings:
- def __init__(self, ksize, stride=1, pad=0): construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width
- def forw... | Implement the Python class `MaxPooling2d` described below.
Class description:
MaxPooling2d
Method signatures and docstrings:
- def __init__(self, ksize, stride=1, pad=0): construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width
- def forw... | 77056922f23176065b056d5ca136a43971831969 | <|skeleton|>
class MaxPooling2d:
"""MaxPooling2d"""
def __init__(self, ksize, stride=1, pad=0):
"""construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width"""
<|body_0|>
def forward(self, x, training=False):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaxPooling2d:
"""MaxPooling2d"""
def __init__(self, ksize, stride=1, pad=0):
"""construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width"""
if isinstance(ksize, int):
self.ksize = (ksize,) * 2
... | the_stack_v2_python_sparse | prml/neural_networks/layers/pooling.py | zgcgreat/PRML-1 | train | 0 |
25b4d4fbd168b1c0a1638d3ac1e58a4dc86d4917 | [
"from github.objects import CommitComment\ndata = self.http.fetch_commentable_comments(self.id)\nif data[0]['__typename'] == 'CommitComment':\n return CommitComment.from_data(data, self.http)\nelif data[0]['__typename'] == 'GistComment':\n return GistComment.from_data(data, self.http)\nelif data[0]['__typenam... | <|body_start_0|>
from github.objects import CommitComment
data = self.http.fetch_commentable_comments(self.id)
if data[0]['__typename'] == 'CommitComment':
return CommitComment.from_data(data, self.http)
elif data[0]['__typename'] == 'GistComment':
return GistComm... | Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest` | Commentable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Commentable:
"""Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`"""
def fetch_comments(self):
"""|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-rel... | stack_v2_sparse_classes_75kplus_train_000383 | 4,370 | no_license | [
{
"docstring": "|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-related error occurred. ~github.errors.HTTPException An arbitrary HTTP-related error occurred. ~github.errors.Internal A ``\"INTERNAL\"`` status-message was returned. ~github.errors... | 2 | stack_v2_sparse_classes_30k_test_002358 | Implement the Python class `Commentable` described below.
Class description:
Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`
Method signatures and docstrings:
- def fetch_comments(self): |coro| Fetches a list of comments on the commentable. Raises ... | Implement the Python class `Commentable` described below.
Class description:
Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`
Method signatures and docstrings:
- def fetch_comments(self): |coro| Fetches a list of comments on the commentable. Raises ... | 881c2772038ddf99f6b422987659501f10f23544 | <|skeleton|>
class Commentable:
"""Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`"""
def fetch_comments(self):
"""|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-rel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Commentable:
"""Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`"""
def fetch_comments(self):
"""|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-related error oc... | the_stack_v2_python_sparse | github/abc/commentable.py | mehdigolzadeh/Apiv4Downloader | train | 0 |
2bf1e724a5c7ff74a1371b608a6fc6439ff002b8 | [
"super(SRPKeyExchange, self).__init__(cipherSuite, clientHello, serverHello, privateKey)\nself.N = None\nself.v = None\nself.b = None\nself.B = None\nself.verifierDB = verifierDB\nself.A = None\nself.srpUsername = srpUsername\nself.password = password\nself.settings = settings\nif srpUsername is not None and (not i... | <|body_start_0|>
super(SRPKeyExchange, self).__init__(cipherSuite, clientHello, serverHello, privateKey)
self.N = None
self.v = None
self.b = None
self.B = None
self.verifierDB = verifierDB
self.A = None
self.srpUsername = srpUsername
self.password... | Helper class for conducting SRP key exchange | SRPKeyExchange | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SRPKeyExchange:
"""Helper class for conducting SRP key exchange"""
def __init__(self, cipherSuite, clientHello, serverHello, privateKey, verifierDB, srpUsername=None, password=None, settings=None):
"""Link Key Exchange options with verifierDB for SRP"""
<|body_0|>
def ma... | stack_v2_sparse_classes_75kplus_train_000384 | 43,331 | permissive | [
{
"docstring": "Link Key Exchange options with verifierDB for SRP",
"name": "__init__",
"signature": "def __init__(self, cipherSuite, clientHello, serverHello, privateKey, verifierDB, srpUsername=None, password=None, settings=None)"
},
{
"docstring": "Create SRP version of Server Key Exchange",
... | 5 | stack_v2_sparse_classes_30k_train_001760 | Implement the Python class `SRPKeyExchange` described below.
Class description:
Helper class for conducting SRP key exchange
Method signatures and docstrings:
- def __init__(self, cipherSuite, clientHello, serverHello, privateKey, verifierDB, srpUsername=None, password=None, settings=None): Link Key Exchange options ... | Implement the Python class `SRPKeyExchange` described below.
Class description:
Helper class for conducting SRP key exchange
Method signatures and docstrings:
- def __init__(self, cipherSuite, clientHello, serverHello, privateKey, verifierDB, srpUsername=None, password=None, settings=None): Link Key Exchange options ... | 541f58da464296001109f9cfbb879256957b3819 | <|skeleton|>
class SRPKeyExchange:
"""Helper class for conducting SRP key exchange"""
def __init__(self, cipherSuite, clientHello, serverHello, privateKey, verifierDB, srpUsername=None, password=None, settings=None):
"""Link Key Exchange options with verifierDB for SRP"""
<|body_0|>
def ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SRPKeyExchange:
"""Helper class for conducting SRP key exchange"""
def __init__(self, cipherSuite, clientHello, serverHello, privateKey, verifierDB, srpUsername=None, password=None, settings=None):
"""Link Key Exchange options with verifierDB for SRP"""
super(SRPKeyExchange, self).__init_... | the_stack_v2_python_sparse | code/default/lib/noarch/tlslite/keyexchange.py | XX-net/XX-Net | train | 40,250 |
7425639b403dc57b0e2c69bc7bf7d1aecd6990bb | [
"self.testTag(elem, 'list')\nout = []\nfor xitem in elem:\n out.append(XmlDataIO.fromXml(xitem))\nreturn out",
"if xparent is not None:\n elem = ElementTree.SubElement(xparent, 'list')\nelse:\n elem = ElementTree.Element('list')\nfor item in data:\n XmlDataIO.toXml(item, elem)\nreturn elem"
] | <|body_start_0|>
self.testTag(elem, 'list')
out = []
for xitem in elem:
out.append(XmlDataIO.fromXml(xitem))
return out
<|end_body_0|>
<|body_start_1|>
if xparent is not None:
elem = ElementTree.SubElement(xparent, 'list')
else:
elem =... | ListIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListIO:
def load(self, elem):
"""Converts the inputted list tag to Python. :param elem | <xml.etree.ElementTree> :return <list>"""
<|body_0|>
def save(self, data, xparent=None):
"""Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.El... | stack_v2_sparse_classes_75kplus_train_000385 | 15,996 | permissive | [
{
"docstring": "Converts the inputted list tag to Python. :param elem | <xml.etree.ElementTree> :return <list>",
"name": "load",
"signature": "def load(self, elem)"
},
{
"docstring": "Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None... | 2 | stack_v2_sparse_classes_30k_train_006993 | Implement the Python class `ListIO` described below.
Class description:
Implement the ListIO class.
Method signatures and docstrings:
- def load(self, elem): Converts the inputted list tag to Python. :param elem | <xml.etree.ElementTree> :return <list>
- def save(self, data, xparent=None): Parses the element from XML... | Implement the Python class `ListIO` described below.
Class description:
Implement the ListIO class.
Method signatures and docstrings:
- def load(self, elem): Converts the inputted list tag to Python. :param elem | <xml.etree.ElementTree> :return <list>
- def save(self, data, xparent=None): Parses the element from XML... | d31743ec456a41428709968ab11a2cf6c6c76247 | <|skeleton|>
class ListIO:
def load(self, elem):
"""Converts the inputted list tag to Python. :param elem | <xml.etree.ElementTree> :return <list>"""
<|body_0|>
def save(self, data, xparent=None):
"""Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.El... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListIO:
def load(self, elem):
"""Converts the inputted list tag to Python. :param elem | <xml.etree.ElementTree> :return <list>"""
self.testTag(elem, 'list')
out = []
for xitem in elem:
out.append(XmlDataIO.fromXml(xitem))
return out
def save(self, data... | the_stack_v2_python_sparse | projex/xmlutil.py | bitesofcode/projex | train | 7 | |
5cd81ff8a1e2b333244eb751ee2eeb1eb102f79e | [
"if not isinstance(admin, AbstractAdminPage):\n raise InvalidAdminPageTypeError('Input parameter [{admin}] is not an instance of [{base}].'.format(admin=admin, base=AbstractAdminPage))\nsuper().__init__(**options)\nself._admin = admin",
"result = {}\nfor method in self._admin.method_names:\n result[method] ... | <|body_start_0|>
if not isinstance(admin, AbstractAdminPage):
raise InvalidAdminPageTypeError('Input parameter [{admin}] is not an instance of [{base}].'.format(admin=admin, base=AbstractAdminPage))
super().__init__(**options)
self._admin = admin
<|end_body_0|>
<|body_start_1|>
... | admin schema class. | AdminSchema | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminSchema:
"""admin schema class."""
def __init__(self, admin, **options):
"""initializes an instance of AdminSchema. note that at least one of keyword arguments must be provided. :param AbstractAdminPage admin: related admin page instance. :keyword SECURE_TRUE | SECURE_FALSE reada... | stack_v2_sparse_classes_75kplus_train_000386 | 11,627 | permissive | [
{
"docstring": "initializes an instance of AdminSchema. note that at least one of keyword arguments must be provided. :param AbstractAdminPage admin: related admin page instance. :keyword SECURE_TRUE | SECURE_FALSE readable: specifies that any column or attribute which has `allow_read=False` or its name starts ... | 2 | stack_v2_sparse_classes_30k_val_000046 | Implement the Python class `AdminSchema` described below.
Class description:
admin schema class.
Method signatures and docstrings:
- def __init__(self, admin, **options): initializes an instance of AdminSchema. note that at least one of keyword arguments must be provided. :param AbstractAdminPage admin: related admin... | Implement the Python class `AdminSchema` described below.
Class description:
admin schema class.
Method signatures and docstrings:
- def __init__(self, admin, **options): initializes an instance of AdminSchema. note that at least one of keyword arguments must be provided. :param AbstractAdminPage admin: related admin... | 9d4776498225de4f3d16a4600b5b19212abe8562 | <|skeleton|>
class AdminSchema:
"""admin schema class."""
def __init__(self, admin, **options):
"""initializes an instance of AdminSchema. note that at least one of keyword arguments must be provided. :param AbstractAdminPage admin: related admin page instance. :keyword SECURE_TRUE | SECURE_FALSE reada... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdminSchema:
"""admin schema class."""
def __init__(self, admin, **options):
"""initializes an instance of AdminSchema. note that at least one of keyword arguments must be provided. :param AbstractAdminPage admin: related admin page instance. :keyword SECURE_TRUE | SECURE_FALSE readable: specifie... | the_stack_v2_python_sparse | src/pyrin/admin/page/schema.py | mononobi/pyrin | train | 20 |
5e5b5018b690c4bb49322e0a7c680754a474c4a1 | [
"self.maximum = maximum_value\nif maximum_value <= 0:\n self.maximum = -1\nself.__writer = output\nself.__barwidth = 30\nself.__last_percent = -1",
"if config.SILENT:\n return None\nif self.maximum == -1:\n return False\nt_percent_done = int((new_value + 1) / self.maximum * self.__barwidth)\nif t_percent... | <|body_start_0|>
self.maximum = maximum_value
if maximum_value <= 0:
self.maximum = -1
self.__writer = output
self.__barwidth = 30
self.__last_percent = -1
<|end_body_0|>
<|body_start_1|>
if config.SILENT:
return None
if self.maximum == -1... | progressbar | [
"MIT",
"X11-distribute-modifications-variant"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class progressbar:
def __init__(self, maximum_value, output=sys.stderr):
"""Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use."""
<|body_0|>
def update(self, ne... | stack_v2_sparse_classes_75kplus_train_000387 | 2,033 | permissive | [
{
"docstring": "Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use.",
"name": "__init__",
"signature": "def __init__(self, maximum_value, output=sys.stderr)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_016940 | Implement the Python class `progressbar` described below.
Class description:
Implement the progressbar class.
Method signatures and docstrings:
- def __init__(self, maximum_value, output=sys.stderr): Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Op... | Implement the Python class `progressbar` described below.
Class description:
Implement the progressbar class.
Method signatures and docstrings:
- def __init__(self, maximum_value, output=sys.stderr): Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Op... | a1e35eba86fb62b336d559c0b8c0015f38426781 | <|skeleton|>
class progressbar:
def __init__(self, maximum_value, output=sys.stderr):
"""Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use."""
<|body_0|>
def update(self, ne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class progressbar:
def __init__(self, maximum_value, output=sys.stderr):
"""Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use."""
self.maximum = maximum_value
if maximum_v... | the_stack_v2_python_sparse | progress.py | oaxiom/glbase3 | train | 12 | |
b552b57e885cc03f71d154a606903e93c7d561f0 | [
"self.signatures = signature_dict\nself.ssgsea_kwds = ssgsea_kwds\nself.all_ids = reduce(lambda x, y: x.union(y), self.signatures.values(), set())",
"series_in = False\nif isinstance(sample_data, pd.Series):\n sample_data = pd.DataFrame(sample_data)\n series_in = True\nif sample_data.index.duplicated().any(... | <|body_start_0|>
self.signatures = signature_dict
self.ssgsea_kwds = ssgsea_kwds
self.all_ids = reduce(lambda x, y: x.union(y), self.signatures.values(), set())
<|end_body_0|>
<|body_start_1|>
series_in = False
if isinstance(sample_data, pd.Series):
sample_data = pd.... | Basic classifier that uses pre-defined signatures to score samples and assess classification. | ssGSEAClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ssGSEAClassifier:
"""Basic classifier that uses pre-defined signatures to score samples and assess classification."""
def __init__(self, signature_dict, **ssgsea_kwds):
""":param signature_dict: Dictionary. Keys are the class name, values are iterables of genes / probes or any other ... | stack_v2_sparse_classes_75kplus_train_000388 | 3,530 | no_license | [
{
"docstring": ":param signature_dict: Dictionary. Keys are the class name, values are iterables of genes / probes or any other row index :param ssgsea_kwds: Any additional kwargs are passed directly to the ssgsea algorithm.",
"name": "__init__",
"signature": "def __init__(self, signature_dict, **ssgsea... | 2 | stack_v2_sparse_classes_30k_train_033819 | Implement the Python class `ssGSEAClassifier` described below.
Class description:
Basic classifier that uses pre-defined signatures to score samples and assess classification.
Method signatures and docstrings:
- def __init__(self, signature_dict, **ssgsea_kwds): :param signature_dict: Dictionary. Keys are the class n... | Implement the Python class `ssGSEAClassifier` described below.
Class description:
Basic classifier that uses pre-defined signatures to score samples and assess classification.
Method signatures and docstrings:
- def __init__(self, signature_dict, **ssgsea_kwds): :param signature_dict: Dictionary. Keys are the class n... | 3cb6fa0e763ddc0a375fcd99a55eab5f9df26fe3 | <|skeleton|>
class ssGSEAClassifier:
"""Basic classifier that uses pre-defined signatures to score samples and assess classification."""
def __init__(self, signature_dict, **ssgsea_kwds):
""":param signature_dict: Dictionary. Keys are the class name, values are iterables of genes / probes or any other ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ssGSEAClassifier:
"""Basic classifier that uses pre-defined signatures to score samples and assess classification."""
def __init__(self, signature_dict, **ssgsea_kwds):
""":param signature_dict: Dictionary. Keys are the class name, values are iterables of genes / probes or any other row index :pa... | the_stack_v2_python_sparse | classification/signature.py | gaberosser/qmul-bioinf | train | 3 |
4a1df3ca888cddaf278f74c5b02e195e32ed268c | [
"self.name = name\nself.aset = []\nself.aset_6dof = []\nself.gset = []\nself.oset = []\nself.load_uset()",
"with open(self.name) as f:\n i = 0\n for line in f:\n if line.__len__() > 29:\n if line[16:18] == '- ' and line[38:40] == '- ':\n if line[60:66] != ' ':\n ... | <|body_start_0|>
self.name = name
self.aset = []
self.aset_6dof = []
self.gset = []
self.oset = []
self.load_uset()
<|end_body_0|>
<|body_start_1|>
with open(self.name) as f:
i = 0
for line in f:
if line.__len__() > 29:
... | Class of USET table output from NASTRAN. | USET | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class USET:
"""Class of USET table output from NASTRAN."""
def __init__(self, name):
"""Method to initialize the USET class."""
<|body_0|>
def load_uset(self):
"""Method to load the USET f06."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.name =... | stack_v2_sparse_classes_75kplus_train_000389 | 2,679 | no_license | [
{
"docstring": "Method to initialize the USET class.",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "Method to load the USET f06.",
"name": "load_uset",
"signature": "def load_uset(self)"
}
] | 2 | null | Implement the Python class `USET` described below.
Class description:
Class of USET table output from NASTRAN.
Method signatures and docstrings:
- def __init__(self, name): Method to initialize the USET class.
- def load_uset(self): Method to load the USET f06. | Implement the Python class `USET` described below.
Class description:
Class of USET table output from NASTRAN.
Method signatures and docstrings:
- def __init__(self, name): Method to initialize the USET class.
- def load_uset(self): Method to load the USET f06.
<|skeleton|>
class USET:
"""Class of USET table out... | 6b37842203ff4318a48dbf0258cbe2b253436e7d | <|skeleton|>
class USET:
"""Class of USET table output from NASTRAN."""
def __init__(self, name):
"""Method to initialize the USET class."""
<|body_0|>
def load_uset(self):
"""Method to load the USET f06."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class USET:
"""Class of USET table output from NASTRAN."""
def __init__(self, name):
"""Method to initialize the USET class."""
self.name = name
self.aset = []
self.aset_6dof = []
self.gset = []
self.oset = []
self.load_uset()
def load_uset(self):
... | the_stack_v2_python_sparse | loads/f06_results.py | tslowery78/PyLnD | train | 0 |
0280a4eba23ef163ad734cc7eaa3a1367a2073db | [
"self.poll = poll\nself.inline_message_id = inline_message_id\nself.admin_user = admin_user\nself.admin_message_id = admin_message_id\nself.vote_user = vote_user\nself.vote_message_id = vote_message_id",
"if self.inline_message_id is not None:\n message = f'Reference {self.id}: inline_message_id {self.inline_m... | <|body_start_0|>
self.poll = poll
self.inline_message_id = inline_message_id
self.admin_user = admin_user
self.admin_message_id = admin_message_id
self.vote_user = vote_user
self.vote_message_id = vote_message_id
<|end_body_0|>
<|body_start_1|>
if self.inline_mes... | The model for a Reference. | Reference | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reference:
"""The model for a Reference."""
def __init__(self, poll, inline_message_id=None, admin_user=None, admin_message_id=None, vote_user=None, vote_message_id=None):
"""Create a new poll."""
<|body_0|>
def __repr__(self):
"""Print as string."""
<|bo... | stack_v2_sparse_classes_75kplus_train_000390 | 2,317 | permissive | [
{
"docstring": "Create a new poll.",
"name": "__init__",
"signature": "def __init__(self, poll, inline_message_id=None, admin_user=None, admin_message_id=None, vote_user=None, vote_message_id=None)"
},
{
"docstring": "Print as string.",
"name": "__repr__",
"signature": "def __repr__(self... | 2 | stack_v2_sparse_classes_30k_train_031805 | Implement the Python class `Reference` described below.
Class description:
The model for a Reference.
Method signatures and docstrings:
- def __init__(self, poll, inline_message_id=None, admin_user=None, admin_message_id=None, vote_user=None, vote_message_id=None): Create a new poll.
- def __repr__(self): Print as st... | Implement the Python class `Reference` described below.
Class description:
The model for a Reference.
Method signatures and docstrings:
- def __init__(self, poll, inline_message_id=None, admin_user=None, admin_message_id=None, vote_user=None, vote_message_id=None): Create a new poll.
- def __repr__(self): Print as st... | 33bc71b56f79453359043bd0e778cd153d3a83a3 | <|skeleton|>
class Reference:
"""The model for a Reference."""
def __init__(self, poll, inline_message_id=None, admin_user=None, admin_message_id=None, vote_user=None, vote_message_id=None):
"""Create a new poll."""
<|body_0|>
def __repr__(self):
"""Print as string."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Reference:
"""The model for a Reference."""
def __init__(self, poll, inline_message_id=None, admin_user=None, admin_message_id=None, vote_user=None, vote_message_id=None):
"""Create a new poll."""
self.poll = poll
self.inline_message_id = inline_message_id
self.admin_user ... | the_stack_v2_python_sparse | pollbot/models/reference.py | RuslanBitcash/ultimate-poll-bot | train | 1 |
95999ae321a73db06f8374e80349f425560e511c | [
"try:\n json_data = json.loads(request.data.decode())\n resp_data = trafficShaperController.start_bandwitdh_shaping(json_data)\n resp = Response(resp_data, status=200, mimetype='application/text')\n return resp\nexcept Exception as err:\n return Response(json.dumps(str(err)), status=500, mimetype='ap... | <|body_start_0|>
try:
json_data = json.loads(request.data.decode())
resp_data = trafficShaperController.start_bandwitdh_shaping(json_data)
resp = Response(resp_data, status=200, mimetype='application/text')
return resp
except Exception as err:
... | TrafficShaper_Configuration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficShaper_Configuration:
def post(self):
"""Start bandwitdh shaping"""
<|body_0|>
def put(self, if_name):
"""Update bandwitdh shaping configuration"""
<|body_1|>
def delete(self, if_name):
"""Stop bandwitdh shaping"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_000391 | 4,055 | no_license | [
{
"docstring": "Start bandwitdh shaping",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update bandwitdh shaping configuration",
"name": "put",
"signature": "def put(self, if_name)"
},
{
"docstring": "Stop bandwitdh shaping",
"name": "delete",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_031798 | Implement the Python class `TrafficShaper_Configuration` described below.
Class description:
Implement the TrafficShaper_Configuration class.
Method signatures and docstrings:
- def post(self): Start bandwitdh shaping
- def put(self, if_name): Update bandwitdh shaping configuration
- def delete(self, if_name): Stop b... | Implement the Python class `TrafficShaper_Configuration` described below.
Class description:
Implement the TrafficShaper_Configuration class.
Method signatures and docstrings:
- def post(self): Start bandwitdh shaping
- def put(self, if_name): Update bandwitdh shaping configuration
- def delete(self, if_name): Stop b... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class TrafficShaper_Configuration:
def post(self):
"""Start bandwitdh shaping"""
<|body_0|>
def put(self, if_name):
"""Update bandwitdh shaping configuration"""
<|body_1|>
def delete(self, if_name):
"""Stop bandwitdh shaping"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrafficShaper_Configuration:
def post(self):
"""Start bandwitdh shaping"""
try:
json_data = json.loads(request.data.decode())
resp_data = trafficShaperController.start_bandwitdh_shaping(json_data)
resp = Response(resp_data, status=200, mimetype='application/... | the_stack_v2_python_sparse | configuration-agent/traffic_shaper/rest_api/resources/traffic_shaper.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
6cecfd8498235e87f9e4924bea246ca809e5749c | [
"elements = [Adder(val) for val in (0, -2, -1000000.0)]\nfor elements in itertools.product(elements, repeat=6):\n for initial in (0, -15, +1000000.0):\n with self.subTest(chain=elements, initial=initial):\n a, b, c, d, e, f = elements\n chain_a = a >> (b, c >> (d, e >> f))\n ... | <|body_start_0|>
elements = [Adder(val) for val in (0, -2, -1000000.0)]
for elements in itertools.product(elements, repeat=6):
for initial in (0, -15, +1000000.0):
with self.subTest(chain=elements, initial=initial):
a, b, c, d, e, f = elements
... | ChainNested | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChainNested:
def test_multi(self):
"""Push nested fork as `a >> (b, c >> (d, e >> ...`"""
<|body_0|>
def test_abort(self):
"""Abort in nested fork"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
elements = [Adder(val) for val in (0, -2, -1000000.0)]... | stack_v2_sparse_classes_75kplus_train_000392 | 3,474 | permissive | [
{
"docstring": "Push nested fork as `a >> (b, c >> (d, e >> ...`",
"name": "test_multi",
"signature": "def test_multi(self)"
},
{
"docstring": "Abort in nested fork",
"name": "test_abort",
"signature": "def test_abort(self)"
}
] | 2 | null | Implement the Python class `ChainNested` described below.
Class description:
Implement the ChainNested class.
Method signatures and docstrings:
- def test_multi(self): Push nested fork as `a >> (b, c >> (d, e >> ...`
- def test_abort(self): Abort in nested fork | Implement the Python class `ChainNested` described below.
Class description:
Implement the ChainNested class.
Method signatures and docstrings:
- def test_multi(self): Push nested fork as `a >> (b, c >> (d, e >> ...`
- def test_abort(self): Abort in nested fork
<|skeleton|>
class ChainNested:
def test_multi(sel... | 4e17f9992b4780bd0d9309202e2847df640bffe8 | <|skeleton|>
class ChainNested:
def test_multi(self):
"""Push nested fork as `a >> (b, c >> (d, e >> ...`"""
<|body_0|>
def test_abort(self):
"""Abort in nested fork"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChainNested:
def test_multi(self):
"""Push nested fork as `a >> (b, c >> (d, e >> ...`"""
elements = [Adder(val) for val in (0, -2, -1000000.0)]
for elements in itertools.product(elements, repeat=6):
for initial in (0, -15, +1000000.0):
with self.subTest(cha... | the_stack_v2_python_sparse | chainlet_unittests/test_dataflow/test_nested.py | maxfischer2781/chainlet | train | 1 | |
41ffcfd217152d8ae0df424953be1445edea86c9 | [
"data = xlrd.open_workbook(file_path)\ntable = data.sheets()[0]\nreturn table",
"data = xlrd.open_workbook(file_path)\ntable = data.sheet_by_name(sheetname)\nreturn table",
"table = self.getTable(file_path)\nrows = table.nrows\nreturn rows",
"table = self.getTable(file_path)\ncols = table.ncols\nreturn cols"
... | <|body_start_0|>
data = xlrd.open_workbook(file_path)
table = data.sheets()[0]
return table
<|end_body_0|>
<|body_start_1|>
data = xlrd.open_workbook(file_path)
table = data.sheet_by_name(sheetname)
return table
<|end_body_1|>
<|body_start_2|>
table = self.getTa... | ReadExcel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadExcel:
def getTable(self, file_path):
"""读取一个excel文件并返回该表格对象"""
<|body_0|>
def getTableBySheetName(self, file_path, sheetname):
"""读取一个excel文件并返回该表格对象"""
<|body_1|>
def getExcelRows(self, file_path):
"""通过获取到的表格对象得到总行数"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_000393 | 900 | no_license | [
{
"docstring": "读取一个excel文件并返回该表格对象",
"name": "getTable",
"signature": "def getTable(self, file_path)"
},
{
"docstring": "读取一个excel文件并返回该表格对象",
"name": "getTableBySheetName",
"signature": "def getTableBySheetName(self, file_path, sheetname)"
},
{
"docstring": "通过获取到的表格对象得到总行数",
... | 4 | null | Implement the Python class `ReadExcel` described below.
Class description:
Implement the ReadExcel class.
Method signatures and docstrings:
- def getTable(self, file_path): 读取一个excel文件并返回该表格对象
- def getTableBySheetName(self, file_path, sheetname): 读取一个excel文件并返回该表格对象
- def getExcelRows(self, file_path): 通过获取到的表格对象得到总... | Implement the Python class `ReadExcel` described below.
Class description:
Implement the ReadExcel class.
Method signatures and docstrings:
- def getTable(self, file_path): 读取一个excel文件并返回该表格对象
- def getTableBySheetName(self, file_path, sheetname): 读取一个excel文件并返回该表格对象
- def getExcelRows(self, file_path): 通过获取到的表格对象得到总... | 4dd065806f20bfdec885fa2b40f2c22e5a8d4f15 | <|skeleton|>
class ReadExcel:
def getTable(self, file_path):
"""读取一个excel文件并返回该表格对象"""
<|body_0|>
def getTableBySheetName(self, file_path, sheetname):
"""读取一个excel文件并返回该表格对象"""
<|body_1|>
def getExcelRows(self, file_path):
"""通过获取到的表格对象得到总行数"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReadExcel:
def getTable(self, file_path):
"""读取一个excel文件并返回该表格对象"""
data = xlrd.open_workbook(file_path)
table = data.sheets()[0]
return table
def getTableBySheetName(self, file_path, sheetname):
"""读取一个excel文件并返回该表格对象"""
data = xlrd.open_workbook(file_path... | the_stack_v2_python_sparse | Data/ReadExcel.py | Hardworking-tester/HuaYing | train | 0 | |
39c55b6abd96132265b026d4484734f85b2ee518 | [
"if not cls._repository_url:\n return None\nif not cls._repository_url.startswith('https://github.com/'):\n raise RuntimeError('Do not known how to handle this repository: %s' % cls._repository_url)\nlocal_repository_dir = cls.local_repository_location()\nif not local_repository_dir:\n return None\nreturn ... | <|body_start_0|>
if not cls._repository_url:
return None
if not cls._repository_url.startswith('https://github.com/'):
raise RuntimeError('Do not known how to handle this repository: %s' % cls._repository_url)
local_repository_dir = cls.local_repository_location()
... | Implements all methods needed to handle cache handling for git-repository-based adapters | GitRepositoryAdapter | [
"MIT",
"CC-BY-SA-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitRepositoryAdapter:
"""Implements all methods needed to handle cache handling for git-repository-based adapters"""
def fetch_command(cls):
"""Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not s... | stack_v2_sparse_classes_75kplus_train_000394 | 5,184 | permissive | [
{
"docstring": "Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not specified",
"name": "fetch_command",
"signature": "def fetch_command(cls)"
},
{
"docstring": "Update of the repository. Return cmdline that h... | 6 | stack_v2_sparse_classes_30k_train_030551 | Implement the Python class `GitRepositoryAdapter` described below.
Class description:
Implements all methods needed to handle cache handling for git-repository-based adapters
Method signatures and docstrings:
- def fetch_command(cls): Initial fetch of the repository. Return cmdline that has to be executed to fetch th... | Implement the Python class `GitRepositoryAdapter` described below.
Class description:
Implements all methods needed to handle cache handling for git-repository-based adapters
Method signatures and docstrings:
- def fetch_command(cls): Initial fetch of the repository. Return cmdline that has to be executed to fetch th... | 7a3c5c32d1a087770c65d765b546e3f6b856626e | <|skeleton|>
class GitRepositoryAdapter:
"""Implements all methods needed to handle cache handling for git-repository-based adapters"""
def fetch_command(cls):
"""Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GitRepositoryAdapter:
"""Implements all methods needed to handle cache handling for git-repository-based adapters"""
def fetch_command(cls):
"""Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not specified"""
... | the_stack_v2_python_sparse | lib/adapter/git_adapter.py | santoshakil/cheat.sh | train | 2 |
69806b954a1de8eb08071a7774aacb5b8fe74dd8 | [
"dval = {}\nmodel = type(self)\nmapper = inspect(model)\nfor col in mapper.attrs:\n col_key = col.key\n dval[col_key] = str(getattr(self, col_key))\nreturn dval",
"model_dict = self.to_dict()\njson_str = json.dumps(model_dict, indent=indent)\nreturn json_str"
] | <|body_start_0|>
dval = {}
model = type(self)
mapper = inspect(model)
for col in mapper.attrs:
col_key = col.key
dval[col_key] = str(getattr(self, col_key))
return dval
<|end_body_0|>
<|body_start_1|>
model_dict = self.to_dict()
json_str =... | Mixin style class that adds serialization to data model objects. | SerializableModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerializableModel:
"""Mixin style class that adds serialization to data model objects."""
def to_dict(self):
"""Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model."""
<|body_0|>
def to_json(self, indent=4):
""... | stack_v2_sparse_classes_75kplus_train_000395 | 6,583 | no_license | [
{
"docstring": "Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model.",
"name": "to_dict",
"signature": "def to_dict(self)"
},
{
"docstring": "Iterates the formal data attributes of a model and creates a dictionary with the data based on the mo... | 2 | stack_v2_sparse_classes_30k_train_033761 | Implement the Python class `SerializableModel` described below.
Class description:
Mixin style class that adds serialization to data model objects.
Method signatures and docstrings:
- def to_dict(self): Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model.
- def to_... | Implement the Python class `SerializableModel` described below.
Class description:
Mixin style class that adds serialization to data model objects.
Method signatures and docstrings:
- def to_dict(self): Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model.
- def to_... | 530ea184f29add6f42bee1465343f6ddb51a1e51 | <|skeleton|>
class SerializableModel:
"""Mixin style class that adds serialization to data model objects."""
def to_dict(self):
"""Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model."""
<|body_0|>
def to_json(self, indent=4):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SerializableModel:
"""Mixin style class that adds serialization to data model objects."""
def to_dict(self):
"""Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model."""
dval = {}
model = type(self)
mapper = inspect(model)... | the_stack_v2_python_sparse | packages/akit/datum/orm.py | TrendingTechnology/automationkit | train | 0 |
17d629adf5a1a5a51ac4551e4632e03f6c38f89f | [
"self.type = type\nif type == 'disk':\n self.destination = destination\nelif type == 'memory':\n raise NotImplementedError(\"The output can't be a variable in memory yet\")\nelse:\n raise ValueError('The type should be disk or memory')",
"try:\n file = open(self.destination, 'wb')\n file.write(data... | <|body_start_0|>
self.type = type
if type == 'disk':
self.destination = destination
elif type == 'memory':
raise NotImplementedError("The output can't be a variable in memory yet")
else:
raise ValueError('The type should be disk or memory')
<|end_body_... | OutputStreamHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputStreamHandler:
def __init__(self, destination, type='disk'):
"""initialize the handler and be able to access the disk/memory as specified and make sure they are available. type is a string, either “disk” or “memory” destination is either a path to the disk, or a memory holding by t... | stack_v2_sparse_classes_75kplus_train_000396 | 1,067 | permissive | [
{
"docstring": "initialize the handler and be able to access the disk/memory as specified and make sure they are available. type is a string, either “disk” or “memory” destination is either a path to the disk, or a memory holding by this handler",
"name": "__init__",
"signature": "def __init__(self, des... | 2 | null | Implement the Python class `OutputStreamHandler` described below.
Class description:
Implement the OutputStreamHandler class.
Method signatures and docstrings:
- def __init__(self, destination, type='disk'): initialize the handler and be able to access the disk/memory as specified and make sure they are available. ty... | Implement the Python class `OutputStreamHandler` described below.
Class description:
Implement the OutputStreamHandler class.
Method signatures and docstrings:
- def __init__(self, destination, type='disk'): initialize the handler and be able to access the disk/memory as specified and make sure they are available. ty... | dd101b4fb6ab41d39256e98f7e290453e2c147e9 | <|skeleton|>
class OutputStreamHandler:
def __init__(self, destination, type='disk'):
"""initialize the handler and be able to access the disk/memory as specified and make sure they are available. type is a string, either “disk” or “memory” destination is either a path to the disk, or a memory holding by t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutputStreamHandler:
def __init__(self, destination, type='disk'):
"""initialize the handler and be able to access the disk/memory as specified and make sure they are available. type is a string, either “disk” or “memory” destination is either a path to the disk, or a memory holding by this handler"""... | the_stack_v2_python_sparse | Code/wfmg/workFlowManager/output_stream_handler.py | fiu-airlab/Data-Science-Workflow-Manager | train | 1 | |
ebcef0dad7e29394cdf1b21b265fedba77d7ca4a | [
"tenant = tenant_util.find_tenant(tenant_id=tenant_id)\nif not tenant:\n _tenant_not_found()\nevent_producer = tenant_util.find_event_producer(tenant, producer_id=event_producer_id)\nif not event_producer:\n _producer_not_found()\nresp.status = falcon.HTTP_200\nresp.body = api.format_response_body({'event_pro... | <|body_start_0|>
tenant = tenant_util.find_tenant(tenant_id=tenant_id)
if not tenant:
_tenant_not_found()
event_producer = tenant_util.find_event_producer(tenant, producer_id=event_producer_id)
if not event_producer:
_producer_not_found()
resp.status = fal... | EventProducer Resource allows for the retrieval and update of a specified Event Producer for a Tenant. | EventProducerResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventProducerResource:
"""EventProducer Resource allows for the retrieval and update of a specified Event Producer for a Tenant."""
def on_get(self, req, resp, tenant_id, event_producer_id):
"""Retrieve a specified Event Producer from a Tenant when an HTTP GET is received"""
... | stack_v2_sparse_classes_75kplus_train_000397 | 12,230 | permissive | [
{
"docstring": "Retrieve a specified Event Producer from a Tenant when an HTTP GET is received",
"name": "on_get",
"signature": "def on_get(self, req, resp, tenant_id, event_producer_id)"
},
{
"docstring": "Make an update to a specified Event Producer's configuration when an HTTP PUT is received... | 3 | null | Implement the Python class `EventProducerResource` described below.
Class description:
EventProducer Resource allows for the retrieval and update of a specified Event Producer for a Tenant.
Method signatures and docstrings:
- def on_get(self, req, resp, tenant_id, event_producer_id): Retrieve a specified Event Produc... | Implement the Python class `EventProducerResource` described below.
Class description:
EventProducer Resource allows for the retrieval and update of a specified Event Producer for a Tenant.
Method signatures and docstrings:
- def on_get(self, req, resp, tenant_id, event_producer_id): Retrieve a specified Event Produc... | 1df9efe33ead702d0f53dfc227b5da385ba9cf23 | <|skeleton|>
class EventProducerResource:
"""EventProducer Resource allows for the retrieval and update of a specified Event Producer for a Tenant."""
def on_get(self, req, resp, tenant_id, event_producer_id):
"""Retrieve a specified Event Producer from a Tenant when an HTTP GET is received"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventProducerResource:
"""EventProducer Resource allows for the retrieval and update of a specified Event Producer for a Tenant."""
def on_get(self, req, resp, tenant_id, event_producer_id):
"""Retrieve a specified Event Producer from a Tenant when an HTTP GET is received"""
tenant = tena... | the_stack_v2_python_sparse | meniscus/api/tenant/resources.py | priestd09/meniscus | train | 0 |
4023b3ba8e9d105725fcd1f35e4aa94849b91f08 | [
"self.filepath = filepath\nwith open(self.filepath) as f:\n for line in f:\n line = line.rstrip('\\n')\n if re.match('^#{1}\\\\w+', line):\n bits = line.split('\\t')\n self.columns = bits\n break",
"data = defaultdict(set)\nwith open(self.filepath) as f:\n for ... | <|body_start_0|>
self.filepath = filepath
with open(self.filepath) as f:
for line in f:
line = line.rstrip('\n')
if re.match('^#{1}\\w+', line):
bits = line.split('\t')
self.columns = bits
break
<|end... | Class representing an index file as it is represented in the IGSR project | SequenceIndex | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceIndex:
"""Class representing an index file as it is represented in the IGSR project"""
def __init__(self, filepath):
"""Constructor Parameters ---------- filepath : str Path to index file. columns : list List with column names in the file."""
<|body_0|>
def runs_... | stack_v2_sparse_classes_75kplus_train_000398 | 2,397 | permissive | [
{
"docstring": "Constructor Parameters ---------- filepath : str Path to index file. columns : list List with column names in the file.",
"name": "__init__",
"signature": "def __init__(self, filepath)"
},
{
"docstring": "This function will return a dictionary for which each key will be a differe... | 2 | stack_v2_sparse_classes_30k_train_012637 | Implement the Python class `SequenceIndex` described below.
Class description:
Class representing an index file as it is represented in the IGSR project
Method signatures and docstrings:
- def __init__(self, filepath): Constructor Parameters ---------- filepath : str Path to index file. columns : list List with colum... | Implement the Python class `SequenceIndex` described below.
Class description:
Class representing an index file as it is represented in the IGSR project
Method signatures and docstrings:
- def __init__(self, filepath): Constructor Parameters ---------- filepath : str Path to index file. columns : list List with colum... | ffea4885227c2299f886a4f41e70b6e1f6bb43da | <|skeleton|>
class SequenceIndex:
"""Class representing an index file as it is represented in the IGSR project"""
def __init__(self, filepath):
"""Constructor Parameters ---------- filepath : str Path to index file. columns : list List with column names in the file."""
<|body_0|>
def runs_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SequenceIndex:
"""Class representing an index file as it is represented in the IGSR project"""
def __init__(self, filepath):
"""Constructor Parameters ---------- filepath : str Path to index file. columns : list List with column names in the file."""
self.filepath = filepath
with ... | the_stack_v2_python_sparse | SequenceIndex/SequenceIndex.py | igsr/igsr_analysis | train | 3 |
bea52c949d9410e4ab047e7b35047e5ecf21e4ec | [
"self.not_exists_au = 1\nself.not_exists_ac = 1\nself.not_big = 1\nself.rate = rate\nself.hours = hours\nself.cur = cur\nself.user = user\nself.response_ts = response_ts\nself.set_period()\nself.data_retrieval()\nif self.not_exists_au and self.not_exists_ac:\n self.align_timeseries()\n self.one_hot_encode()",... | <|body_start_0|>
self.not_exists_au = 1
self.not_exists_ac = 1
self.not_big = 1
self.rate = rate
self.hours = hours
self.cur = cur
self.user = user
self.response_ts = response_ts
self.set_period()
self.data_retrieval()
if self.not_e... | Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses | OneHotTimeSeries | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneHotTimeSeries:
"""Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses"""
def __init__(self, cur, user, response_ts, rate, hours):
""":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of... | stack_v2_sparse_classes_75kplus_train_000399 | 6,866 | no_license | [
{
"docstring": ":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of uXX, XX E[00,59]. Database tables assosiacted with each user use it in their name as well plus an acronym depicting the details. E.g. u00sleep table contains sleep information for user u00. :response_ts: Unix times... | 5 | stack_v2_sparse_classes_30k_train_041914 | Implement the Python class `OneHotTimeSeries` described below.
Class description:
Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses
Method signatures and docstrings:
- def __init__(self, cur, user, response_ts, rate, hours): :cur: Cursor pointing to... | Implement the Python class `OneHotTimeSeries` described below.
Class description:
Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses
Method signatures and docstrings:
- def __init__(self, cur, user, response_ts, rate, hours): :cur: Cursor pointing to... | 27ef638e50b7b102d12d193d57442a41001c3060 | <|skeleton|>
class OneHotTimeSeries:
"""Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses"""
def __init__(self, cur, user, response_ts, rate, hours):
""":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OneHotTimeSeries:
"""Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses"""
def __init__(self, cur, user, response_ts, rate, hours):
""":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of uXX, XX E[00... | the_stack_v2_python_sparse | sleep/deep learning/oh2channels.py | koolboy2016/StudentLife-DataMining-ModelTraining | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.