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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18666b57d4e0a04ddbc436b831c77eac9fc0fd0a | [
"self._api_key = api_key\nself._device_id = device_id\nself._device_ids = device_ids\nself._device_names = device_names",
"title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)\ndata = kwargs.get(ATTR_DATA) or {}\nsend_notification(device_id=self._device_id, device_ids=self._device_ids, device_names=self._device_nam... | <|body_start_0|>
self._api_key = api_key
self._device_id = device_id
self._device_ids = device_ids
self._device_names = device_names
<|end_body_0|>
<|body_start_1|>
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
data = kwargs.get(ATTR_DATA) or {}
send_notific... | Implement the notification service for Join. | JoinNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinNotificationService:
"""Implement the notification service for Join."""
def __init__(self, api_key, device_id, device_ids, device_names):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to a user."""
... | stack_v2_sparse_classes_75kplus_train_066800 | 3,006 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, api_key, device_id, device_ids, device_names)"
},
{
"docstring": "Send a message to a user.",
"name": "send_message",
"signature": "def send_message(self, message='', **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009248 | Implement the Python class `JoinNotificationService` described below.
Class description:
Implement the notification service for Join.
Method signatures and docstrings:
- def __init__(self, api_key, device_id, device_ids, device_names): Initialize the service.
- def send_message(self, message='', **kwargs): Send a mes... | Implement the Python class `JoinNotificationService` described below.
Class description:
Implement the notification service for Join.
Method signatures and docstrings:
- def __init__(self, api_key, device_id, device_ids, device_names): Initialize the service.
- def send_message(self, message='', **kwargs): Send a mes... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class JoinNotificationService:
"""Implement the notification service for Join."""
def __init__(self, api_key, device_id, device_ids, device_names):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to a user."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JoinNotificationService:
"""Implement the notification service for Join."""
def __init__(self, api_key, device_id, device_ids, device_names):
"""Initialize the service."""
self._api_key = api_key
self._device_id = device_id
self._device_ids = device_ids
self._devic... | the_stack_v2_python_sparse | homeassistant/components/joaoapps_join/notify.py | home-assistant/core | train | 35,501 |
6cc07005984263fa6614700037e32de71fe39bb5 | [
"wait_for_nodes_1 = WaitForNodes(node_list, timeout=10.0)\nassert wait_for_nodes_1.wait()\nassert wait_for_nodes_1.get_nodes_not_found() == set()\nwait_for_nodes_1.shutdown()\nwith WaitForNodes(node_list, timeout=10.0) as wait_for_nodes_2:\n print('All nodes were found !')\n assert wait_for_nodes_2.get_nodes_... | <|body_start_0|>
wait_for_nodes_1 = WaitForNodes(node_list, timeout=10.0)
assert wait_for_nodes_1.wait()
assert wait_for_nodes_1.get_nodes_not_found() == set()
wait_for_nodes_1.shutdown()
with WaitForNodes(node_list, timeout=10.0) as wait_for_nodes_2:
print('All nodes... | CheckMultipleNodesLaunched | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckMultipleNodesLaunched:
def test_nodes_successful(self, node_list):
"""Check if all the nodes were launched correctly."""
<|body_0|>
def test_node_does_not_exist(self, node_list):
"""Insert a invalid node name that should not exist."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_066801 | 4,984 | permissive | [
{
"docstring": "Check if all the nodes were launched correctly.",
"name": "test_nodes_successful",
"signature": "def test_nodes_successful(self, node_list)"
},
{
"docstring": "Insert a invalid node name that should not exist.",
"name": "test_node_does_not_exist",
"signature": "def test_n... | 2 | stack_v2_sparse_classes_30k_train_026707 | Implement the Python class `CheckMultipleNodesLaunched` described below.
Class description:
Implement the CheckMultipleNodesLaunched class.
Method signatures and docstrings:
- def test_nodes_successful(self, node_list): Check if all the nodes were launched correctly.
- def test_node_does_not_exist(self, node_list): I... | Implement the Python class `CheckMultipleNodesLaunched` described below.
Class description:
Implement the CheckMultipleNodesLaunched class.
Method signatures and docstrings:
- def test_nodes_successful(self, node_list): Check if all the nodes were launched correctly.
- def test_node_does_not_exist(self, node_list): I... | 1d97c4fc7445554f6f85f63305d424fc017212a0 | <|skeleton|>
class CheckMultipleNodesLaunched:
def test_nodes_successful(self, node_list):
"""Check if all the nodes were launched correctly."""
<|body_0|>
def test_node_does_not_exist(self, node_list):
"""Insert a invalid node name that should not exist."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckMultipleNodesLaunched:
def test_nodes_successful(self, node_list):
"""Check if all the nodes were launched correctly."""
wait_for_nodes_1 = WaitForNodes(node_list, timeout=10.0)
assert wait_for_nodes_1.wait()
assert wait_for_nodes_1.get_nodes_not_found() == set()
w... | the_stack_v2_python_sparse | launch_testing/launch_testing_examples/launch_testing_examples/check_multiple_nodes_launch_test.py | ros2/examples | train | 560 | |
a8fc1baf24d2e757b9fa77bc2a4630e897be0027 | [
"def dfs(root, temp_str=''):\n if root is None:\n temp_str += 'None,'\n else:\n temp_str += str(root.val) + ','\n temp_str = dfs(root.left, temp_str)\n temp_str = dfs(root.right, temp_str)\n return temp_str\nreturn dfs(root)",
"def rdeserialize(l):\n \"\"\" a recursive help... | <|body_start_0|>
def dfs(root, temp_str=''):
if root is None:
temp_str += 'None,'
else:
temp_str += str(root.val) + ','
temp_str = dfs(root.left, temp_str)
temp_str = dfs(root.right, temp_str)
return temp_str
... | Codec | [] | 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_066802 | 2,666 | no_license | [
{
"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_018775 | 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:... | 7965e8232d604edb40871cf46520b168a8be2834 | <|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 dfs(root, temp_str=''):
if root is None:
temp_str += 'None,'
else:
temp_str += str(root.val) + ','
temp_str = ... | the_stack_v2_python_sparse | leetcode/hard/297_Serialize_and_Deserialize_Binary_Tree.py | ambarish710/python_concepts | train | 0 | |
cc639848fefbadf3f664190c4f3bc8978d9bf84a | [
"size, ans = (len(s), 0)\nmemo = [0] * size\nfor i in range(1, size):\n if ')' == s[i] and i - memo[i - 1] > 0 and ('(' == s[i - memo[i - 1] - 1]):\n memo[i] = memo[i - 1] + 2 + (memo[i - memo[i - 1] - 2] if i - memo[i - 1] > 1 else 0)\n ans = max(ans, memo[i])\nreturn ans",
"size, ans = (len(s),... | <|body_start_0|>
size, ans = (len(s), 0)
memo = [0] * size
for i in range(1, size):
if ')' == s[i] and i - memo[i - 1] > 0 and ('(' == s[i - memo[i - 1] - 1]):
memo[i] = memo[i - 1] + 2 + (memo[i - memo[i - 1] - 2] if i - memo[i - 1] > 1 else 0)
ans = ... | SolutionLongestValidParentheses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionLongestValidParentheses:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size, ans = (len(s), ... | stack_v2_sparse_classes_75kplus_train_066803 | 1,052 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses1",
"signature": "def longestValidParentheses1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000986 | Implement the Python class `SolutionLongestValidParentheses` described below.
Class description:
Implement the SolutionLongestValidParentheses class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses1(self, s): :type s: str :rtype: int | Implement the Python class `SolutionLongestValidParentheses` described below.
Class description:
Implement the SolutionLongestValidParentheses class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses1(self, s): :type s: str :rtype: int
<|... | a07d8b3cfd5eadb3c3b2f4383cb8ffc32d52f928 | <|skeleton|>
class SolutionLongestValidParentheses:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolutionLongestValidParentheses:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
size, ans = (len(s), 0)
memo = [0] * size
for i in range(1, size):
if ')' == s[i] and i - memo[i - 1] > 0 and ('(' == s[i - memo[i - 1] - 1]):
memo[... | the_stack_v2_python_sparse | python/LongestValidParentheses.py | hellocomrade/happycoding | train | 5 | |
abb52a4a61bbfdebb958e6b1fefc40fe8b1e5d09 | [
"self.datastore_entity_vec = datastore_entity_vec\nself.network_config = network_config\nself.parent_source = parent_source\nself.rename_object_params = rename_object_params\nself.resource_pool_entity = resource_pool_entity\nself.target_datastore_folder = target_datastore_folder\nself.target_vm_folder = target_vm_f... | <|body_start_0|>
self.datastore_entity_vec = datastore_entity_vec
self.network_config = network_config
self.parent_source = parent_source
self.rename_object_params = rename_object_params
self.resource_pool_entity = resource_pool_entity
self.target_datastore_folder = targe... | Implementation of the 'VmwareStandbyResource' model. TODO: type description here. Attributes: datastore_entity_vec (list of EntityProto): Datastore entities where the standby VM should be created. network_config (RestoredObjectNetworkConfigProto): Network configuration for the standby VM. parent_source (EntityProto): T... | VmwareStandbyResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmwareStandbyResource:
"""Implementation of the 'VmwareStandbyResource' model. TODO: type description here. Attributes: datastore_entity_vec (list of EntityProto): Datastore entities where the standby VM should be created. network_config (RestoredObjectNetworkConfigProto): Network configuration f... | stack_v2_sparse_classes_75kplus_train_066804 | 4,811 | permissive | [
{
"docstring": "Constructor for the VmwareStandbyResource class",
"name": "__init__",
"signature": "def __init__(self, datastore_entity_vec=None, network_config=None, parent_source=None, rename_object_params=None, resource_pool_entity=None, target_datastore_folder=None, target_vm_folder=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_033315 | Implement the Python class `VmwareStandbyResource` described below.
Class description:
Implementation of the 'VmwareStandbyResource' model. TODO: type description here. Attributes: datastore_entity_vec (list of EntityProto): Datastore entities where the standby VM should be created. network_config (RestoredObjectNetwo... | Implement the Python class `VmwareStandbyResource` described below.
Class description:
Implementation of the 'VmwareStandbyResource' model. TODO: type description here. Attributes: datastore_entity_vec (list of EntityProto): Datastore entities where the standby VM should be created. network_config (RestoredObjectNetwo... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VmwareStandbyResource:
"""Implementation of the 'VmwareStandbyResource' model. TODO: type description here. Attributes: datastore_entity_vec (list of EntityProto): Datastore entities where the standby VM should be created. network_config (RestoredObjectNetworkConfigProto): Network configuration f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VmwareStandbyResource:
"""Implementation of the 'VmwareStandbyResource' model. TODO: type description here. Attributes: datastore_entity_vec (list of EntityProto): Datastore entities where the standby VM should be created. network_config (RestoredObjectNetworkConfigProto): Network configuration for the standb... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vmware_standby_resource.py | cohesity/management-sdk-python | train | 24 |
6d7e1f8a1a096364cc493ba82661ee7184ab62a9 | [
"super().__init__()\nif out_channels is None:\n out_channels = in_channels\nself.in_channels, self.out_channels = (in_channels, out_channels)\nself.map = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation)",
"x = self.map(input)\nx_gate = torch.sigmo... | <|body_start_0|>
super().__init__()
if out_channels is None:
out_channels = in_channels
self.in_channels, self.out_channels = (in_channels, out_channels)
self.map = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation... | Sigmoid Linear Units for 2D inputs | SiLU2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batc... | stack_v2_sparse_classes_75kplus_train_066805 | 2,967 | no_license | [
{
"docstring": "Args: in_channels <int> out_channels <int>",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1))"
},
{
"docstring": "Args: input (batch_size, in_channels, H, W) Returns: output (batch_size, o... | 2 | stack_v2_sparse_classes_30k_train_010912 | Implement the Python class `SiLU2d` described below.
Class description:
Sigmoid Linear Units for 2D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): Args: in_channels <int> out_channels <int>
- def forward(self, inpu... | Implement the Python class `SiLU2d` described below.
Class description:
Sigmoid Linear Units for 2D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): Args: in_channels <int> out_channels <int>
- def forward(self, inpu... | 4f7f77406cf580785ebf932d78069e7d6e35b765 | <|skeleton|>
class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
super().__init__()
if out_channels is None:
out_channels = in_c... | the_stack_v2_python_sparse | src/models/silu.py | shelly-tang/DNN-based_source_separation | train | 0 |
f0c5172908af582a79d6c0bba1a0e1efb5e08e6e | [
"action = self.tcex.playbook.read(self.args.action)\ndomain = self.tcex.playbook.read(self.args.domain)\nif action == 'decode':\n self.updated_domain = domain.encode('idna').decode('utf-8')\nelif action == 'encode':\n self.updated_domain = domain.encode('utf-8').decode('idna')\nself.exit_message = '{} has bee... | <|body_start_0|>
action = self.tcex.playbook.read(self.args.action)
domain = self.tcex.playbook.read(self.args.domain)
if action == 'decode':
self.updated_domain = domain.encode('idna').decode('utf-8')
elif action == 'encode':
self.updated_domain = domain.encode('... | Playbook App | App | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""Playbook App"""
def run(self):
"""Run the App main logic. This method should contain the core logic of the App."""
<|body_0|>
def write_output(self):
"""Write the Playbook output variables. This method should be overridden with the output variables define... | stack_v2_sparse_classes_75kplus_train_066806 | 1,270 | permissive | [
{
"docstring": "Run the App main logic. This method should contain the core logic of the App.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Write the Playbook output variables. This method should be overridden with the output variables defined in the install.json configuration... | 2 | stack_v2_sparse_classes_30k_test_001971 | Implement the Python class `App` described below.
Class description:
Playbook App
Method signatures and docstrings:
- def run(self): Run the App main logic. This method should contain the core logic of the App.
- def write_output(self): Write the Playbook output variables. This method should be overridden with the ou... | Implement the Python class `App` described below.
Class description:
Playbook App
Method signatures and docstrings:
- def run(self): Run the App main logic. This method should contain the core logic of the App.
- def write_output(self): Write the Playbook output variables. This method should be overridden with the ou... | 0f2e6a2d1c71f104b1522fd68ec01b9f9f3b92f9 | <|skeleton|>
class App:
"""Playbook App"""
def run(self):
"""Run the App main logic. This method should contain the core logic of the App."""
<|body_0|>
def write_output(self):
"""Write the Playbook output variables. This method should be overridden with the output variables define... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class App:
"""Playbook App"""
def run(self):
"""Run the App main logic. This method should contain the core logic of the App."""
action = self.tcex.playbook.read(self.args.action)
domain = self.tcex.playbook.read(self.args.domain)
if action == 'decode':
self.updated_... | the_stack_v2_python_sparse | apps/TCPB_-_Punycode_Decoder/app.py | ThreatConnect-Inc/threatconnect-playbooks | train | 76 |
769a44c9d325a1bbc356c9db97a6e338a4e2bcd5 | [
"if not s or not wordDict:\n return []\nn = len(s)\nf = [[] for i in range(n)]\nfor i in range(n - 1, -1, -1):\n for j in range(i + 1, n + 1):\n if s[i:j] in wordDict:\n if j == n or len(f[j]) > 0:\n f[i].append(j)\nprint(f)\nreturn self.dfs(0, s, f, '', [])",
"if p == len(s... | <|body_start_0|>
if not s or not wordDict:
return []
n = len(s)
f = [[] for i in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n + 1):
if s[i:j] in wordDict:
if j == n or len(f[j]) > 0:
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索"""
<|body_0|>
def dfs(self, p, s, f, now, res):
"""深度优先搜索,当前单词搜索完之后... | stack_v2_sparse_classes_75kplus_train_066807 | 2,910 | no_license | [
{
"docstring": "利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": "深度优先搜索,当前单词搜索完之后,从结束为止下一个字符开始搜索",
... | 2 | stack_v2_sparse_classes_30k_train_052436 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): 利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): 利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,... | 95dddb78bccd169d9d219a473627361fe739ab5e | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索"""
<|body_0|>
def dfs(self, p, s, f, now, res):
"""深度优先搜索,当前单词搜索完之后... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wordBreak(self, s, wordDict):
"""利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索"""
if not s or not wordDict:
return []
n = len(s)
f = [[] for i in... | the_stack_v2_python_sparse | BFS&DFS/wordBreak2.py | Philex5/codingPractice | train | 0 | |
6c430eafa9e0a5e6493c7a0c725e43cfb199fed9 | [
"if G.Env.save_transformed_metrics:\n self.evaluate('holdout', self.data_holdout.target.T.run, self.data_holdout.prediction.T.run)\nelse:\n self.evaluate('holdout', self.data_holdout.target.fold, self.data_holdout.prediction.run)\nsuper().on_run_end()",
"if G.Env.save_transformed_metrics:\n self.evaluate... | <|body_start_0|>
if G.Env.save_transformed_metrics:
self.evaluate('holdout', self.data_holdout.target.T.run, self.data_holdout.prediction.T.run)
else:
self.evaluate('holdout', self.data_holdout.target.fold, self.data_holdout.prediction.run)
super().on_run_end()
<|end_body... | EvaluatorHoldout | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluatorHoldout:
def on_run_end(self):
"""Evaluate holdout predictions for the run"""
<|body_0|>
def on_fold_end(self):
"""Evaluate (run-averaged) holdout predictions for the fold"""
<|body_1|>
def on_rep_end(self):
"""Evaluate (run-averaged) ho... | stack_v2_sparse_classes_75kplus_train_066808 | 5,856 | permissive | [
{
"docstring": "Evaluate holdout predictions for the run",
"name": "on_run_end",
"signature": "def on_run_end(self)"
},
{
"docstring": "Evaluate (run-averaged) holdout predictions for the fold",
"name": "on_fold_end",
"signature": "def on_fold_end(self)"
},
{
"docstring": "Evalua... | 4 | stack_v2_sparse_classes_30k_train_021406 | Implement the Python class `EvaluatorHoldout` described below.
Class description:
Implement the EvaluatorHoldout class.
Method signatures and docstrings:
- def on_run_end(self): Evaluate holdout predictions for the run
- def on_fold_end(self): Evaluate (run-averaged) holdout predictions for the fold
- def on_rep_end(... | Implement the Python class `EvaluatorHoldout` described below.
Class description:
Implement the EvaluatorHoldout class.
Method signatures and docstrings:
- def on_run_end(self): Evaluate holdout predictions for the run
- def on_fold_end(self): Evaluate (run-averaged) holdout predictions for the fold
- def on_rep_end(... | 3709d5e97dd23efa0df1b79982ae029789e1af57 | <|skeleton|>
class EvaluatorHoldout:
def on_run_end(self):
"""Evaluate holdout predictions for the run"""
<|body_0|>
def on_fold_end(self):
"""Evaluate (run-averaged) holdout predictions for the fold"""
<|body_1|>
def on_rep_end(self):
"""Evaluate (run-averaged) ho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EvaluatorHoldout:
def on_run_end(self):
"""Evaluate holdout predictions for the run"""
if G.Env.save_transformed_metrics:
self.evaluate('holdout', self.data_holdout.target.T.run, self.data_holdout.prediction.T.run)
else:
self.evaluate('holdout', self.data_holdou... | the_stack_v2_python_sparse | hyperparameter_hunter/callbacks/evaluators.py | shaoeric/hyperparameter_hunter | train | 0 | |
bab1fe6877936cafc715e912e4bb3274e57f362a | [
"s, h = common.service_json_request(self.ipaddr, self.port, 'GET', self.URI_VPOOL_SHOW.format(vpooltype, uri), None)\no = common.json_decode(s)\nif o['inactive']:\n return None\nreturn o",
"if common.is_uri(name):\n return name\ns, h = common.service_json_request(self.ipaddr, self.port, 'GET', self.URI_VPOO... | <|body_start_0|>
s, h = common.service_json_request(self.ipaddr, self.port, 'GET', self.URI_VPOOL_SHOW.format(vpooltype, uri), None)
o = common.json_decode(s)
if o['inactive']:
return None
return o
<|end_body_0|>
<|body_start_1|>
if common.is_uri(name):
r... | VirtualPool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualPool:
def vpool_show_uri(self, vpooltype, uri):
"""Makes REST API call and retrieves vpool details based on UUID. This function will take uri as input and returns with all parameters of VPOOL like label, urn and type. :param vpooltype : Type of virtual pool {'block'} :param uri : ... | stack_v2_sparse_classes_75kplus_train_066809 | 2,887 | permissive | [
{
"docstring": "Makes REST API call and retrieves vpool details based on UUID. This function will take uri as input and returns with all parameters of VPOOL like label, urn and type. :param vpooltype : Type of virtual pool {'block'} :param uri : unique resource identifier of the vpool :returns: object containin... | 2 | stack_v2_sparse_classes_30k_train_050040 | Implement the Python class `VirtualPool` described below.
Class description:
Implement the VirtualPool class.
Method signatures and docstrings:
- def vpool_show_uri(self, vpooltype, uri): Makes REST API call and retrieves vpool details based on UUID. This function will take uri as input and returns with all parameter... | Implement the Python class `VirtualPool` described below.
Class description:
Implement the VirtualPool class.
Method signatures and docstrings:
- def vpool_show_uri(self, vpooltype, uri): Makes REST API call and retrieves vpool details based on UUID. This function will take uri as input and returns with all parameter... | f8f1a4fe4a6da6e77d5dbff4f96eb123ec445230 | <|skeleton|>
class VirtualPool:
def vpool_show_uri(self, vpooltype, uri):
"""Makes REST API call and retrieves vpool details based on UUID. This function will take uri as input and returns with all parameters of VPOOL like label, urn and type. :param vpooltype : Type of virtual pool {'block'} :param uri : ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VirtualPool:
def vpool_show_uri(self, vpooltype, uri):
"""Makes REST API call and retrieves vpool details based on UUID. This function will take uri as input and returns with all parameters of VPOOL like label, urn and type. :param vpooltype : Type of virtual pool {'block'} :param uri : unique resourc... | the_stack_v2_python_sparse | cinder/volume/drivers/coprhd/helpers/virtualpool.py | Nexenta/cinder | train | 3 | |
30137f72106c75f2d4b0a328118d0324e34e7b94 | [
"core.component.__init__(self, ofconn)\nmc.get_client()\nserver.register_event_handler(ofevents.pktin.name, self)",
"if isinstance(event, ofevents.pktin) and event.match.dl_type == dpkt.ethernet.ETH_TYPE_ARP:\n iport = mc.get(nat.SW_INNER_PORT)\n intfs = self.get_intf_n_range()\n lointf = mc.get(nat.SW_I... | <|body_start_0|>
core.component.__init__(self, ofconn)
mc.get_client()
server.register_event_handler(ofevents.pktin.name, self)
<|end_body_0|>
<|body_start_1|>
if isinstance(event, ofevents.pktin) and event.match.dl_type == dpkt.ethernet.ETH_TYPE_ARP:
iport = mc.get(nat.SW_I... | Class to handle arp in COIN @author ykk @date Jun 2011 | arp_handler | [
"LicenseRef-scancode-x11-stanford"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class arp_handler:
"""Class to handle arp in COIN @author ykk @date Jun 2011"""
def __init__(self, server, ofconn):
"""Initialize @param server yapc core @param conn reference to connections @param sfr send flow removed or not"""
<|body_0|>
def processevent(self, event):
... | stack_v2_sparse_classes_75kplus_train_066810 | 32,475 | permissive | [
{
"docstring": "Initialize @param server yapc core @param conn reference to connections @param sfr send flow removed or not",
"name": "__init__",
"signature": "def __init__(self, server, ofconn)"
},
{
"docstring": "Event handler (for ARP only) @param event event to handle @return false if proces... | 5 | null | Implement the Python class `arp_handler` described below.
Class description:
Class to handle arp in COIN @author ykk @date Jun 2011
Method signatures and docstrings:
- def __init__(self, server, ofconn): Initialize @param server yapc core @param conn reference to connections @param sfr send flow removed or not
- def ... | Implement the Python class `arp_handler` described below.
Class description:
Class to handle arp in COIN @author ykk @date Jun 2011
Method signatures and docstrings:
- def __init__(self, server, ofconn): Initialize @param server yapc core @param conn reference to connections @param sfr send flow removed or not
- def ... | c3f5a31b74d5587671329eea9582ac8aed0c58a4 | <|skeleton|>
class arp_handler:
"""Class to handle arp in COIN @author ykk @date Jun 2011"""
def __init__(self, server, ofconn):
"""Initialize @param server yapc core @param conn reference to connections @param sfr send flow removed or not"""
<|body_0|>
def processevent(self, event):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class arp_handler:
"""Class to handle arp in COIN @author ykk @date Jun 2011"""
def __init__(self, server, ofconn):
"""Initialize @param server yapc core @param conn reference to connections @param sfr send flow removed or not"""
core.component.__init__(self, ofconn)
mc.get_client()
... | the_stack_v2_python_sparse | yapc/coin/nat.py | yapkke/yapc | train | 1 |
f89e331a97b2b4594e92f037d2f0f85cf6df6391 | [
"self.set_header('content-type', 'application/json')\nfollowed_str = self.get_argument('is_followed', default=None)\nignored_str = self.get_argument('is_ignored', default=None)\nkeyword_type = self.get_argument('keyword_type', default=None)\nDimensions = ('page', 'did', 'uid', 'ip')\nif keyword_type not in Dimensio... | <|body_start_0|>
self.set_header('content-type', 'application/json')
followed_str = self.get_argument('is_followed', default=None)
ignored_str = self.get_argument('is_ignored', default=None)
keyword_type = self.get_argument('keyword_type', default=None)
Dimensions = ('page', 'did... | FollowKeywordHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowKeywordHandler:
def get(self):
"""关注管理关键字列表 @API summary: 查询所有爬虫关注关键字 tags: - platform parameters: - name: is_followed required: false in: query type: boolean description: 关键字是否关注 - name: is_ignored required: false in: query type: boolean description: 关键字是否忽略 - name: keyword_type r... | stack_v2_sparse_classes_75kplus_train_066811 | 5,169 | permissive | [
{
"docstring": "关注管理关键字列表 @API summary: 查询所有爬虫关注关键字 tags: - platform parameters: - name: is_followed required: false in: query type: boolean description: 关键字是否关注 - name: is_ignored required: false in: query type: boolean description: 关键字是否忽略 - name: keyword_type required: true in: query type: string description... | 2 | stack_v2_sparse_classes_30k_train_033419 | Implement the Python class `FollowKeywordHandler` described below.
Class description:
Implement the FollowKeywordHandler class.
Method signatures and docstrings:
- def get(self): 关注管理关键字列表 @API summary: 查询所有爬虫关注关键字 tags: - platform parameters: - name: is_followed required: false in: query type: boolean description: 关... | Implement the Python class `FollowKeywordHandler` described below.
Class description:
Implement the FollowKeywordHandler class.
Method signatures and docstrings:
- def get(self): 关注管理关键字列表 @API summary: 查询所有爬虫关注关键字 tags: - platform parameters: - name: is_followed required: false in: query type: boolean description: 关... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class FollowKeywordHandler:
def get(self):
"""关注管理关键字列表 @API summary: 查询所有爬虫关注关键字 tags: - platform parameters: - name: is_followed required: false in: query type: boolean description: 关键字是否关注 - name: is_ignored required: false in: query type: boolean description: 关键字是否忽略 - name: keyword_type r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FollowKeywordHandler:
def get(self):
"""关注管理关键字列表 @API summary: 查询所有爬虫关注关键字 tags: - platform parameters: - name: is_followed required: false in: query type: boolean description: 关键字是否关注 - name: is_ignored required: false in: query type: boolean description: 关键字是否忽略 - name: keyword_type required: true ... | the_stack_v2_python_sparse | nebula/views/follow.py | threathunterX/nebula_web | train | 2 | |
5c30d6774065302319daeeea4ed5f73ec012e917 | [
"self.antall_inkasso_field = antall_inkasso_field\nself.ajour_dato_inkasso_field = APIHelper.RFC3339DateTime(ajour_dato_inkasso_field) if ajour_dato_inkasso_field else None\nself.antall_panter_losore_field = antall_panter_losore_field\nself.ajour_dato_losore_field = APIHelper.RFC3339DateTime(ajour_dato_losore_field... | <|body_start_0|>
self.antall_inkasso_field = antall_inkasso_field
self.ajour_dato_inkasso_field = APIHelper.RFC3339DateTime(ajour_dato_inkasso_field) if ajour_dato_inkasso_field else None
self.antall_panter_losore_field = antall_panter_losore_field
self.ajour_dato_losore_field = APIHelpe... | Implementation of the 'BetaSammendrag' model. TODO: type model description here. Attributes: antall_inkasso_field (int): TODO: type description here. ajour_dato_inkasso_field (datetime): TODO: type description here. antall_panter_losore_field (int): TODO: type description here. ajour_dato_losore_field (datetime): TODO:... | BetaSammendrag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BetaSammendrag:
"""Implementation of the 'BetaSammendrag' model. TODO: type model description here. Attributes: antall_inkasso_field (int): TODO: type description here. ajour_dato_inkasso_field (datetime): TODO: type description here. antall_panter_losore_field (int): TODO: type description here.... | stack_v2_sparse_classes_75kplus_train_066812 | 4,350 | permissive | [
{
"docstring": "Constructor for the BetaSammendrag class",
"name": "__init__",
"signature": "def __init__(self, antall_inkasso_field=None, ajour_dato_inkasso_field=None, antall_panter_losore_field=None, ajour_dato_losore_field=None, antall_panter_eiendom_field=None, ajour_dato_eiendom_field=None, additi... | 2 | stack_v2_sparse_classes_30k_train_009746 | Implement the Python class `BetaSammendrag` described below.
Class description:
Implementation of the 'BetaSammendrag' model. TODO: type model description here. Attributes: antall_inkasso_field (int): TODO: type description here. ajour_dato_inkasso_field (datetime): TODO: type description here. antall_panter_losore_fi... | Implement the Python class `BetaSammendrag` described below.
Class description:
Implementation of the 'BetaSammendrag' model. TODO: type model description here. Attributes: antall_inkasso_field (int): TODO: type description here. ajour_dato_inkasso_field (datetime): TODO: type description here. antall_panter_losore_fi... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class BetaSammendrag:
"""Implementation of the 'BetaSammendrag' model. TODO: type model description here. Attributes: antall_inkasso_field (int): TODO: type description here. ajour_dato_inkasso_field (datetime): TODO: type description here. antall_panter_losore_field (int): TODO: type description here.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BetaSammendrag:
"""Implementation of the 'BetaSammendrag' model. TODO: type model description here. Attributes: antall_inkasso_field (int): TODO: type description here. ajour_dato_inkasso_field (datetime): TODO: type description here. antall_panter_losore_field (int): TODO: type description here. ajour_dato_l... | the_stack_v2_python_sparse | idfy_rest_client/models/beta_sammendrag.py | dealflowteam/Idfy | train | 0 |
18d23af903fd7fe11fc9e7be95af99543c632cfa | [
"try:\n user = CustomUser.objects.get(email=username)\n if user.check_password(password):\n return user\nexcept CustomUser.DoesNotExist:\n return None",
"try:\n user = CustomUser.objects.get(pk=user_id)\n if user.is_active:\n return user\n return None\nexcept CustomUser.DoesNotExis... | <|body_start_0|>
try:
user = CustomUser.objects.get(email=username)
if user.check_password(password):
return user
except CustomUser.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
try:
user = CustomUser.objects.get(pk=use... | Class which holds methods for Custom user authentication | CustomUserAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserAuth:
"""Class which holds methods for Custom user authentication"""
def authenticate(self, username=None, password=None):
"""User login method :param username: username (email) :param password: user password :return:"""
<|body_0|>
def get_user(self, user_id):
... | stack_v2_sparse_classes_75kplus_train_066813 | 1,013 | no_license | [
{
"docstring": "User login method :param username: username (email) :param password: user password :return:",
"name": "authenticate",
"signature": "def authenticate(self, username=None, password=None)"
},
{
"docstring": "Get user by id :param user_id: id :return: User",
"name": "get_user",
... | 2 | null | Implement the Python class `CustomUserAuth` described below.
Class description:
Class which holds methods for Custom user authentication
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): User login method :param username: username (email) :param password: user password :return:... | Implement the Python class `CustomUserAuth` described below.
Class description:
Class which holds methods for Custom user authentication
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): User login method :param username: username (email) :param password: user password :return:... | 83f5acb57862c1766748e7bed92335a3e9c71957 | <|skeleton|>
class CustomUserAuth:
"""Class which holds methods for Custom user authentication"""
def authenticate(self, username=None, password=None):
"""User login method :param username: username (email) :param password: user password :return:"""
<|body_0|>
def get_user(self, user_id):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUserAuth:
"""Class which holds methods for Custom user authentication"""
def authenticate(self, username=None, password=None):
"""User login method :param username: username (email) :param password: user password :return:"""
try:
user = CustomUser.objects.get(email=usern... | the_stack_v2_python_sparse | moninag/registration/backends.py | Lv-219-Python/MoniNag | train | 4 |
814cfc5a34effc2a440c60d5aa43db239f6266bb | [
"category = classifier.classify(key)\nif category in container:\n container[category].append(value)\nelse:\n container.update({category: subCollectionFactory(value)})",
"elapsedTscGroup = {}\nfor txn in txnSubCollection:\n if txn.hasProbes([beginProbe, endProbe]):\n beginCounter = txn.getCounterFo... | <|body_start_0|>
category = classifier.classify(key)
if category in container:
container[category].append(value)
else:
container.update({category: subCollectionFactory(value)})
<|end_body_0|>
<|body_start_1|>
elapsedTscGroup = {}
for txn in txnSubCollecti... | Aggregates transaction by categories | TxnAggregator | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated value... | stack_v2_sparse_classes_75kplus_train_066814 | 5,883 | permissive | [
{
"docstring": "Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated values :param subCollectionFactory: Callable used to build an instance of subcollection :param classifier: Predicate to classify transactions into different categ... | 4 | stack_v2_sparse_classes_30k_train_016841 | Implement the Python class `TxnAggregator` described below.
Class description:
Aggregates transaction by categories
Method signatures and docstrings:
- def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value): Adds transaction to a transaction subcollection with matching category :param cont... | Implement the Python class `TxnAggregator` described below.
Class description:
Aggregates transaction by categories
Method signatures and docstrings:
- def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value): Adds transaction to a transaction subcollection with matching category :param cont... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated values :param subC... | the_stack_v2_python_sparse | scripts/lib/xpedite/analytics/aggregator.py | dendisuhubdy/Xpedite | train | 1 |
8ec0ddc8b8d32afd52b2070f01a27d7faf7db5f3 | [
"self.n = n\n' Index of the band for which to compute effective mass.\\n\\n Can also be a callable taking the extraction object on input and\\n returning a number.\\n '\nsuper(EffectiveMass, self).__init__(**kwargs)",
"from numpy import average\nout = super(EffectiveMass, self).run(indiv, outdir,... | <|body_start_0|>
self.n = n
' Index of the band for which to compute effective mass.\n\n Can also be a callable taking the extraction object on input and\n returning a number.\n '
super(EffectiveMass, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
from numpy i... | Evaluates effective mass. | EffectiveMass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EffectiveMass:
"""Evaluates effective mass."""
def __init__(self, n=0, **kwargs):
"""Computes effective mass for a given direction. For other keyword arguments, see `Bandgap`. :Parameters: n : int or callable Index of the band for which to compute effective mass. If callable, takes t... | stack_v2_sparse_classes_75kplus_train_066815 | 9,676 | no_license | [
{
"docstring": "Computes effective mass for a given direction. For other keyword arguments, see `Bandgap`. :Parameters: n : int or callable Index of the band for which to compute effective mass. If callable, takes the extraction object on input and should return a number.",
"name": "__init__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_036358 | Implement the Python class `EffectiveMass` described below.
Class description:
Evaluates effective mass.
Method signatures and docstrings:
- def __init__(self, n=0, **kwargs): Computes effective mass for a given direction. For other keyword arguments, see `Bandgap`. :Parameters: n : int or callable Index of the band ... | Implement the Python class `EffectiveMass` described below.
Class description:
Evaluates effective mass.
Method signatures and docstrings:
- def __init__(self, n=0, **kwargs): Computes effective mass for a given direction. For other keyword arguments, see `Bandgap`. :Parameters: n : int or callable Index of the band ... | 9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3 | <|skeleton|>
class EffectiveMass:
"""Evaluates effective mass."""
def __init__(self, n=0, **kwargs):
"""Computes effective mass for a given direction. For other keyword arguments, see `Bandgap`. :Parameters: n : int or callable Index of the band for which to compute effective mass. If callable, takes t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EffectiveMass:
"""Evaluates effective mass."""
def __init__(self, n=0, **kwargs):
"""Computes effective mass for a given direction. For other keyword arguments, see `Bandgap`. :Parameters: n : int or callable Index of the band for which to compute effective mass. If callable, takes the extraction... | the_stack_v2_python_sparse | ga/escan/evaluator.py | Shibu778/LaDa | train | 0 |
51a80ef7b85d759dcdce8dd65783d9426266bc6a | [
"self.scale = scale\nself.cost_type = cost_type\nself.func = func\nerr_str = 'Illegal GAN cost type, can only be: gen or dis'\nassert self.cost_type in ['dis', 'gen']\nerr_str = 'Unsupported GAN cost function, supported: original, modified, wasserstein'\nassert self.func in ['original', 'modified', 'wasserstein'], ... | <|body_start_0|>
self.scale = scale
self.cost_type = cost_type
self.func = func
err_str = 'Illegal GAN cost type, can only be: gen or dis'
assert self.cost_type in ['dis', 'gen']
err_str = 'Unsupported GAN cost function, supported: original, modified, wasserstein'
... | Discriminator cost for a Generative Adversarial Network The Discriminator cost is a packaged cross-entropy where the inputs with label 0 and the inputs with label 1 are passed in separately. It takes the form :math:`C = \\log (y_data) + \\log (1 - y_noise)` where :math:`y_data` are the fprop outputs of the data minibat... | GANCost | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GANCost:
"""Discriminator cost for a Generative Adversarial Network The Discriminator cost is a packaged cross-entropy where the inputs with label 0 and the inputs with label 1 are passed in separately. It takes the form :math:`C = \\log (y_data) + \\log (1 - y_noise)` where :math:`y_data` are th... | stack_v2_sparse_classes_75kplus_train_066816 | 28,077 | permissive | [
{
"docstring": "Args: scale (float, optional): Amount by which to scale the backpropagated error (default: 1) cost_type (string): select discriminator cost \"dis\" or generator cost \"gen\" cost_func (string): cost function: choice from \"original\", \"modified\" and \"wasserstein\" (Goodfellow et al. 2014, Arj... | 5 | stack_v2_sparse_classes_30k_train_047063 | Implement the Python class `GANCost` described below.
Class description:
Discriminator cost for a Generative Adversarial Network The Discriminator cost is a packaged cross-entropy where the inputs with label 0 and the inputs with label 1 are passed in separately. It takes the form :math:`C = \\log (y_data) + \\log (1 ... | Implement the Python class `GANCost` described below.
Class description:
Discriminator cost for a Generative Adversarial Network The Discriminator cost is a packaged cross-entropy where the inputs with label 0 and the inputs with label 1 are passed in separately. It takes the form :math:`C = \\log (y_data) + \\log (1 ... | 11fd08f5fab303067c03dfc4d1e4332e12a61187 | <|skeleton|>
class GANCost:
"""Discriminator cost for a Generative Adversarial Network The Discriminator cost is a packaged cross-entropy where the inputs with label 0 and the inputs with label 1 are passed in separately. It takes the form :math:`C = \\log (y_data) + \\log (1 - y_noise)` where :math:`y_data` are th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GANCost:
"""Discriminator cost for a Generative Adversarial Network The Discriminator cost is a packaged cross-entropy where the inputs with label 0 and the inputs with label 1 are passed in separately. It takes the form :math:`C = \\log (y_data) + \\log (1 - y_noise)` where :math:`y_data` are the fprop outpu... | the_stack_v2_python_sparse | skynet/neon/transforms/cost.py | evanjzou/stocks-nn | train | 4 |
fa3815bb0bd94e08baa938f19cf3a84096779979 | [
"select_query = {'tag_count': 'SELECT COUNT(*) FROM %(tagged_item)s\\n WHERE %(tag)s.id = %(tagged_item)s.tag_id\\n AND %(tagged_item)s.content_type_id = %(content_type_id)s\\n ' % {'tagged_item': connection.ops.quote_name(TaggedItem._meta.db_tabl... | <|body_start_0|>
select_query = {'tag_count': 'SELECT COUNT(*) FROM %(tagged_item)s\n WHERE %(tag)s.id = %(tagged_item)s.tag_id\n AND %(tagged_item)s.content_type_id = %(content_type_id)s\n ' % {'tagged_item': connection.ops.quote_name(TaggedI... | MetaTagManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaTagManager:
def most_active(self, content_type_id, num):
"""Returns a list of Tag objects for a particular @content_type_id sorted by the number of objects which have each Tag in descending order. Returns a max of @num objects."""
<|body_0|>
def count_tags(self, tags, mo... | stack_v2_sparse_classes_75kplus_train_066817 | 4,602 | permissive | [
{
"docstring": "Returns a list of Tag objects for a particular @content_type_id sorted by the number of objects which have each Tag in descending order. Returns a max of @num objects.",
"name": "most_active",
"signature": "def most_active(self, content_type_id, num)"
},
{
"docstring": "Attaches ... | 4 | stack_v2_sparse_classes_30k_train_028316 | Implement the Python class `MetaTagManager` described below.
Class description:
Implement the MetaTagManager class.
Method signatures and docstrings:
- def most_active(self, content_type_id, num): Returns a list of Tag objects for a particular @content_type_id sorted by the number of objects which have each Tag in de... | Implement the Python class `MetaTagManager` described below.
Class description:
Implement the MetaTagManager class.
Method signatures and docstrings:
- def most_active(self, content_type_id, num): Returns a list of Tag objects for a particular @content_type_id sorted by the number of objects which have each Tag in de... | 5f8f3b682ac28fd3f464e7a993c3988c1a49eb02 | <|skeleton|>
class MetaTagManager:
def most_active(self, content_type_id, num):
"""Returns a list of Tag objects for a particular @content_type_id sorted by the number of objects which have each Tag in descending order. Returns a max of @num objects."""
<|body_0|>
def count_tags(self, tags, mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetaTagManager:
def most_active(self, content_type_id, num):
"""Returns a list of Tag objects for a particular @content_type_id sorted by the number of objects which have each Tag in descending order. Returns a max of @num objects."""
select_query = {'tag_count': 'SELECT COUNT(*) FROM %(tagged... | the_stack_v2_python_sparse | eruditio/shared_apps/django_metatagging/managers.py | genghisu/eruditio | train | 0 | |
b18cfd722ad1b63ca0af342fa0a2596fe91cc2f3 | [
"self.menu = Menu('Menu Principal:')\nself.view = MenuView(self.menu)\nself.gamecontroller = gamecontroller\nself.nb_rounds = nb_rounds",
"self.menu.add('auto', 'Charger tournoi passé', LoadTournamentController(self.gamecontroller))\nself.menu.add('auto', 'Créer nouveau tournoi', CreateTournamentController(self.g... | <|body_start_0|>
self.menu = Menu('Menu Principal:')
self.view = MenuView(self.menu)
self.gamecontroller = gamecontroller
self.nb_rounds = nb_rounds
<|end_body_0|>
<|body_start_1|>
self.menu.add('auto', 'Charger tournoi passé', LoadTournamentController(self.gamecontroller))
... | Menu principal 1. Charger tournoi passé 2. Créer nouveau tournoi 3. Rapports tournoi 4. Gérer tournoi 5. Gérer joueurs 6. Quitter | HomeMenuController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeMenuController:
"""Menu principal 1. Charger tournoi passé 2. Créer nouveau tournoi 3. Rapports tournoi 4. Gérer tournoi 5. Gérer joueurs 6. Quitter"""
def __init__(self, gamecontroller, nb_rounds=0):
"""Construit le Menu de la classe et la vue pour ce menu. Arguments: gamecontro... | stack_v2_sparse_classes_75kplus_train_066818 | 40,289 | no_license | [
{
"docstring": "Construit le Menu de la classe et la vue pour ce menu. Arguments: gamecontroller (instance de GameController) -- contrôleur général du tournoi. Permet d'accéder à tous les objets et méthodes du tournoi courant.",
"name": "__init__",
"signature": "def __init__(self, gamecontroller, nb_rou... | 2 | stack_v2_sparse_classes_30k_train_017590 | Implement the Python class `HomeMenuController` described below.
Class description:
Menu principal 1. Charger tournoi passé 2. Créer nouveau tournoi 3. Rapports tournoi 4. Gérer tournoi 5. Gérer joueurs 6. Quitter
Method signatures and docstrings:
- def __init__(self, gamecontroller, nb_rounds=0): Construit le Menu d... | Implement the Python class `HomeMenuController` described below.
Class description:
Menu principal 1. Charger tournoi passé 2. Créer nouveau tournoi 3. Rapports tournoi 4. Gérer tournoi 5. Gérer joueurs 6. Quitter
Method signatures and docstrings:
- def __init__(self, gamecontroller, nb_rounds=0): Construit le Menu d... | bd0edae5773d464e30ce40f72be8f8f7d1711f66 | <|skeleton|>
class HomeMenuController:
"""Menu principal 1. Charger tournoi passé 2. Créer nouveau tournoi 3. Rapports tournoi 4. Gérer tournoi 5. Gérer joueurs 6. Quitter"""
def __init__(self, gamecontroller, nb_rounds=0):
"""Construit le Menu de la classe et la vue pour ce menu. Arguments: gamecontro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HomeMenuController:
"""Menu principal 1. Charger tournoi passé 2. Créer nouveau tournoi 3. Rapports tournoi 4. Gérer tournoi 5. Gérer joueurs 6. Quitter"""
def __init__(self, gamecontroller, nb_rounds=0):
"""Construit le Menu de la classe et la vue pour ce menu. Arguments: gamecontroller (instanc... | the_stack_v2_python_sparse | application/controllers/applicationcontroller.py | ChardonBleu/Echecs | train | 0 |
c62c90cd8247c5e6a49689fa4d8d60508a465c40 | [
"super(Logger, self).__init__(self, level=min(console_level, file_level))\n\ndef expand_format_tags(message, use_color=True):\n \"\"\"Expands $*SEQ tags in a string. If use_color is False, removes\n the tags.\n \"\"\"\n if use_color:\n message = message.replace('$RESET', printers.... | <|body_start_0|>
super(Logger, self).__init__(self, level=min(console_level, file_level))
def expand_format_tags(message, use_color=True):
"""Expands $*SEQ tags in a string. If use_color is False, removes
the tags.
"""
if use_color:
... | Implements a multiprocessing-safe logger with timing and colored console output. | Logger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
"""Implements a multiprocessing-safe logger with timing and colored console output."""
def __init__(self, console_level=logging.INFO, filename=None, file_level=logging.DEBUG, no_backups=5):
"""Initializer"""
<|body_0|>
def close(self):
"""Close the logger... | stack_v2_sparse_classes_75kplus_train_066819 | 12,759 | permissive | [
{
"docstring": "Initializer",
"name": "__init__",
"signature": "def __init__(self, console_level=logging.INFO, filename=None, file_level=logging.DEBUG, no_backups=5)"
},
{
"docstring": "Close the logger",
"name": "close",
"signature": "def close(self)"
},
{
"docstring": "Return l... | 3 | stack_v2_sparse_classes_30k_train_028208 | Implement the Python class `Logger` described below.
Class description:
Implements a multiprocessing-safe logger with timing and colored console output.
Method signatures and docstrings:
- def __init__(self, console_level=logging.INFO, filename=None, file_level=logging.DEBUG, no_backups=5): Initializer
- def close(se... | Implement the Python class `Logger` described below.
Class description:
Implements a multiprocessing-safe logger with timing and colored console output.
Method signatures and docstrings:
- def __init__(self, console_level=logging.INFO, filename=None, file_level=logging.DEBUG, no_backups=5): Initializer
- def close(se... | c426565d870d944bd5b9712629d8f1ba2527c67f | <|skeleton|>
class Logger:
"""Implements a multiprocessing-safe logger with timing and colored console output."""
def __init__(self, console_level=logging.INFO, filename=None, file_level=logging.DEBUG, no_backups=5):
"""Initializer"""
<|body_0|>
def close(self):
"""Close the logger... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
"""Implements a multiprocessing-safe logger with timing and colored console output."""
def __init__(self, console_level=logging.INFO, filename=None, file_level=logging.DEBUG, no_backups=5):
"""Initializer"""
super(Logger, self).__init__(self, level=min(console_level, file_level))
... | the_stack_v2_python_sparse | pyexperiment/Logger.py | olivierh59500/pyexperiment | train | 0 |
622af55a76e82c05cace9b67496e828004002f64 | [
"application.help()\nstatus = self.pyre_interactiveSession(application=application)\nreturn status",
"tag = application.pyre_namespace or application.pyre_name if application else 'pyre'\nimport code, sys\nself.pyre_enrich(tag)\nsys.ps1 = f'{tag}: '\nsys.ps2 = ' ... '\nsymbols = {}\nif application:\n symbols[... | <|body_start_0|>
application.help()
status = self.pyre_interactiveSession(application=application)
return status
<|end_body_0|>
<|body_start_1|>
tag = application.pyre_namespace or application.pyre_name if application else 'pyre'
import code, sys
self.pyre_enrich(tag)
... | A shell that invokes the main application behavior and then enters interactive mode | Interactive | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interactive:
"""A shell that invokes the main application behavior and then enters interactive mode"""
def launch(self, application, *args, **kwds):
"""Invoke the application behavior"""
<|body_0|>
def pyre_interactiveSession(self, application=None, banner=None, context=... | stack_v2_sparse_classes_75kplus_train_066820 | 3,835 | permissive | [
{
"docstring": "Invoke the application behavior",
"name": "launch",
"signature": "def launch(self, application, *args, **kwds)"
},
{
"docstring": "Convert this session to an interactive one",
"name": "pyre_interactiveSession",
"signature": "def pyre_interactiveSession(self, application=N... | 3 | stack_v2_sparse_classes_30k_train_039283 | Implement the Python class `Interactive` described below.
Class description:
A shell that invokes the main application behavior and then enters interactive mode
Method signatures and docstrings:
- def launch(self, application, *args, **kwds): Invoke the application behavior
- def pyre_interactiveSession(self, applica... | Implement the Python class `Interactive` described below.
Class description:
A shell that invokes the main application behavior and then enters interactive mode
Method signatures and docstrings:
- def launch(self, application, *args, **kwds): Invoke the application behavior
- def pyre_interactiveSession(self, applica... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Interactive:
"""A shell that invokes the main application behavior and then enters interactive mode"""
def launch(self, application, *args, **kwds):
"""Invoke the application behavior"""
<|body_0|>
def pyre_interactiveSession(self, application=None, banner=None, context=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interactive:
"""A shell that invokes the main application behavior and then enters interactive mode"""
def launch(self, application, *args, **kwds):
"""Invoke the application behavior"""
application.help()
status = self.pyre_interactiveSession(application=application)
retu... | the_stack_v2_python_sparse | packages/pyre/shells/Interactive.py | pyre/pyre | train | 27 |
a34d1ca3a8b4ec696bdadbb45bc93c83c2bd6a7d | [
"self.loc = loc\nself.scale = scale\nself.NG = NormalDist()\nsuper().__init__(ContinuousSpace(-np.inf, np.inf))",
"y1 = self.NG.sample(num_samples)\ny2 = self.NG.sample(num_samples)\nreturn self.scale * (y1 / y2) + self.loc",
"loc = self.loc\nscale = self.scale\nv = m.pi * self.scale * (1 + np.square((x - loc) ... | <|body_start_0|>
self.loc = loc
self.scale = scale
self.NG = NormalDist()
super().__init__(ContinuousSpace(-np.inf, np.inf))
<|end_body_0|>
<|body_start_1|>
y1 = self.NG.sample(num_samples)
y2 = self.NG.sample(num_samples)
return self.scale * (y1 / y2) + self.loc... | Simple cauchy distribution. | CauchyDist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CauchyDist:
"""Simple cauchy distribution."""
def __init__(self, loc=1, scale=1):
"""Creates Cauchy(loc, scale) distribution. :param loc Location of the distribution. :param scale Scale of the distribution"""
<|body_0|>
def sample(self, num_samples=1):
"""Generat... | stack_v2_sparse_classes_75kplus_train_066821 | 1,451 | permissive | [
{
"docstring": "Creates Cauchy(loc, scale) distribution. :param loc Location of the distribution. :param scale Scale of the distribution",
"name": "__init__",
"signature": "def __init__(self, loc=1, scale=1)"
},
{
"docstring": "Generate random numbers from Cauchy(mean,scale) by using ratio of no... | 3 | stack_v2_sparse_classes_30k_train_018568 | Implement the Python class `CauchyDist` described below.
Class description:
Simple cauchy distribution.
Method signatures and docstrings:
- def __init__(self, loc=1, scale=1): Creates Cauchy(loc, scale) distribution. :param loc Location of the distribution. :param scale Scale of the distribution
- def sample(self, nu... | Implement the Python class `CauchyDist` described below.
Class description:
Simple cauchy distribution.
Method signatures and docstrings:
- def __init__(self, loc=1, scale=1): Creates Cauchy(loc, scale) distribution. :param loc Location of the distribution. :param scale Scale of the distribution
- def sample(self, nu... | 4c854e90bfd4acaa511c1786c96f0610d7aea037 | <|skeleton|>
class CauchyDist:
"""Simple cauchy distribution."""
def __init__(self, loc=1, scale=1):
"""Creates Cauchy(loc, scale) distribution. :param loc Location of the distribution. :param scale Scale of the distribution"""
<|body_0|>
def sample(self, num_samples=1):
"""Generat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CauchyDist:
"""Simple cauchy distribution."""
def __init__(self, loc=1, scale=1):
"""Creates Cauchy(loc, scale) distribution. :param loc Location of the distribution. :param scale Scale of the distribution"""
self.loc = loc
self.scale = scale
self.NG = NormalDist()
... | the_stack_v2_python_sparse | src/continuous/cauchy.py | kosmitive/univariate-distributions | train | 0 |
6105e452e661f52f0105828907c2e5617ebd4fa2 | [
"f = open(fa_file, 'r')\nlines = f.readlines()\ndescription = lines[0][1:].split()\nself.fname = fa_file\nself.name = description[0]\nself.seq = ''.join([x[:-1] for x in lines[1:]])\nself.__setDivergence__(float(description[1].split('=')[1]))\nf.close()",
"self.divergence = nearestDivergence(div)\nself.gi = GAP_P... | <|body_start_0|>
f = open(fa_file, 'r')
lines = f.readlines()
description = lines[0][1:].split()
self.fname = fa_file
self.name = description[0]
self.seq = ''.join([x[:-1] for x in lines[1:]])
self.__setDivergence__(float(description[1].split('=')[1]))
f.c... | Stores information on a given consensus sequence, such as the sequence name, average kimura divergence, and the sequence itself. Fields: fname - Name of .fa file this consensus sequence is derived from. name - Name of the consensus sequence as given in original .fa file. seq - Sequence of bases making up this consensus... | ConsensusSequence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsensusSequence:
"""Stores information on a given consensus sequence, such as the sequence name, average kimura divergence, and the sequence itself. Fields: fname - Name of .fa file this consensus sequence is derived from. name - Name of the consensus sequence as given in original .fa file. seq... | stack_v2_sparse_classes_75kplus_train_066822 | 8,028 | no_license | [
{
"docstring": "Initializes this ConsensusSequence with the given parameters. Retrieves the name and divergence from the given fa file. The first line should be in the following format: >DF######## avg_kimura=#### [name] The first token in this line will be the name of this consensus and the avg_kimura will be ... | 2 | stack_v2_sparse_classes_30k_train_024651 | Implement the Python class `ConsensusSequence` described below.
Class description:
Stores information on a given consensus sequence, such as the sequence name, average kimura divergence, and the sequence itself. Fields: fname - Name of .fa file this consensus sequence is derived from. name - Name of the consensus sequ... | Implement the Python class `ConsensusSequence` described below.
Class description:
Stores information on a given consensus sequence, such as the sequence name, average kimura divergence, and the sequence itself. Fields: fname - Name of .fa file this consensus sequence is derived from. name - Name of the consensus sequ... | f149913b28544359b9140ee0a2776267fbc7ba1d | <|skeleton|>
class ConsensusSequence:
"""Stores information on a given consensus sequence, such as the sequence name, average kimura divergence, and the sequence itself. Fields: fname - Name of .fa file this consensus sequence is derived from. name - Name of the consensus sequence as given in original .fa file. seq... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsensusSequence:
"""Stores information on a given consensus sequence, such as the sequence name, average kimura divergence, and the sequence itself. Fields: fname - Name of .fa file this consensus sequence is derived from. name - Name of the consensus sequence as given in original .fa file. seq - Sequence o... | the_stack_v2_python_sparse | src/generate_alignments.py | yehric2018/dfam-pipeline | train | 0 |
db8b773aca99167c2b0c06142b324d3ac0c5385a | [
"super(ModuleUIFrame, self).__init__(parent)\nself.columnconfigure(0, weight=1)\nself.rowconfigure(0, weight=1)\napi_frame = ttk.LabelFrame(self, padding=8, text='Google API')\napi_frame.grid(row=0, column=0, sticky='W E N S')\napi_frame.columnconfigure(0, weight=1)\nself.reddit_api_user_agent = tk.StringVar()\nttk... | <|body_start_0|>
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
api_frame = ttk.LabelFrame(self, padding=8, text='Google API')
api_frame.grid(row=0, column=0, sticky='W E N S')
api_frame.columnconfigure(0, weig... | The UI for the gamedeals module | ModuleUIFrame | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
<|body_0|>
def update_google_key(self):
"""Updates the Google API key with the text value"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_066823 | 2,701 | permissive | [
{
"docstring": "Create a new UI for the module Args: parent: A tk or ttk object",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Updates the Google API key with the text value",
"name": "update_google_key",
"signature": "def update_google_key(self)"
}
... | 2 | stack_v2_sparse_classes_30k_train_004814 | Implement the Python class `ModuleUIFrame` described below.
Class description:
The UI for the gamedeals module
Method signatures and docstrings:
- def __init__(self, parent): Create a new UI for the module Args: parent: A tk or ttk object
- def update_google_key(self): Updates the Google API key with the text value | Implement the Python class `ModuleUIFrame` described below.
Class description:
The UI for the gamedeals module
Method signatures and docstrings:
- def __init__(self, parent): Create a new UI for the module Args: parent: A tk or ttk object
- def update_google_key(self): Updates the Google API key with the text value
... | 3e044b7152a04ebf15e95bd332f476724b40c652 | <|skeleton|>
class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
<|body_0|>
def update_google_key(self):
"""Updates the Google API key with the text value"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
api_f... | the_stack_v2_python_sparse | modis/discord_modis/modules/gamedeals/_ui.py | OKEPlazmA/modis | train | 0 |
e04f35e4a654a5741f9ebe8602631595a2226b59 | [
"token = kwargs['token']\nuser_id = token['user_id']\nuser = UserDetail.objects.filter(user_id=user_id)\nif not user:\n result = False\n data = ''\n error = '未查询到用户'\n return JsonResponse({'result': result, 'data': data, 'error': error})\nuser_se = StaffSerializer(user[0], many=False)\nresult = True\nda... | <|body_start_0|>
token = kwargs['token']
user_id = token['user_id']
user = UserDetail.objects.filter(user_id=user_id)
if not user:
result = False
data = ''
error = '未查询到用户'
return JsonResponse({'result': result, 'data': data, 'error': error... | desc: 个人信息管理模块 | StaffInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaffInfo:
"""desc: 个人信息管理模块"""
def get(self, request, **kwargs):
"""desc:个人账户查看 :param request: :return:"""
<|body_0|>
def put(self, request, **kwargs):
"""desc:修改密码 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
token = kwargs['token... | stack_v2_sparse_classes_75kplus_train_066824 | 8,165 | no_license | [
{
"docstring": "desc:个人账户查看 :param request: :return:",
"name": "get",
"signature": "def get(self, request, **kwargs)"
},
{
"docstring": "desc:修改密码 :return:",
"name": "put",
"signature": "def put(self, request, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031077 | Implement the Python class `StaffInfo` described below.
Class description:
desc: 个人信息管理模块
Method signatures and docstrings:
- def get(self, request, **kwargs): desc:个人账户查看 :param request: :return:
- def put(self, request, **kwargs): desc:修改密码 :return: | Implement the Python class `StaffInfo` described below.
Class description:
desc: 个人信息管理模块
Method signatures and docstrings:
- def get(self, request, **kwargs): desc:个人账户查看 :param request: :return:
- def put(self, request, **kwargs): desc:修改密码 :return:
<|skeleton|>
class StaffInfo:
"""desc: 个人信息管理模块"""
def g... | 22159c3f827f6defe96c4586fb8b4629c238b6c4 | <|skeleton|>
class StaffInfo:
"""desc: 个人信息管理模块"""
def get(self, request, **kwargs):
"""desc:个人账户查看 :param request: :return:"""
<|body_0|>
def put(self, request, **kwargs):
"""desc:修改密码 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StaffInfo:
"""desc: 个人信息管理模块"""
def get(self, request, **kwargs):
"""desc:个人账户查看 :param request: :return:"""
token = kwargs['token']
user_id = token['user_id']
user = UserDetail.objects.filter(user_id=user_id)
if not user:
result = False
dat... | the_stack_v2_python_sparse | staff/views.py | haominqu/excenter | train | 0 |
1f106f21f18cec95cbb6aa65dc21e827d6a28add | [
"alignment_paths = [primary_csv_path, unclassified_csv_path]\nheader_line = header_line\nwrite_header = [False, False]\nread_lines = [[], []]\nfor i in alignment_paths:\n try:\n open(i, 'r').close()\n except FileNotFoundError:\n open(i, 'w').close()\nfor i in range(len(alignment_paths)):\n wi... | <|body_start_0|>
alignment_paths = [primary_csv_path, unclassified_csv_path]
header_line = header_line
write_header = [False, False]
read_lines = [[], []]
for i in alignment_paths:
try:
open(i, 'r').close()
except FileNotFoundError:
... | GlobalGenomicFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalGenomicFunctions:
def write_header_row(primary_csv_path: str, unclassified_csv_path: str, header_line: str):
"""This class will be responsible for taking the input path and attempting to create a header row for the primary alignment and unclassified alignments If the files already ... | stack_v2_sparse_classes_75kplus_train_066825 | 19,347 | no_license | [
{
"docstring": "This class will be responsible for taking the input path and attempting to create a header row for the primary alignment and unclassified alignments If the files already exist, it will test if the first row is a header row. If this row is a header row, nothing will be done, otherwise it will cre... | 2 | stack_v2_sparse_classes_30k_train_005863 | Implement the Python class `GlobalGenomicFunctions` described below.
Class description:
Implement the GlobalGenomicFunctions class.
Method signatures and docstrings:
- def write_header_row(primary_csv_path: str, unclassified_csv_path: str, header_line: str): This class will be responsible for taking the input path an... | Implement the Python class `GlobalGenomicFunctions` described below.
Class description:
Implement the GlobalGenomicFunctions class.
Method signatures and docstrings:
- def write_header_row(primary_csv_path: str, unclassified_csv_path: str, header_line: str): This class will be responsible for taking the input path an... | 9ab650a460785adab085af523dec8ee8fa2105ba | <|skeleton|>
class GlobalGenomicFunctions:
def write_header_row(primary_csv_path: str, unclassified_csv_path: str, header_line: str):
"""This class will be responsible for taking the input path and attempting to create a header row for the primary alignment and unclassified alignments If the files already ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GlobalGenomicFunctions:
def write_header_row(primary_csv_path: str, unclassified_csv_path: str, header_line: str):
"""This class will be responsible for taking the input path and attempting to create a header row for the primary alignment and unclassified alignments If the files already exist, it will... | the_stack_v2_python_sparse | Scripts/GenomicData.py | JoshLoecker/ARS | train | 0 | |
077519f165031fa38c4adc959ca72e68e85bb265 | [
"self._root = root\nself._stdout = None\nself._stderr = None\nself._stringio_output = None\nself._stringio_error = None",
"self._stdout = sys.stdout\nself._stderr = sys.stderr\nsys.stdout = self._stringio_output = StringIO()\nsys.stderr = self._stringio_error = StringIO()\nreturn self",
"out = self._stringio_ou... | <|body_start_0|>
self._root = root
self._stdout = None
self._stderr = None
self._stringio_output = None
self._stringio_error = None
<|end_body_0|>
<|body_start_1|>
self._stdout = sys.stdout
self._stderr = sys.stderr
sys.stdout = self._stringio_output = St... | Context manager for capturing and formating stdout and stderr. | ShortOutput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShortOutput:
"""Context manager for capturing and formating stdout and stderr."""
def __init__(self, root):
"""Context manager for capturing and formating stdout and stderr. Parameter --------- root : str Path where ciocheck script was called (root directory)."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_066826 | 7,101 | permissive | [
{
"docstring": "Context manager for capturing and formating stdout and stderr. Parameter --------- root : str Path where ciocheck script was called (root directory).",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": "Capture stdout and stderr in a StringIO.",
"n... | 3 | stack_v2_sparse_classes_30k_train_012977 | Implement the Python class `ShortOutput` described below.
Class description:
Context manager for capturing and formating stdout and stderr.
Method signatures and docstrings:
- def __init__(self, root): Context manager for capturing and formating stdout and stderr. Parameter --------- root : str Path where ciocheck sc... | Implement the Python class `ShortOutput` described below.
Class description:
Context manager for capturing and formating stdout and stderr.
Method signatures and docstrings:
- def __init__(self, root): Context manager for capturing and formating stdout and stderr. Parameter --------- root : str Path where ciocheck sc... | 8d44f41d98b6540c5ad4b41b9bcc5e68386b31d1 | <|skeleton|>
class ShortOutput:
"""Context manager for capturing and formating stdout and stderr."""
def __init__(self, root):
"""Context manager for capturing and formating stdout and stderr. Parameter --------- root : str Path where ciocheck script was called (root directory)."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShortOutput:
"""Context manager for capturing and formating stdout and stderr."""
def __init__(self, root):
"""Context manager for capturing and formating stdout and stderr. Parameter --------- root : str Path where ciocheck script was called (root directory)."""
self._root = root
... | the_stack_v2_python_sparse | ciocheck/utils.py | EdwardBetts/ciocheck | train | 0 |
e8431fd0b06039553570c80634fa2f7ef239033e | [
"def proxy_func(*args, **kwargs):\n \"\"\"proxy_docstring\"\"\"\n pass\nproxy.clone_function_meta(public_func, proxy_func)\nself.assertEqual(public_func.__doc__, proxy_func.__doc__)",
"def proxy_func(*args, **kwargs):\n \"\"\"proxy_docstring\"\"\"\n pass\nproxy.clone_function_meta(public_func, proxy_f... | <|body_start_0|>
def proxy_func(*args, **kwargs):
"""proxy_docstring"""
pass
proxy.clone_function_meta(public_func, proxy_func)
self.assertEqual(public_func.__doc__, proxy_func.__doc__)
<|end_body_0|>
<|body_start_1|>
def proxy_func(*args, **kwargs):
... | TestExecutablePath | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExecutablePath:
def test_info(self):
"""Inherit informational attributes"""
<|body_0|>
def test_lookup(self):
"""Inherit lookup attributes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def proxy_func(*args, **kwargs):
"""proxy_docs... | stack_v2_sparse_classes_75kplus_train_066827 | 963 | permissive | [
{
"docstring": "Inherit informational attributes",
"name": "test_info",
"signature": "def test_info(self)"
},
{
"docstring": "Inherit lookup attributes",
"name": "test_lookup",
"signature": "def test_lookup(self)"
}
] | 2 | null | Implement the Python class `TestExecutablePath` described below.
Class description:
Implement the TestExecutablePath class.
Method signatures and docstrings:
- def test_info(self): Inherit informational attributes
- def test_lookup(self): Inherit lookup attributes | Implement the Python class `TestExecutablePath` described below.
Class description:
Implement the TestExecutablePath class.
Method signatures and docstrings:
- def test_info(self): Inherit informational attributes
- def test_lookup(self): Inherit lookup attributes
<|skeleton|>
class TestExecutablePath:
def test... | 5485cc612c868cbc02fdfbaf7be0483457b94101 | <|skeleton|>
class TestExecutablePath:
def test_info(self):
"""Inherit informational attributes"""
<|body_0|>
def test_lookup(self):
"""Inherit lookup attributes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestExecutablePath:
def test_info(self):
"""Inherit informational attributes"""
def proxy_func(*args, **kwargs):
"""proxy_docstring"""
pass
proxy.clone_function_meta(public_func, proxy_func)
self.assertEqual(public_func.__doc__, proxy_func.__doc__)
... | the_stack_v2_python_sparse | cpy2py_unittests/test_utility/test_proxy.py | maxfischer2781/cpy2py | train | 3 | |
1e9ebb1104b3dcf9ff4f3bd5067e1a4f0c58abd6 | [
"List = self.indexChar(S, C)\nresult = []\nfor i in range(len(S)):\n result.append(min((abs(i - k) for k in List)))\nreturn result",
"res = []\nif len(S) == 0 or C not in S:\n return -1\nfor i in range(len(S)):\n if S[i] == C:\n res.append(i)\nreturn res"
] | <|body_start_0|>
List = self.indexChar(S, C)
result = []
for i in range(len(S)):
result.append(min((abs(i - k) for k in List)))
return result
<|end_body_0|>
<|body_start_1|>
res = []
if len(S) == 0 or C not in S:
return -1
for i in range(l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_0|>
def indexChar(self, S, C):
"""找出S中C的所有下标索引"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
List = self.indexChar(S, C)
result = []
... | stack_v2_sparse_classes_75kplus_train_066828 | 653 | no_license | [
{
"docstring": ":type S: str :type C: str :rtype: List[int]",
"name": "shortestToChar",
"signature": "def shortestToChar(self, S, C)"
},
{
"docstring": "找出S中C的所有下标索引",
"name": "indexChar",
"signature": "def indexChar(self, S, C)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046152 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestToChar(self, S, C): :type S: str :type C: str :rtype: List[int]
- def indexChar(self, S, C): 找出S中C的所有下标索引 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestToChar(self, S, C): :type S: str :type C: str :rtype: List[int]
- def indexChar(self, S, C): 找出S中C的所有下标索引
<|skeleton|>
class Solution:
def shortestToChar(self, ... | 2df5d3b361bc7d25cd3d2afd5ac1c64fbc303920 | <|skeleton|>
class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_0|>
def indexChar(self, S, C):
"""找出S中C的所有下标索引"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
List = self.indexChar(S, C)
result = []
for i in range(len(S)):
result.append(min((abs(i - k) for k in List)))
return result
def indexChar(self, S, C):
"... | the_stack_v2_python_sparse | leetcode_821.py | SongJialiJiali/test | train | 0 | |
cac3ed1bdfb11ffb1e90e27ab15ceb71a7e99c8b | [
"Galkin.__init__(self, kwargs_model=kwargs_model, kwargs_aperture=kwargs_aperture, kwargs_psf=kwargs_psf, kwargs_cosmo=kwargs_cosmo, kwargs_numerics=kwargs_numerics, analytic_kinematics=analytic_kinematics)\nif not self.aperture_type == 'IFU_shells':\n raise ValueError('GalkinShells is not supported with apertur... | <|body_start_0|>
Galkin.__init__(self, kwargs_model=kwargs_model, kwargs_aperture=kwargs_aperture, kwargs_psf=kwargs_psf, kwargs_cosmo=kwargs_cosmo, kwargs_numerics=kwargs_numerics, analytic_kinematics=analytic_kinematics)
if not self.aperture_type == 'IFU_shells':
raise ValueError('GalkinSh... | class to calculate velocity dispersion for radial shells in a fast way | GalkinShells | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GalkinShells:
"""class to calculate velocity dispersion for radial shells in a fast way"""
def __init__(self, kwargs_model, kwargs_aperture, kwargs_psf, kwargs_cosmo, kwargs_numerics=None, analytic_kinematics=False):
""":param kwargs_model: keyword arguments describing the model comp... | stack_v2_sparse_classes_75kplus_train_066829 | 3,570 | permissive | [
{
"docstring": ":param kwargs_model: keyword arguments describing the model components :param kwargs_aperture: keyword arguments describing the spectroscopic aperture, see Aperture() class :param kwargs_psf: keyword argument specifying the PSF of the observation :param kwargs_cosmo: keyword arguments that defin... | 2 | stack_v2_sparse_classes_30k_train_041017 | Implement the Python class `GalkinShells` described below.
Class description:
class to calculate velocity dispersion for radial shells in a fast way
Method signatures and docstrings:
- def __init__(self, kwargs_model, kwargs_aperture, kwargs_psf, kwargs_cosmo, kwargs_numerics=None, analytic_kinematics=False): :param ... | Implement the Python class `GalkinShells` described below.
Class description:
class to calculate velocity dispersion for radial shells in a fast way
Method signatures and docstrings:
- def __init__(self, kwargs_model, kwargs_aperture, kwargs_psf, kwargs_cosmo, kwargs_numerics=None, analytic_kinematics=False): :param ... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class GalkinShells:
"""class to calculate velocity dispersion for radial shells in a fast way"""
def __init__(self, kwargs_model, kwargs_aperture, kwargs_psf, kwargs_cosmo, kwargs_numerics=None, analytic_kinematics=False):
""":param kwargs_model: keyword arguments describing the model comp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GalkinShells:
"""class to calculate velocity dispersion for radial shells in a fast way"""
def __init__(self, kwargs_model, kwargs_aperture, kwargs_psf, kwargs_cosmo, kwargs_numerics=None, analytic_kinematics=False):
""":param kwargs_model: keyword arguments describing the model components :param... | the_stack_v2_python_sparse | lenstronomy/GalKin/galkin_shells.py | lenstronomy/lenstronomy | train | 41 |
1b7f01bf65725529bad8f820d7fc8db15a52bae0 | [
"if isinstance(value, DirDescriptor):\n return value\nelif isinstance(value, str):\n return DirDescriptor(value)\nelif isinstance(value, dict):\n try:\n path = value['dir']\n except KeyError:\n raise ValidationError(\"dictionary must contain a 'dir' element\")\n if not isinstance(path, ... | <|body_start_0|>
if isinstance(value, DirDescriptor):
return value
elif isinstance(value, str):
return DirDescriptor(value)
elif isinstance(value, dict):
try:
path = value['dir']
except KeyError:
raise ValidationErro... | Directory field. | DirField | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirField:
"""Directory field."""
def to_python(self, value):
"""Convert value if needed."""
<|body_0|>
def to_output(self, value):
"""Convert value to process output format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if isinstance(value, Di... | stack_v2_sparse_classes_75kplus_train_066830 | 42,700 | permissive | [
{
"docstring": "Convert value if needed.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Convert value to process output format.",
"name": "to_output",
"signature": "def to_output(self, value)"
}
] | 2 | null | Implement the Python class `DirField` described below.
Class description:
Directory field.
Method signatures and docstrings:
- def to_python(self, value): Convert value if needed.
- def to_output(self, value): Convert value to process output format. | Implement the Python class `DirField` described below.
Class description:
Directory field.
Method signatures and docstrings:
- def to_python(self, value): Convert value if needed.
- def to_output(self, value): Convert value to process output format.
<|skeleton|>
class DirField:
"""Directory field."""
def to... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class DirField:
"""Directory field."""
def to_python(self, value):
"""Convert value if needed."""
<|body_0|>
def to_output(self, value):
"""Convert value to process output format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DirField:
"""Directory field."""
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, DirDescriptor):
return value
elif isinstance(value, str):
return DirDescriptor(value)
elif isinstance(value, dict):
try:
... | the_stack_v2_python_sparse | resolwe/process/fields.py | genialis/resolwe | train | 35 |
edb1fdf69cc56d077585116e38f053c168f82b0c | [
"super(DMCM, self).__init__()\nself.conv_net = cfg.get_image_net(mode)\nself.sparse_net = cfg.get_genes_net(mode)\nself.conv_net.apply(_init_weights_xavier)",
"x1, x2 = x\ny1 = self.conv_net.forward(x1)\ny2 = self.sparse_net.forward(x2)\nreturn (y1, y2)"
] | <|body_start_0|>
super(DMCM, self).__init__()
self.conv_net = cfg.get_image_net(mode)
self.sparse_net = cfg.get_genes_net(mode)
self.conv_net.apply(_init_weights_xavier)
<|end_body_0|>
<|body_start_1|>
x1, x2 = x
y1 = self.conv_net.forward(x1)
y2 = self.sparse_ne... | DMCM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DMCM:
def __init__(self, mode, cfg):
"""Initialize model for Deep Multimodal Correlation Maximization."""
<|body_0|>
def forward(self, x):
"""Perform forward pass of images and associated signal through model. Output embeddings y1, y2."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_066831 | 1,803 | no_license | [
{
"docstring": "Initialize model for Deep Multimodal Correlation Maximization.",
"name": "__init__",
"signature": "def __init__(self, mode, cfg)"
},
{
"docstring": "Perform forward pass of images and associated signal through model. Output embeddings y1, y2.",
"name": "forward",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_018331 | Implement the Python class `DMCM` described below.
Class description:
Implement the DMCM class.
Method signatures and docstrings:
- def __init__(self, mode, cfg): Initialize model for Deep Multimodal Correlation Maximization.
- def forward(self, x): Perform forward pass of images and associated signal through model. ... | Implement the Python class `DMCM` described below.
Class description:
Implement the DMCM class.
Method signatures and docstrings:
- def __init__(self, mode, cfg): Initialize model for Deep Multimodal Correlation Maximization.
- def forward(self, x): Perform forward pass of images and associated signal through model. ... | 1b65fc0c3ec6b182907ba070e859c1d92fc98942 | <|skeleton|>
class DMCM:
def __init__(self, mode, cfg):
"""Initialize model for Deep Multimodal Correlation Maximization."""
<|body_0|>
def forward(self, x):
"""Perform forward pass of images and associated signal through model. Output embeddings y1, y2."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DMCM:
def __init__(self, mode, cfg):
"""Initialize model for Deep Multimodal Correlation Maximization."""
super(DMCM, self).__init__()
self.conv_net = cfg.get_image_net(mode)
self.sparse_net = cfg.get_genes_net(mode)
self.conv_net.apply(_init_weights_xavier)
def fo... | the_stack_v2_python_sparse | models/dmcm.py | KaiqianZhang/dpcca_v8 | train | 1 | |
a552a58f10b432411abec7012eba9003a34930ad | [
"paddle.set_default_dtype(np.float64)\nsuper(Conv2DNet, self).__init__()\nself._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', weight_attr=paddle.nn.initializer.Constant(value=0.5), bias_attr=paddle.nn.initializer.Constant(val... | <|body_start_0|>
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
self._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', weight_attr=paddle.nn.initializer.Constant(value=0.5), bias_attr=... | model | Conv2DNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
sel... | stack_v2_sparse_classes_75kplus_train_066832 | 1,731 | no_license | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000510 | Implement the Python class `Conv2DNet` described below.
Class description:
model
Method signatures and docstrings:
- def __init__(self): __init__
- def forward(self, inputs): forward | Implement the Python class `Conv2DNet` described below.
Class description:
model
Method signatures and docstrings:
- def __init__(self): __init__
- def forward(self, inputs): forward
<|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
self._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', w... | the_stack_v2_python_sparse | framework/api/optimizer/conv2d_dygraph_model.py | PaddlePaddle/PaddleTest | train | 42 |
51e60e2dd68a54f172d40198d1b99fe5928c2ed3 | [
"self.message_handler = message_handler\nself.encryption_context = encryption_context\nself.system_session_key = system_session_key\nself.parent_process_monitor = parent_process_monitor\nself.cluster_monitor = cluster_monitor\nself.logger = logger\nself.max_reconnect_delay = max_reconnect_delay\nself.mode = mode\ns... | <|body_start_0|>
self.message_handler = message_handler
self.encryption_context = encryption_context
self.system_session_key = system_session_key
self.parent_process_monitor = parent_process_monitor
self.cluster_monitor = cluster_monitor
self.logger = logger
self.... | Abstract class used to initiate a connection to cloudgateway via websocket. This is abstract because there are different methods by which we may want to connect to Cloudgateway. | CloudgatewayConnector | [
"BSD-3-Clause",
"MIT-0",
"MIT",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-mit-taylor-variant",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudgatewayConnector:
"""Abstract class used to initiate a connection to cloudgateway via websocket. This is abstract because there are different methods by which we may want to connect to Cloudgateway."""
def __init__(self, message_handler, encryption_context, system_session_key, parent_pr... | stack_v2_sparse_classes_75kplus_train_066833 | 5,126 | permissive | [
{
"docstring": "Args: message_handler: IMessageHandler interface for delegating messages encryption_context: EncryptionContext object system_session_key: SplunkAuthHeader parent_process_monitor: ParentProcessMonitor logger: Logger object for logging purposes max_reconnect_delay: optional parameter to specify ho... | 3 | stack_v2_sparse_classes_30k_train_038456 | Implement the Python class `CloudgatewayConnector` described below.
Class description:
Abstract class used to initiate a connection to cloudgateway via websocket. This is abstract because there are different methods by which we may want to connect to Cloudgateway.
Method signatures and docstrings:
- def __init__(self... | Implement the Python class `CloudgatewayConnector` described below.
Class description:
Abstract class used to initiate a connection to cloudgateway via websocket. This is abstract because there are different methods by which we may want to connect to Cloudgateway.
Method signatures and docstrings:
- def __init__(self... | 0498d7db73772476192f96218c159070e2f3035a | <|skeleton|>
class CloudgatewayConnector:
"""Abstract class used to initiate a connection to cloudgateway via websocket. This is abstract because there are different methods by which we may want to connect to Cloudgateway."""
def __init__(self, message_handler, encryption_context, system_session_key, parent_pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudgatewayConnector:
"""Abstract class used to initiate a connection to cloudgateway via websocket. This is abstract because there are different methods by which we may want to connect to Cloudgateway."""
def __init__(self, message_handler, encryption_context, system_session_key, parent_process_monitor... | the_stack_v2_python_sparse | splunk_app_cloudgateway/lib/cloudgateway/private/websocket/cloudgateway_connector.py | DwarfCraft/splunk_app | train | 0 |
5cdae14e22c9d41c59f35b62d3d1c03f0e38d6cf | [
"x = pixel % w\ny = pixel // w\nlocation = [x, y]\nlocation.insert(channel_axis, slice(None))\nlocation = tuple(location)\nif np.random.randint(0, 2) == 1:\n value = min_\nelse:\n value = max_\nperturbed[location] = value",
"a = input_or_adv\ndel input_or_adv\ndel label\ndel unpack\nchannel_axis = a.channel... | <|body_start_0|>
x = pixel % w
y = pixel // w
location = [x, y]
location.insert(channel_axis, slice(None))
location = tuple(location)
if np.random.randint(0, 2) == 1:
value = min_
else:
value = max_
perturbed[location] = value
<|end... | Perturbs multiple pixels and sets them to the min or max. | MultiplePixelsAttack | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiplePixelsAttack:
"""Perturbs multiple pixels and sets them to the min or max."""
def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0):
"""Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param ... | stack_v2_sparse_classes_75kplus_train_066834 | 3,118 | permissive | [
{
"docstring": "Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param min_: the min value to be set :param max_: the max value to be set :param w: the width of the image :param channel_axis: :return:",
"name": "perturb_pixel",
"signature... | 2 | stack_v2_sparse_classes_30k_train_006051 | Implement the Python class `MultiplePixelsAttack` described below.
Class description:
Perturbs multiple pixels and sets them to the min or max.
Method signatures and docstrings:
- def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0): Perturb a :param perturbed: the image to be perturbed :param pix... | Implement the Python class `MultiplePixelsAttack` described below.
Class description:
Perturbs multiple pixels and sets them to the min or max.
Method signatures and docstrings:
- def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0): Perturb a :param perturbed: the image to be perturbed :param pix... | 81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a | <|skeleton|>
class MultiplePixelsAttack:
"""Perturbs multiple pixels and sets them to the min or max."""
def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0):
"""Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiplePixelsAttack:
"""Perturbs multiple pixels and sets them to the min or max."""
def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0):
"""Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param min_: the min... | the_stack_v2_python_sparse | cnns/nnlib/attacks/multiple_pixels.py | adam-dziedzic/bandlimited-cnns | train | 17 |
0abf71a4882ba097f85817a4cde1dac3921b166c | [
"if '\\\\' in self.network_path:\n return self.network_path.split('\\\\')[-1]\nelse:\n return self.network_path.split('/')[-1]",
"if self.username and 'user' not in extra_opts:\n extra_opts['user'] = self.username\nif self.password and 'password' not in extra_opts:\n extra_opts['password'] = self.pass... | <|body_start_0|>
if '\\' in self.network_path:
return self.network_path.split('\\')[-1]
else:
return self.network_path.split('/')[-1]
<|end_body_0|>
<|body_start_1|>
if self.username and 'user' not in extra_opts:
extra_opts['user'] = self.username
if ... | Class representing a Samba share mount. | SambaMount | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SambaMount:
"""Class representing a Samba share mount."""
def id(self):
"""Return mount ID."""
<|body_0|>
def mount(self, extra_opts={}):
"""Mount the Samba share."""
<|body_1|>
def umount(self):
"""Unmount the Samba share."""
<|body_... | stack_v2_sparse_classes_75kplus_train_066835 | 7,408 | no_license | [
{
"docstring": "Return mount ID.",
"name": "id",
"signature": "def id(self)"
},
{
"docstring": "Mount the Samba share.",
"name": "mount",
"signature": "def mount(self, extra_opts={})"
},
{
"docstring": "Unmount the Samba share.",
"name": "umount",
"signature": "def umount... | 3 | stack_v2_sparse_classes_30k_train_039400 | Implement the Python class `SambaMount` described below.
Class description:
Class representing a Samba share mount.
Method signatures and docstrings:
- def id(self): Return mount ID.
- def mount(self, extra_opts={}): Mount the Samba share.
- def umount(self): Unmount the Samba share. | Implement the Python class `SambaMount` described below.
Class description:
Class representing a Samba share mount.
Method signatures and docstrings:
- def id(self): Return mount ID.
- def mount(self, extra_opts={}): Mount the Samba share.
- def umount(self): Unmount the Samba share.
<|skeleton|>
class SambaMount:
... | 0f690816216c206fba5b224e87d2fed86ee008b2 | <|skeleton|>
class SambaMount:
"""Class representing a Samba share mount."""
def id(self):
"""Return mount ID."""
<|body_0|>
def mount(self, extra_opts={}):
"""Mount the Samba share."""
<|body_1|>
def umount(self):
"""Unmount the Samba share."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SambaMount:
"""Class representing a Samba share mount."""
def id(self):
"""Return mount ID."""
if '\\' in self.network_path:
return self.network_path.split('\\')[-1]
else:
return self.network_path.split('/')[-1]
def mount(self, extra_opts={}):
... | the_stack_v2_python_sparse | fs-samba/fileshare.py | minhnhut0602/applications | train | 0 |
9e040e28ac176be878db16d2e0d938b82238749b | [
"Timings.fast()\nself.app = Application()\nself.app.start(_notepad_exe())\nself.dlg = self.app.window(name='Untitled - Notepad', class_name='Notepad')\nself.ctrl = HwndWrapper(self.dlg.Edit.handle)\nself.dlg.Edit.set_edit_text('Here is some text\\r\\n and some more')\nself.app2 = Application().start(_notepad_exe())... | <|body_start_0|>
Timings.fast()
self.app = Application()
self.app.start(_notepad_exe())
self.dlg = self.app.window(name='Untitled - Notepad', class_name='Notepad')
self.ctrl = HwndWrapper(self.dlg.Edit.handle)
self.dlg.Edit.set_edit_text('Here is some text\r\n and some mo... | Regression unit tests for Notepad | NotepadRegressionTests | [
"BSD-3-Clause",
"LGPL-2.1-or-later",
"LGPL-2.1-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotepadRegressionTests:
"""Regression unit tests for Notepad"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
<|body_0|>
def tearDown(self):
"""Close the application after tests"""
<|body_1|>
def testMenuSele... | stack_v2_sparse_classes_75kplus_train_066836 | 39,360 | permissive | [
{
"docstring": "Set some data and ensure the application is in the state we want",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Close the application after tests",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "In notepad - MenuSele... | 3 | null | Implement the Python class `NotepadRegressionTests` described below.
Class description:
Regression unit tests for Notepad
Method signatures and docstrings:
- def setUp(self): Set some data and ensure the application is in the state we want
- def tearDown(self): Close the application after tests
- def testMenuSelectNo... | Implement the Python class `NotepadRegressionTests` described below.
Class description:
Regression unit tests for Notepad
Method signatures and docstrings:
- def setUp(self): Set some data and ensure the application is in the state we want
- def tearDown(self): Close the application after tests
- def testMenuSelectNo... | bf7f789d01b7c66ccd0c213db0a029da7e588c9e | <|skeleton|>
class NotepadRegressionTests:
"""Regression unit tests for Notepad"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
<|body_0|>
def tearDown(self):
"""Close the application after tests"""
<|body_1|>
def testMenuSele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotepadRegressionTests:
"""Regression unit tests for Notepad"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
self.app = Application()
self.app.start(_notepad_exe())
self.dlg = self.app.window(name='Untitled ... | the_stack_v2_python_sparse | pywinauto/unittests/test_hwndwrapper.py | pywinauto/pywinauto | train | 4,466 |
16b0e56c341f313e3a8d0af1080904d39e4ca5fa | [
"\"\"\"\n 暴力求解(超时)\n \"\"\"\nres = []\nfor i in range(len(words)):\n for j in range(i + 1, len(words)):\n temp1, temp2 = (words[i] + words[j], words[j] + words[i])\n if temp1 == temp1[::-1]:\n res.append([i, j])\n if temp2 == temp2[::-1]:\n res.append([j, ... | <|body_start_0|>
"""
暴力求解(超时)
"""
res = []
for i in range(len(words)):
for j in range(i + 1, len(words)):
temp1, temp2 = (words[i] + words[j], words[j] + words[i])
if temp1 == temp1[::-1]:
res.append(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def palindromePairs1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairs(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
... | stack_v2_sparse_classes_75kplus_train_066837 | 10,105 | no_license | [
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairs1",
"signature": "def palindromePairs1(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairs",
"signature": "def palindromePairs(self, words)"
}... | 2 | stack_v2_sparse_classes_30k_train_000011 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairs1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairs(self, words): :type words: List[str] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairs1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairs(self, words): :type words: List[str] :rtype: List[List[int]]
<|skeleton|>... | e8eae749e77be21716ada6019db4c39d3f00989c | <|skeleton|>
class Solution:
def palindromePairs1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairs(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def palindromePairs1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
"""
暴力求解(超时)
"""
res = []
for i in range(len(words)):
for j in range(i + 1, len(words)):
temp1, temp2 = (words[i] + word... | the_stack_v2_python_sparse | hash table/336. Palindrome Pairs.py | zazaliu/leetcode-python | train | 1 | |
a2027fc35fac278eedc0d6b16539ecf32c5ecaa2 | [
"super(NAM, self).__init__()\nself._num_inputs = num_inputs\nif isinstance(num_units, list):\n assert len(num_units) == num_inputs\n self._num_units = num_units\nelif isinstance(num_units, int):\n self._num_units = [num_units for _ in range(self._num_inputs)]\nself._trainable = trainable\nself._shallow = s... | <|body_start_0|>
super(NAM, self).__init__()
self._num_inputs = num_inputs
if isinstance(num_units, list):
assert len(num_units) == num_inputs
self._num_units = num_units
elif isinstance(num_units, int):
self._num_units = [num_units for _ in range(self... | Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature. | NAM | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NAM:
"""Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature."""
def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs):
"""Initializes NAM hyperparameters. Args: num_inputs: Number of fe... | stack_v2_sparse_classes_75kplus_train_066838 | 10,796 | permissive | [
{
"docstring": "Initializes NAM hyperparameters. Args: num_inputs: Number of feature inputs in input data. num_units: Number of hidden units in first layer of each feature net. trainable: Whether the NAM parameters are trainable or not. shallow: If True, then shallow feature nets with a single hidden layer are ... | 5 | stack_v2_sparse_classes_30k_val_000686 | Implement the Python class `NAM` described below.
Class description:
Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature.
Method signatures and docstrings:
- def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs): Initia... | Implement the Python class `NAM` described below.
Class description:
Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature.
Method signatures and docstrings:
- def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs): Initia... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class NAM:
"""Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature."""
def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs):
"""Initializes NAM hyperparameters. Args: num_inputs: Number of fe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NAM:
"""Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature."""
def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs):
"""Initializes NAM hyperparameters. Args: num_inputs: Number of feature inputs ... | the_stack_v2_python_sparse | neural_additive_models/models.py | Ayoob7/google-research | train | 2 |
7465753fae16b56ab035b684148b8ea3ac5a56e8 | [
"from __builtin__ import xrange\ns1_len, s2_len = (len(s1), len(s2))\nif s1_len > s2_len:\n return False\na1 = [ord(c) - ord('a') for c in s1]\na2 = [ord(c) - ord('a') for c in s2]\ntarget, window = ([0] * 26, [0] * 26)\nfor c in a1:\n target[c] += 1\nfor idx in xrange(s1_len):\n window[a2[idx]] += 1\nfor ... | <|body_start_0|>
from __builtin__ import xrange
s1_len, s2_len = (len(s1), len(s2))
if s1_len > s2_len:
return False
a1 = [ord(c) - ord('a') for c in s1]
a2 = [ord(c) - ord('a') for c in s2]
target, window = ([0] * 26, [0] * 26)
for c in a1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_0|>
def rewrite(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from __builtin__ import xran... | stack_v2_sparse_classes_75kplus_train_066839 | 2,732 | no_license | [
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "checkInclusion",
"signature": "def checkInclusion(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "rewrite",
"signature": "def rewrite(self, s1, s2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022492 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool
- def rewrite(self, s1, s2): :type s1: str :type s2: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool
- def rewrite(self, s1, s2): :type s1: str :type s2: str :rtype: bool
<|skeleton|>
class Solution:
... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_0|>
def rewrite(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
from __builtin__ import xrange
s1_len, s2_len = (len(s1), len(s2))
if s1_len > s2_len:
return False
a1 = [ord(c) - ord('a') for c in s1]
a2 = [ord(c) - ord('a'... | the_stack_v2_python_sparse | co_fb/567_Permutation_in_String.py | vsdrun/lc_public | train | 6 | |
f976c2242466f0bb05e759080fbbf959bb7ef18e | [
"separate = [x.partition('T') for x in list]\nstrings = [x[0] for x in separate]\nclear = [i for i in strings if i != '--']\nintegers = [int(x) for x in clear]\nlngs = sorted(integers)\nif len(lngs) == 0:\n pass\nelse:\n return lngs[-1]",
"ints = DataTypes.integers(list)\nsorted_list = []\nfor i in ints:\n ... | <|body_start_0|>
separate = [x.partition('T') for x in list]
strings = [x[0] for x in separate]
clear = [i for i in strings if i != '--']
integers = [int(x) for x in clear]
lngs = sorted(integers)
if len(lngs) == 0:
pass
else:
return lngs[-... | Most of these functions are for the "Season Leaders" and "Season Stats" pages. | StatOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatOrder:
"""Most of these functions are for the "Season Leaders" and "Season Stats" pages."""
def lng(cls, list):
"""Returns the greatest value from a list of strings of lng data"""
<|body_0|>
def greatest_least(cls, list):
"""Parameter has to be list of string... | stack_v2_sparse_classes_75kplus_train_066840 | 48,979 | no_license | [
{
"docstring": "Returns the greatest value from a list of strings of lng data",
"name": "lng",
"signature": "def lng(cls, list)"
},
{
"docstring": "Parameter has to be list of strings that are integers",
"name": "greatest_least",
"signature": "def greatest_least(cls, list)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_047652 | Implement the Python class `StatOrder` described below.
Class description:
Most of these functions are for the "Season Leaders" and "Season Stats" pages.
Method signatures and docstrings:
- def lng(cls, list): Returns the greatest value from a list of strings of lng data
- def greatest_least(cls, list): Parameter has... | Implement the Python class `StatOrder` described below.
Class description:
Most of these functions are for the "Season Leaders" and "Season Stats" pages.
Method signatures and docstrings:
- def lng(cls, list): Returns the greatest value from a list of strings of lng data
- def greatest_least(cls, list): Parameter has... | 8004577bd11d60534d6106fb1893209431a70697 | <|skeleton|>
class StatOrder:
"""Most of these functions are for the "Season Leaders" and "Season Stats" pages."""
def lng(cls, list):
"""Returns the greatest value from a list of strings of lng data"""
<|body_0|>
def greatest_least(cls, list):
"""Parameter has to be list of string... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatOrder:
"""Most of these functions are for the "Season Leaders" and "Season Stats" pages."""
def lng(cls, list):
"""Returns the greatest value from a list of strings of lng data"""
separate = [x.partition('T') for x in list]
strings = [x[0] for x in separate]
clear = [i... | the_stack_v2_python_sparse | main/data_functions.py | ytrevor81/NFL-Stats-Library | train | 1 |
9d17cc3bafec477922414c1a137c623dd57c6d9d | [
"msg = MIMEMultipart('alternative')\nmsg['Subject'] = message['subject']\nmsg['From'] = message['sender']\nmsg['To'] = ', '.join(message['receivers'])\nmsg.attach(MIMEText(message['body'], 'html'))\ns = aiosmtplib.SMTP(hostname=EMAIL_HOST, port=EMAIL_PORT, loop=loop)\ntry:\n await s.connect()\n await s.login(... | <|body_start_0|>
msg = MIMEMultipart('alternative')
msg['Subject'] = message['subject']
msg['From'] = message['sender']
msg['To'] = ', '.join(message['receivers'])
msg.attach(MIMEText(message['body'], 'html'))
s = aiosmtplib.SMTP(hostname=EMAIL_HOST, port=EMAIL_PORT, loop... | Отправка электронной почты Отправка вложений пока не поддерживается | Email | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Email:
"""Отправка электронной почты Отправка вложений пока не поддерживается"""
async def send_html_email(message):
"""Отправка писем в формате HTML"""
<|body_0|>
async def send(self, message_body):
"""Отправка письма :param message_body: строка с json-описанием... | stack_v2_sparse_classes_75kplus_train_066841 | 3,463 | no_license | [
{
"docstring": "Отправка писем в формате HTML",
"name": "send_html_email",
"signature": "async def send_html_email(message)"
},
{
"docstring": "Отправка письма :param message_body: строка с json-описанием сообщения",
"name": "send",
"signature": "async def send(self, message_body)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039135 | Implement the Python class `Email` described below.
Class description:
Отправка электронной почты Отправка вложений пока не поддерживается
Method signatures and docstrings:
- async def send_html_email(message): Отправка писем в формате HTML
- async def send(self, message_body): Отправка письма :param message_body: ст... | Implement the Python class `Email` described below.
Class description:
Отправка электронной почты Отправка вложений пока не поддерживается
Method signatures and docstrings:
- async def send_html_email(message): Отправка писем в формате HTML
- async def send(self, message_body): Отправка письма :param message_body: ст... | 8c0e8fa16588fc384979b9514d3d716713c6ea83 | <|skeleton|>
class Email:
"""Отправка электронной почты Отправка вложений пока не поддерживается"""
async def send_html_email(message):
"""Отправка писем в формате HTML"""
<|body_0|>
async def send(self, message_body):
"""Отправка письма :param message_body: строка с json-описанием... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Email:
"""Отправка электронной почты Отправка вложений пока не поддерживается"""
async def send_html_email(message):
"""Отправка писем в формате HTML"""
msg = MIMEMultipart('alternative')
msg['Subject'] = message['subject']
msg['From'] = message['sender']
msg['To']... | the_stack_v2_python_sparse | bus/handlers/email/email_handler.py | skushnerchuk/kip | train | 0 |
e9b6bae68c9648b443b4f337b69b2f51ccb2ba18 | [
"df_out = pd.DataFrame()\nfor col in df.columns:\n df_small = df[col].value_counts().to_frame(col)\n df_out = df_out.combine_first(df_small)\n if df_out.shape[0] > mx:\n raise Exception(f\"Error the DataFrame is getting to large it has an index size:{df_out.shape[0]}, which is above max:{mx}, ... | <|body_start_0|>
df_out = pd.DataFrame()
for col in df.columns:
df_small = df[col].value_counts().to_frame(col)
df_out = df_out.combine_first(df_small)
if df_out.shape[0] > mx:
raise Exception(f"Error the DataFrame is getting to large it has an index s... | PandasFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PandasFunctions:
def DataFrameValueCounts(df, mx=200):
"""Create a dataframe of all the value counts of each of the columns this only works with categocial data"""
<|body_0|>
def CompressDataFrame(df, axis=[0, 1]):
"""If columns or a Index only contains 0s its remove... | stack_v2_sparse_classes_75kplus_train_066842 | 30,409 | no_license | [
{
"docstring": "Create a dataframe of all the value counts of each of the columns this only works with categocial data",
"name": "DataFrameValueCounts",
"signature": "def DataFrameValueCounts(df, mx=200)"
},
{
"docstring": "If columns or a Index only contains 0s its removed",
"name": "Compre... | 3 | null | Implement the Python class `PandasFunctions` described below.
Class description:
Implement the PandasFunctions class.
Method signatures and docstrings:
- def DataFrameValueCounts(df, mx=200): Create a dataframe of all the value counts of each of the columns this only works with categocial data
- def CompressDataFrame... | Implement the Python class `PandasFunctions` described below.
Class description:
Implement the PandasFunctions class.
Method signatures and docstrings:
- def DataFrameValueCounts(df, mx=200): Create a dataframe of all the value counts of each of the columns this only works with categocial data
- def CompressDataFrame... | d53753e01a3a5c0461883af03d7d3ea89c13d204 | <|skeleton|>
class PandasFunctions:
def DataFrameValueCounts(df, mx=200):
"""Create a dataframe of all the value counts of each of the columns this only works with categocial data"""
<|body_0|>
def CompressDataFrame(df, axis=[0, 1]):
"""If columns or a Index only contains 0s its remove... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PandasFunctions:
def DataFrameValueCounts(df, mx=200):
"""Create a dataframe of all the value counts of each of the columns this only works with categocial data"""
df_out = pd.DataFrame()
for col in df.columns:
df_small = df[col].value_counts().to_frame(col)
df_... | the_stack_v2_python_sparse | _InDevelopment_org/CensusImputationAlexCode2.py | alexthefatcat/CuratedCode-GIT | train | 0 | |
e14880c3a178e5b28f3d6a0156d00de956bf66e4 | [
"data = parse(filename)\ndata = np.array(data)\n\ndef get_cost(a, i):\n return np.absolute(a - i)\nmedian = np.median(data)\nj, k = (math.floor(median), math.ceil(median))\nreturn min((sum(get_cost(data, i)) for i in [j, k]))",
"data = np.array(parse(filename))\n\ndef get_cost(a, i):\n b = np.absolute(a - i... | <|body_start_0|>
data = parse(filename)
data = np.array(data)
def get_cost(a, i):
return np.absolute(a - i)
median = np.median(data)
j, k = (math.floor(median), math.ceil(median))
return min((sum(get_cost(data, i)) for i in [j, k]))
<|end_body_0|>
<|body_sta... | AoC 2021 Day 07 | Day07 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Day07:
"""AoC 2021 Day 07"""
def part1(filename: str):
"""Given a filename, solve 2021 day 07 part 1"""
<|body_0|>
def part2(filename: str):
"""Given a filename, solve 2021 day 07 part 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = par... | stack_v2_sparse_classes_75kplus_train_066843 | 1,204 | no_license | [
{
"docstring": "Given a filename, solve 2021 day 07 part 1",
"name": "part1",
"signature": "def part1(filename: str)"
},
{
"docstring": "Given a filename, solve 2021 day 07 part 2",
"name": "part2",
"signature": "def part2(filename: str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016346 | Implement the Python class `Day07` described below.
Class description:
AoC 2021 Day 07
Method signatures and docstrings:
- def part1(filename: str): Given a filename, solve 2021 day 07 part 1
- def part2(filename: str): Given a filename, solve 2021 day 07 part 2 | Implement the Python class `Day07` described below.
Class description:
AoC 2021 Day 07
Method signatures and docstrings:
- def part1(filename: str): Given a filename, solve 2021 day 07 part 1
- def part2(filename: str): Given a filename, solve 2021 day 07 part 2
<|skeleton|>
class Day07:
"""AoC 2021 Day 07"""
... | e89db235837d2d05848210a18c9c2a4456085570 | <|skeleton|>
class Day07:
"""AoC 2021 Day 07"""
def part1(filename: str):
"""Given a filename, solve 2021 day 07 part 1"""
<|body_0|>
def part2(filename: str):
"""Given a filename, solve 2021 day 07 part 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Day07:
"""AoC 2021 Day 07"""
def part1(filename: str):
"""Given a filename, solve 2021 day 07 part 1"""
data = parse(filename)
data = np.array(data)
def get_cost(a, i):
return np.absolute(a - i)
median = np.median(data)
j, k = (math.floor(media... | the_stack_v2_python_sparse | 2021/python2021/aoc/day07.py | mreishus/aoc | train | 16 |
3ab1113c546bc7a99aea7b355fbc03f64f397463 | [
"self.type = typ\nself.rootobj = rootobject\nself.islead = islead\nself.obj = None\nif self.type == 'excel':\n self._findexcel(field)\nelse:\n self._findword(field)",
"found = False\nfor sheet in self.rootobj:\n r = sheet.min_row\n for c in range(sheet.min_column, sheet.max_column + 1):\n if st... | <|body_start_0|>
self.type = typ
self.rootobj = rootobject
self.islead = islead
self.obj = None
if self.type == 'excel':
self._findexcel(field)
else:
self._findword(field)
<|end_body_0|>
<|body_start_1|>
found = False
for sheet in ... | Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (Workbook) self.islead - чи є поле прові... | SourceItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (W... | stack_v2_sparse_classes_75kplus_train_066844 | 5,367 | no_license | [
{
"docstring": "Конструктор. Здійснює під'єднання до джерела даних. rootobject - об'єкт, де розташовано відповідні дані: документ (Document) або робоча книга (Workbook), в залежності від типу. islead - чи є параметр провідним.",
"name": "__init__",
"signature": "def __init__(self, field, typ, rootobject... | 4 | stack_v2_sparse_classes_30k_train_011090 | Implement the Python class `SourceItem` described below.
Class description:
Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт ... | Implement the Python class `SourceItem` described below.
Class description:
Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт ... | e44bf2b535b34bc31fb323c20901a77b0b3072f2 | <|skeleton|>
class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (W... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (Workbook) self... | the_stack_v2_python_sparse | dz_others/subject23_MS/merge/t23_22_sourceitem.py | davendiy/ads_course2 | train | 0 |
77a05df04ddd22f5c609b32ceda10e6d7b02046a | [
"user = User.objects.create(username='testuser', password='qwerty12345Q!')\nrecruiter = User.objects.create(username='recruiter4', first_name='first4_recruiter', last_name='last_recruiter', email='recruiter4@mail.com')\ncandidate = User.objects.create(username='candidate4', first_name='first_candidate', last_name='... | <|body_start_0|>
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter4', first_name='first4_recruiter', last_name='last_recruiter', email='recruiter4@mail.com')
candidate = User.objects.create(username='candidate4', first_n... | Test GET request Comments app | CommentsGetTestCases | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentsGetTestCases:
"""Test GET request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_get_valid_comments(self):
"""Test for GET Comments with id"""
<|body_1|>
def test_get_invalid_comments(self):
... | stack_v2_sparse_classes_75kplus_train_066845 | 13,494 | no_license | [
{
"docstring": "Create new data in in linked tables",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test for GET Comments with id",
"name": "test_get_valid_comments",
"signature": "def test_get_valid_comments(self)"
},
{
"docstring": "Test for GET not existin... | 3 | stack_v2_sparse_classes_30k_train_004588 | Implement the Python class `CommentsGetTestCases` described below.
Class description:
Test GET request Comments app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_get_valid_comments(self): Test for GET Comments with id
- def test_get_invalid_comments(self): Test fo... | Implement the Python class `CommentsGetTestCases` described below.
Class description:
Test GET request Comments app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_get_valid_comments(self): Test for GET Comments with id
- def test_get_invalid_comments(self): Test fo... | f448ec0453818d55c5c9d30aaa4f19e1d7ca5867 | <|skeleton|>
class CommentsGetTestCases:
"""Test GET request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_get_valid_comments(self):
"""Test for GET Comments with id"""
<|body_1|>
def test_get_invalid_comments(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentsGetTestCases:
"""Test GET request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter4', first_name='first4_recruiter', last... | the_stack_v2_python_sparse | Portfolio/tech-interview/techinterview/feedback/test_feedback.py | HeCToR74/Python | train | 1 |
9abbb516d5fa52ead1845cfc888b466131d9d205 | [
"super(Embedding_LS, self).__init__()\nself.num_classes = num_classes\nself.label_smoothing_prob = label_smoothing_prob\nself.embed = LinearND(num_classes, embedding_dim, bias=False, dropout=dropout)",
"y = _to_onehot(y, self.num_classes, self.label_smoothing_prob)\ny = self.embed(y)\nreturn y"
] | <|body_start_0|>
super(Embedding_LS, self).__init__()
self.num_classes = num_classes
self.label_smoothing_prob = label_smoothing_prob
self.embed = LinearND(num_classes, embedding_dim, bias=False, dropout=dropout)
<|end_body_0|>
<|body_start_1|>
y = _to_onehot(y, self.num_classes... | Embedding_LS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding_LS:
def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0):
"""Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embeddin... | stack_v2_sparse_classes_75kplus_train_066846 | 4,283 | no_license | [
{
"docstring": "Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (float, optional): the probability to drop nodes of the embedding label_smoothing_p... | 2 | stack_v2_sparse_classes_30k_train_033654 | Implement the Python class `Embedding_LS` described below.
Class description:
Implement the Embedding_LS class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0): Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in... | Implement the Python class `Embedding_LS` described below.
Class description:
Implement the Embedding_LS class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0): Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in... | b6b60a338d65bb369d0034f423feb09db10db8b7 | <|skeleton|>
class Embedding_LS:
def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0):
"""Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embeddin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Embedding_LS:
def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0):
"""Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target sp... | the_stack_v2_python_sparse | models/pytorch/linear.py | carolinebear/pytorch_end2end_speech_recognition | train | 0 | |
d3fee48e688ddd08b2c91e0411420b5366d52b9d | [
"parser = parent.add_parser('import', help='import tarball as image filesystem')\nparser.add_argument('--change', '-c', action=ChangeAction)\nparser.add_argument('--message', '-m', help='Set commit message for imported image.')\nparser.add_argument('source', metavar='PATH', nargs=1, help='tarball to use as source o... | <|body_start_0|>
parser = parent.add_parser('import', help='import tarball as image filesystem')
parser.add_argument('--change', '-c', action=ChangeAction)
parser.add_argument('--message', '-m', help='Set commit message for imported image.')
parser.add_argument('source', metavar='PATH', ... | Class for importing tarball as image filesystem. | Import | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Import:
"""Class for importing tarball as image filesystem."""
def subparser(cls, parent):
"""Add Import command to parent parser."""
<|body_0|>
def import_(self):
"""Import tarball as image filesystem."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_066847 | 2,082 | permissive | [
{
"docstring": "Add Import command to parent parser.",
"name": "subparser",
"signature": "def subparser(cls, parent)"
},
{
"docstring": "Import tarball as image filesystem.",
"name": "import_",
"signature": "def import_(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011510 | Implement the Python class `Import` described below.
Class description:
Class for importing tarball as image filesystem.
Method signatures and docstrings:
- def subparser(cls, parent): Add Import command to parent parser.
- def import_(self): Import tarball as image filesystem. | Implement the Python class `Import` described below.
Class description:
Class for importing tarball as image filesystem.
Method signatures and docstrings:
- def subparser(cls, parent): Add Import command to parent parser.
- def import_(self): Import tarball as image filesystem.
<|skeleton|>
class Import:
"""Clas... | 94a46127cb0db2b6187186788a941ec72af476dd | <|skeleton|>
class Import:
"""Class for importing tarball as image filesystem."""
def subparser(cls, parent):
"""Add Import command to parent parser."""
<|body_0|>
def import_(self):
"""Import tarball as image filesystem."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Import:
"""Class for importing tarball as image filesystem."""
def subparser(cls, parent):
"""Add Import command to parent parser."""
parser = parent.add_parser('import', help='import tarball as image filesystem')
parser.add_argument('--change', '-c', action=ChangeAction)
... | the_stack_v2_python_sparse | pypodman/pypodman/lib/actions/import_action.py | 4383/python-podman | train | 0 |
64c62c4beaa9f8f5643b9d8d8f3578ed24a1741e | [
"logout_button_sitem = self.locator_finder_by_id(self.logout_button_id)\nlogout_button_sitem.click()\nprint('Logout from the current user\\n')\nself.wait_for_ajax()",
"elem = self.locator_finder_by_xpath('/html/body/div[2]/div/div[1]/div/ul[1]/li[2]/a[2]')\nself.progress('Health state:' + elem.text)\nreturn elem.... | <|body_start_0|>
logout_button_sitem = self.locator_finder_by_id(self.logout_button_id)
logout_button_sitem.click()
print('Logout from the current user\n')
self.wait_for_ajax()
<|end_body_0|>
<|body_start_1|>
elem = self.locator_finder_by_xpath('/html/body/div[2]/div/div[1]/div/... | Page object representing the user bar | UserBarPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBarPage:
"""Page object representing the user bar"""
def log_out(self):
"""click log out icon on the user bar and wait for"""
<|body_0|>
def get_health_state(self):
"""extract the health state in the upper right corner"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_066848 | 861 | no_license | [
{
"docstring": "click log out icon on the user bar and wait for",
"name": "log_out",
"signature": "def log_out(self)"
},
{
"docstring": "extract the health state in the upper right corner",
"name": "get_health_state",
"signature": "def get_health_state(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021130 | Implement the Python class `UserBarPage` described below.
Class description:
Page object representing the user bar
Method signatures and docstrings:
- def log_out(self): click log out icon on the user bar and wait for
- def get_health_state(self): extract the health state in the upper right corner | Implement the Python class `UserBarPage` described below.
Class description:
Page object representing the user bar
Method signatures and docstrings:
- def log_out(self): click log out icon on the user bar and wait for
- def get_health_state(self): extract the health state in the upper right corner
<|skeleton|>
class... | 4d4a0b049eb83625df41d86f2066ddb0c6c9c85b | <|skeleton|>
class UserBarPage:
"""Page object representing the user bar"""
def log_out(self):
"""click log out icon on the user bar and wait for"""
<|body_0|>
def get_health_state(self):
"""extract the health state in the upper right corner"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserBarPage:
"""Page object representing the user bar"""
def log_out(self):
"""click log out icon on the user bar and wait for"""
logout_button_sitem = self.locator_finder_by_id(self.logout_button_id)
logout_button_sitem.click()
print('Logout from the current user\n')
... | the_stack_v2_python_sparse | release_tester/selenium_ui_test/pages/user_bar_page.py | arangodb/release-test-automation | train | 14 |
579e1bb0d113e8b2d8c43733ffb31265c73a2740 | [
"group_by_handler = {EnumData.BY_TECHNICAL_TITLE: cls.group_users_by_technical_title, EnumData.BY_HIGHEST_DEGREE: cls.group_users_by_education_background, EnumData.BY_AGE_DISTRIBUTION: cls.group_users_by_age, EnumData.BY_DEPARTMENT: cls.group_users_by_department}\nif group_by not in group_by_handler:\n raise Bad... | <|body_start_0|>
group_by_handler = {EnumData.BY_TECHNICAL_TITLE: cls.group_users_by_technical_title, EnumData.BY_HIGHEST_DEGREE: cls.group_users_by_education_background, EnumData.BY_AGE_DISTRIBUTION: cls.group_users_by_age, EnumData.BY_DEPARTMENT: cls.group_users_by_department}
if group_by not in group... | get teachers statistics data | TeachersStatisticsService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeachersStatisticsService:
"""get teachers statistics data"""
def teachers_statistics_group_dispatch(cls, users, group_by, count_only):
"""dispatch group_by function by group_by Parameters: ---------- users: QuerySet group_by: int count_only: boolean"""
<|body_0|>
def gr... | stack_v2_sparse_classes_75kplus_train_066849 | 6,553 | no_license | [
{
"docstring": "dispatch group_by function by group_by Parameters: ---------- users: QuerySet group_by: int count_only: boolean",
"name": "teachers_statistics_group_dispatch",
"signature": "def teachers_statistics_group_dispatch(cls, users, group_by, count_only)"
},
{
"docstring": "Return ------... | 6 | stack_v2_sparse_classes_30k_train_027030 | Implement the Python class `TeachersStatisticsService` described below.
Class description:
get teachers statistics data
Method signatures and docstrings:
- def teachers_statistics_group_dispatch(cls, users, group_by, count_only): dispatch group_by function by group_by Parameters: ---------- users: QuerySet group_by: ... | Implement the Python class `TeachersStatisticsService` described below.
Class description:
get teachers statistics data
Method signatures and docstrings:
- def teachers_statistics_group_dispatch(cls, users, group_by, count_only): dispatch group_by function by group_by Parameters: ---------- users: QuerySet group_by: ... | 48cccddbe8347167cb6120a1cd7d61f9fc57cc7c | <|skeleton|>
class TeachersStatisticsService:
"""get teachers statistics data"""
def teachers_statistics_group_dispatch(cls, users, group_by, count_only):
"""dispatch group_by function by group_by Parameters: ---------- users: QuerySet group_by: int count_only: boolean"""
<|body_0|>
def gr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeachersStatisticsService:
"""get teachers statistics data"""
def teachers_statistics_group_dispatch(cls, users, group_by, count_only):
"""dispatch group_by function by group_by Parameters: ---------- users: QuerySet group_by: int count_only: boolean"""
group_by_handler = {EnumData.BY_TEC... | the_stack_v2_python_sparse | data_warehouse/services/teachers_statistics_service.py | DLUT-SIE/TMSFTT-BE | train | 1 |
fca93300090d0b0a45cc39453432f3aa6b058da1 | [
"threading.Thread.__init__(self)\nself.daemon = False\nself.hass = hass\nself.mac = mac\nself.name = name\nself.data = {'temp': STATE_UNKNOWN, 'humid': STATE_UNKNOWN}\nself.keep_going = True\nself.event = threading.Event()",
"cached_char = Characteristic(BLE_TEMP_UUID, BLE_TEMP_HANDLE)\nadapter = GATTToolBackend(... | <|body_start_0|>
threading.Thread.__init__(self)
self.daemon = False
self.hass = hass
self.mac = mac
self.name = name
self.data = {'temp': STATE_UNKNOWN, 'humid': STATE_UNKNOWN}
self.keep_going = True
self.event = threading.Event()
<|end_body_0|>
<|body_s... | Connection handling. | Monitor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monitor:
"""Connection handling."""
def __init__(self, hass, mac, name):
"""Construct interface object."""
<|body_0|>
def run(self):
"""Thread that keeps connection alive."""
<|body_1|>
def _update(self, handle, value):
"""Notification callba... | stack_v2_sparse_classes_75kplus_train_066850 | 5,965 | permissive | [
{
"docstring": "Construct interface object.",
"name": "__init__",
"signature": "def __init__(self, hass, mac, name)"
},
{
"docstring": "Thread that keeps connection alive.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Notification callback from pygatt.",
"n... | 4 | stack_v2_sparse_classes_30k_train_016884 | Implement the Python class `Monitor` described below.
Class description:
Connection handling.
Method signatures and docstrings:
- def __init__(self, hass, mac, name): Construct interface object.
- def run(self): Thread that keeps connection alive.
- def _update(self, handle, value): Notification callback from pygatt.... | Implement the Python class `Monitor` described below.
Class description:
Connection handling.
Method signatures and docstrings:
- def __init__(self, hass, mac, name): Construct interface object.
- def run(self): Thread that keeps connection alive.
- def _update(self, handle, value): Notification callback from pygatt.... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class Monitor:
"""Connection handling."""
def __init__(self, hass, mac, name):
"""Construct interface object."""
<|body_0|>
def run(self):
"""Thread that keeps connection alive."""
<|body_1|>
def _update(self, handle, value):
"""Notification callba... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Monitor:
"""Connection handling."""
def __init__(self, hass, mac, name):
"""Construct interface object."""
threading.Thread.__init__(self)
self.daemon = False
self.hass = hass
self.mac = mac
self.name = name
self.data = {'temp': STATE_UNKNOWN, 'humi... | the_stack_v2_python_sparse | homeassistant/components/skybeacon/sensor.py | home-assistant/core | train | 35,501 |
e3a973e94e4ec0a2fd4d3fda1f66fb5d4e2f40c4 | [
"def usd_to_usdt(sym):\n if sym == 'USD':\n return 'USDT'\n return sym\nfsym, tsym = (usd_to_usdt(name[0:3]), usd_to_usdt(name[3:]))\nreturn f'{tsym}-{fsym}'.upper()",
"def usd_to_usdt(sym):\n if sym == 'USD':\n return 'USDT'\nfsym = name.replace('_', '')[9:12]\ntsym = name.replace('_', '')... | <|body_start_0|>
def usd_to_usdt(sym):
if sym == 'USD':
return 'USDT'
return sym
fsym, tsym = (usd_to_usdt(name[0:3]), usd_to_usdt(name[3:]))
return f'{tsym}-{fsym}'.upper()
<|end_body_0|>
<|body_start_1|>
def usd_to_usdt(sym):
if sym ... | BittrexMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BittrexMixin:
def pair_local2bittrex(self, name):
"""BTCUSD -> BTC-USD."""
<|body_0|>
def pair_bittrex2local(self, name):
"""ok_sub_spotbtc_usd_trade -> BTCUSD."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def usd_to_usdt(sym):
if sym... | stack_v2_sparse_classes_75kplus_train_066851 | 8,320 | no_license | [
{
"docstring": "BTCUSD -> BTC-USD.",
"name": "pair_local2bittrex",
"signature": "def pair_local2bittrex(self, name)"
},
{
"docstring": "ok_sub_spotbtc_usd_trade -> BTCUSD.",
"name": "pair_bittrex2local",
"signature": "def pair_bittrex2local(self, name)"
}
] | 2 | null | Implement the Python class `BittrexMixin` described below.
Class description:
Implement the BittrexMixin class.
Method signatures and docstrings:
- def pair_local2bittrex(self, name): BTCUSD -> BTC-USD.
- def pair_bittrex2local(self, name): ok_sub_spotbtc_usd_trade -> BTCUSD. | Implement the Python class `BittrexMixin` described below.
Class description:
Implement the BittrexMixin class.
Method signatures and docstrings:
- def pair_local2bittrex(self, name): BTCUSD -> BTC-USD.
- def pair_bittrex2local(self, name): ok_sub_spotbtc_usd_trade -> BTCUSD.
<|skeleton|>
class BittrexMixin:
de... | b7fb2ee29ee75ac3585fd5b15e96624ec306eb02 | <|skeleton|>
class BittrexMixin:
def pair_local2bittrex(self, name):
"""BTCUSD -> BTC-USD."""
<|body_0|>
def pair_bittrex2local(self, name):
"""ok_sub_spotbtc_usd_trade -> BTCUSD."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BittrexMixin:
def pair_local2bittrex(self, name):
"""BTCUSD -> BTC-USD."""
def usd_to_usdt(sym):
if sym == 'USD':
return 'USDT'
return sym
fsym, tsym = (usd_to_usdt(name[0:3]), usd_to_usdt(name[3:]))
return f'{tsym}-{fsym}'.upper()
d... | the_stack_v2_python_sparse | cryptotrader/exchange/bittrex.py | ArtemijRodionov/cryptotrader | train | 0 | |
2f45a2926a1de10138543b3f92eaa4de5e739534 | [
"super().__init__(arg)\ndico_lock = arg['dico_lock']\nself.isSoft = dico_lock['isSoft']\nself.time_out = dico_lock['time_out']\nself.pathFile = arg['pathFile']\nself.pathFile_lock = self.pathFile + '.lock'\nif not self.exists():\n self.creation_file_demandes()\nreturn",
"if self.isSoft:\n from filelock impo... | <|body_start_0|>
super().__init__(arg)
dico_lock = arg['dico_lock']
self.isSoft = dico_lock['isSoft']
self.time_out = dico_lock['time_out']
self.pathFile = arg['pathFile']
self.pathFile_lock = self.pathFile + '.lock'
if not self.exists():
self.creation... | Gestion_echanges | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gestion_echanges:
def __init__(self, arg):
"""gestion des demandes par createur (avec lock) il y a plusieurs createur possibles createur = source de données {'createur' : {'demande_1' : {'parametres' : parametres, 'etat' : etat soit (open, running, close)} }"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_066852 | 3,040 | no_license | [
{
"docstring": "gestion des demandes par createur (avec lock) il y a plusieurs createur possibles createur = source de données {'createur' : {'demande_1' : {'parametres' : parametres, 'etat' : etat soit (open, running, close)} }",
"name": "__init__",
"signature": "def __init__(self, arg)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_016127 | Implement the Python class `Gestion_echanges` described below.
Class description:
Implement the Gestion_echanges class.
Method signatures and docstrings:
- def __init__(self, arg): gestion des demandes par createur (avec lock) il y a plusieurs createur possibles createur = source de données {'createur' : {'demande_1'... | Implement the Python class `Gestion_echanges` described below.
Class description:
Implement the Gestion_echanges class.
Method signatures and docstrings:
- def __init__(self, arg): gestion des demandes par createur (avec lock) il y a plusieurs createur possibles createur = source de données {'createur' : {'demande_1'... | 2f48c5375163f3dbf5c547b9d3555922b5026302 | <|skeleton|>
class Gestion_echanges:
def __init__(self, arg):
"""gestion des demandes par createur (avec lock) il y a plusieurs createur possibles createur = source de données {'createur' : {'demande_1' : {'parametres' : parametres, 'etat' : etat soit (open, running, close)} }"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gestion_echanges:
def __init__(self, arg):
"""gestion des demandes par createur (avec lock) il y a plusieurs createur possibles createur = source de données {'createur' : {'demande_1' : {'parametres' : parametres, 'etat' : etat soit (open, running, close)} }"""
super().__init__(arg)
di... | the_stack_v2_python_sparse | outils/Gestion_echanges.py | Patrick1953/Behavior | train | 0 | |
a857f8260317dfbd401fc19aa00ec30559a4fb1a | [
"packet = packets.TeltonikaConfiguration()\npacket.packetId = 1\npacket.addParam(packets.CFG_DEEP_SLEEP_MODE, 0)\npacket.addParam(packets.CFG_SORTING, packets.CFG_SORTING_ASC)\npacket.addParam(packets.CFG_ACTIVE_DATA_LINK_TIMEOUT, 20)\npacket.addParam(packets.CFG_TARGET_SERVER_IP_ADDRESS, config['host'])\npacket.ad... | <|body_start_0|>
packet = packets.TeltonikaConfiguration()
packet.packetId = 1
packet.addParam(packets.CFG_DEEP_SLEEP_MODE, 0)
packet.addParam(packets.CFG_SORTING, packets.CFG_SORTING_ASC)
packet.addParam(packets.CFG_ACTIVE_DATA_LINK_TIMEOUT, 20)
packet.addParam(packets.C... | TeltonkaCommandConfigure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeltonkaCommandConfigure:
def getConfigurationPacket(self, config):
"""Returns Teltonika configuration packet @param config: config dict @return:"""
<|body_0|>
def getInitiationSmsBuffer(self, data):
"""Returns initiation sms buffer @param data: dict @return:"""
... | stack_v2_sparse_classes_75kplus_train_066853 | 7,719 | no_license | [
{
"docstring": "Returns Teltonika configuration packet @param config: config dict @return:",
"name": "getConfigurationPacket",
"signature": "def getConfigurationPacket(self, config)"
},
{
"docstring": "Returns initiation sms buffer @param data: dict @return:",
"name": "getInitiationSmsBuffer... | 6 | stack_v2_sparse_classes_30k_train_041195 | Implement the Python class `TeltonkaCommandConfigure` described below.
Class description:
Implement the TeltonkaCommandConfigure class.
Method signatures and docstrings:
- def getConfigurationPacket(self, config): Returns Teltonika configuration packet @param config: config dict @return:
- def getInitiationSmsBuffer(... | Implement the Python class `TeltonkaCommandConfigure` described below.
Class description:
Implement the TeltonkaCommandConfigure class.
Method signatures and docstrings:
- def getConfigurationPacket(self, config): Returns Teltonika configuration packet @param config: config dict @return:
- def getInitiationSmsBuffer(... | 4a4bc730252ece695b2773388812e2d59d4947ce | <|skeleton|>
class TeltonkaCommandConfigure:
def getConfigurationPacket(self, config):
"""Returns Teltonika configuration packet @param config: config dict @return:"""
<|body_0|>
def getInitiationSmsBuffer(self, data):
"""Returns initiation sms buffer @param data: dict @return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeltonkaCommandConfigure:
def getConfigurationPacket(self, config):
"""Returns Teltonika configuration packet @param config: config dict @return:"""
packet = packets.TeltonikaConfiguration()
packet.packetId = 1
packet.addParam(packets.CFG_DEEP_SLEEP_MODE, 0)
packet.addP... | the_stack_v2_python_sparse | lib/handlers/teltonika/commands.py | maprox/pipe | train | 4 | |
02cc9a2c15805850a6778259704c666ff77620a6 | [
"super(MLPLayer, self).__init__()\nself.input_dim = input_dim\nself.output_dim = output_dim\nself.name_suffix = name_suffix\nself.batch_norm = batch_norm\nmodules = OrderedDict()\nmodules['hidden' + name_suffix] = nn.Linear(input_dim, output_dim, bias=bias)\nnn.init.xavier_normal_(modules['hidden' + name_suffix].we... | <|body_start_0|>
super(MLPLayer, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.name_suffix = name_suffix
self.batch_norm = batch_norm
modules = OrderedDict()
modules['hidden' + name_suffix] = nn.Linear(input_dim, output_dim, bias=bi... | Base layer for a fully-connected network. Parameters ---------- input_dim : input dimensions (int) options : dict native options: dataPrefix (str) : data root of dataset dataDirectory (str) : audio directory of dataset (default: dataPrefix + '/data') analysisDirectory (str) : transform directory of dataset (default: da... | MLPLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPLayer:
"""Base layer for a fully-connected network. Parameters ---------- input_dim : input dimensions (int) options : dict native options: dataPrefix (str) : data root of dataset dataDirectory (str) : audio directory of dataset (default: dataPrefix + '/data') analysisDirectory (str) : transfo... | stack_v2_sparse_classes_75kplus_train_066854 | 15,390 | no_license | [
{
"docstring": ":param input_dim: input dimension :type input_dim: int :param output_dim: output dimension :type output_dim: int :param nn_lin: non-linearity :type nn_lin: `str` or `nn.Module` :param batch_norm: batch normalization (batch or instance) :type batch_norm: str :param dropout: dropout probability (0... | 2 | stack_v2_sparse_classes_30k_test_000813 | Implement the Python class `MLPLayer` described below.
Class description:
Base layer for a fully-connected network. Parameters ---------- input_dim : input dimensions (int) options : dict native options: dataPrefix (str) : data root of dataset dataDirectory (str) : audio directory of dataset (default: dataPrefix + '/d... | Implement the Python class `MLPLayer` described below.
Class description:
Base layer for a fully-connected network. Parameters ---------- input_dim : input dimensions (int) options : dict native options: dataPrefix (str) : data root of dataset dataDirectory (str) : audio directory of dataset (default: dataPrefix + '/d... | 93da0ef4b8ef6694fd240f8e8823f9c51bd310a4 | <|skeleton|>
class MLPLayer:
"""Base layer for a fully-connected network. Parameters ---------- input_dim : input dimensions (int) options : dict native options: dataPrefix (str) : data root of dataset dataDirectory (str) : audio directory of dataset (default: dataPrefix + '/data') analysisDirectory (str) : transfo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLPLayer:
"""Base layer for a fully-connected network. Parameters ---------- input_dim : input dimensions (int) options : dict native options: dataPrefix (str) : data root of dataset dataDirectory (str) : audio directory of dataset (default: dataPrefix + '/data') analysisDirectory (str) : transform directory ... | the_stack_v2_python_sparse | modules/modules_bottleneck.py | domkirke/vschaos | train | 5 |
5b1ef5fd6c7696f62358d1765a07c5d4915cdd5e | [
"import re\ninput = re.split('(\\\\+|\\\\-|\\\\*|\\\\/)', input)\nn = len(input)\ndp = [[[] for _ in xrange(n)] for _ in xrange(n)]\nfor i in xrange(1, n + 1, 2):\n for j in xrange(0, n + 1 - i, 2):\n if i == 1:\n dp[j][j + i - 1].append(eval(input[j]))\n else:\n for k in xran... | <|body_start_0|>
import re
input = re.split('(\\+|\\-|\\*|\\/)', input)
n = len(input)
dp = [[[] for _ in xrange(n)] for _ in xrange(n)]
for i in xrange(1, n + 1, 2):
for j in xrange(0, n + 1 - i, 2):
if i == 1:
dp[j][j + i - 1].app... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
<|body_0|>
def diffWaysToCompute_rec(self, input):
""":type input: str :rtype: List[int]"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_066855 | 2,376 | permissive | [
{
"docstring": "define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position",
"name": "diffWaysToCompute",
"signature": "def diffWaysToCompute(self, input)"
},
{
"docstring": ":type input: str :rtype: List[int]",
"name": "diffWaysToCompute_rec",
... | 2 | stack_v2_sparse_classes_30k_train_000697 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diffWaysToCompute(self, input): define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position
- def diffWaysToCompute_rec(self, input)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diffWaysToCompute(self, input): define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position
- def diffWaysToCompute_rec(self, input)... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
<|body_0|>
def diffWaysToCompute_rec(self, input):
""":type input: str :rtype: List[int]"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
import re
input = re.split('(\\+|\\-|\\*|\\/)', input)
n = len(input)
dp = [[[] for _ in xrange(n)] for _ in xrange(... | the_stack_v2_python_sparse | 241-Different-Ways-to-Add-Parentheses/solution.py | Tanych/CodeTracking | train | 0 | |
1fe4cabbb4f4a39dbd98fc8783d192f90489670f | [
"array_len = len(array)\nif array_len == 0:\n return [-1, -1]\nmax_val = -9999\nmin_val = 9999\nfirst_pos = -1\nlast_pos = -1\nfor i in range(array_len):\n if max_val <= array[i]:\n max_val = max(array[i], max_val)\n else:\n last_pos = i\nfor i in range(array_len - 1, -1, -1):\n if min_val... | <|body_start_0|>
array_len = len(array)
if array_len == 0:
return [-1, -1]
max_val = -9999
min_val = 9999
first_pos = -1
last_pos = -1
for i in range(array_len):
if max_val <= array[i]:
max_val = max(array[i], max_val)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subSort1(self, array: List[int]) -> List[int]:
"""方法:左右指针 【两遍遍历】"""
<|body_0|>
def subSort(self, array: List[int]) -> List[int]:
"""方法:左右指针 【一遍遍历】"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
array_len = len(array)
if array_... | stack_v2_sparse_classes_75kplus_train_066856 | 1,820 | no_license | [
{
"docstring": "方法:左右指针 【两遍遍历】",
"name": "subSort1",
"signature": "def subSort1(self, array: List[int]) -> List[int]"
},
{
"docstring": "方法:左右指针 【一遍遍历】",
"name": "subSort",
"signature": "def subSort(self, array: List[int]) -> List[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_023584 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subSort1(self, array: List[int]) -> List[int]: 方法:左右指针 【两遍遍历】
- def subSort(self, array: List[int]) -> List[int]: 方法:左右指针 【一遍遍历】 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subSort1(self, array: List[int]) -> List[int]: 方法:左右指针 【两遍遍历】
- def subSort(self, array: List[int]) -> List[int]: 方法:左右指针 【一遍遍历】
<|skeleton|>
class Solution:
def subSor... | f831fd9603592ae5bee3679924f962a3ebce381c | <|skeleton|>
class Solution:
def subSort1(self, array: List[int]) -> List[int]:
"""方法:左右指针 【两遍遍历】"""
<|body_0|>
def subSort(self, array: List[int]) -> List[int]:
"""方法:左右指针 【一遍遍历】"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subSort1(self, array: List[int]) -> List[int]:
"""方法:左右指针 【两遍遍历】"""
array_len = len(array)
if array_len == 0:
return [-1, -1]
max_val = -9999
min_val = 9999
first_pos = -1
last_pos = -1
for i in range(array_len):
... | the_stack_v2_python_sparse | topic25_left_right_pointer/MS1616_subSort1/interview.py | GongFuXiong/leetcode | train | 0 | |
3ab8a4e7b381ee5c5f69a1d9d3bd140664309fd0 | [
"right = []\nq, result = (deque(), [])\nq = deque()\nif root:\n q.append(root)\nwhile len(q):\n level = []\n for _ in range(len(q)):\n x = q.popleft()\n level.append(x.val)\n if x.left:\n q.append(x.left)\n if x.right:\n q.append(x.right)\n right.append(... | <|body_start_0|>
right = []
q, result = (deque(), [])
q = deque()
if root:
q.append(root)
while len(q):
level = []
for _ in range(len(q)):
x = q.popleft()
level.append(x.val)
if x.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def leftSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
right = []
q, result = (... | stack_v2_sparse_classes_75kplus_train_066857 | 1,423 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "rightSideView",
"signature": "def rightSideView(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "leftSideView",
"signature": "def leftSideView(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023680 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int]
- def leftSideView(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int]
- def leftSideView(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solution:
de... | 049fd6dea5557299f921faeadfe5c1c84bf50a2f | <|skeleton|>
class Solution:
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def leftSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
right = []
q, result = (deque(), [])
q = deque()
if root:
q.append(root)
while len(q):
level = []
for _ in range(len(q)):
x ... | the_stack_v2_python_sparse | p199_binary_tree_right_side_view.py | ymwondimu/LeetCode | train | 0 | |
e78bd14cc904e01c58b57fec2375d0b1989aef5c | [
"dp, dp1, dp2 = (0, 0, 1)\nfor _ in range(n):\n dp = dp1 + dp2\n dp1 = dp2\n dp2 = dp\nreturn dp",
"q = [[1, 1], [1, 0]]\nrv = self.matrix_pow(q, n)\nreturn rv[0][0]",
"rv = [[1, 0], [0, 1]]\nwhile n > 0:\n if n & 1:\n rv = self.matrix_multiply(rv, a)\n n >>= 1\n a = self.matrix_multipl... | <|body_start_0|>
dp, dp1, dp2 = (0, 0, 1)
for _ in range(n):
dp = dp1 + dp2
dp1 = dp2
dp2 = dp
return dp
<|end_body_0|>
<|body_start_1|>
q = [[1, 1], [1, 0]]
rv = self.matrix_pow(q, n)
return rv[0][0]
<|end_body_1|>
<|body_start_2|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n: int) -> int:
"""动态规划"""
<|body_0|>
def climbStairsMatrix(self, n: int) -> int:
"""矩阵快速幂"""
<|body_1|>
def matrix_pow(self, a: List[List[int]], n: int) -> List[List[int]]:
"""二阶矩阵幂"""
<|body_2|>
def ... | stack_v2_sparse_classes_75kplus_train_066858 | 1,560 | no_license | [
{
"docstring": "动态规划",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
},
{
"docstring": "矩阵快速幂",
"name": "climbStairsMatrix",
"signature": "def climbStairsMatrix(self, n: int) -> int"
},
{
"docstring": "二阶矩阵幂",
"name": "matrix_pow",
"signature"... | 5 | stack_v2_sparse_classes_30k_train_015378 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: 动态规划
- def climbStairsMatrix(self, n: int) -> int: 矩阵快速幂
- def matrix_pow(self, a: List[List[int]], n: int) -> List[List[int]]: 二阶矩阵幂
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: 动态规划
- def climbStairsMatrix(self, n: int) -> int: 矩阵快速幂
- def matrix_pow(self, a: List[List[int]], n: int) -> List[List[int]]: 二阶矩阵幂
- def ... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def climbStairs(self, n: int) -> int:
"""动态规划"""
<|body_0|>
def climbStairsMatrix(self, n: int) -> int:
"""矩阵快速幂"""
<|body_1|>
def matrix_pow(self, a: List[List[int]], n: int) -> List[List[int]]:
"""二阶矩阵幂"""
<|body_2|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def climbStairs(self, n: int) -> int:
"""动态规划"""
dp, dp1, dp2 = (0, 0, 1)
for _ in range(n):
dp = dp1 + dp2
dp1 = dp2
dp2 = dp
return dp
def climbStairsMatrix(self, n: int) -> int:
"""矩阵快速幂"""
q = [[1, 1], [1, 0... | the_stack_v2_python_sparse | 70.爬楼梯/solution.py | QtTao/daily_leetcode | train | 0 | |
1b27a07071ac669eed2ea6fd63abbb44245e8a56 | [
"if amount == 0:\n return 0\nqueue = collections.deque(coins)\nd = {x: 1 for x in coins}\nwhile queue:\n cur = queue.popleft()\n if cur == amount:\n return d[cur]\n for i in coins:\n k = cur + i\n if k <= amount and (not k in d):\n queue.append(k)\n d[k] = d[cu... | <|body_start_0|>
if amount == 0:
return 0
queue = collections.deque(coins)
d = {x: 1 for x in coins}
while queue:
cur = queue.popleft()
if cur == amount:
return d[cur]
for i in coins:
k = cur + i
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
"""bfs AC :param coins: :param amount: :return:"""
<|body_0|>
def coinChange3(self, coins, amount):
"""完全背包问题 :param coins: :param amount: :return:"""
<|body_1|>
def coinChange2(self, coins, amount):
... | stack_v2_sparse_classes_75kplus_train_066859 | 2,469 | no_license | [
{
"docstring": "bfs AC :param coins: :param amount: :return:",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": "完全背包问题 :param coins: :param amount: :return:",
"name": "coinChange3",
"signature": "def coinChange3(self, coins, amount)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_027192 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): bfs AC :param coins: :param amount: :return:
- def coinChange3(self, coins, amount): 完全背包问题 :param coins: :param amount: :return:
- def coinC... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): bfs AC :param coins: :param amount: :return:
- def coinChange3(self, coins, amount): 完全背包问题 :param coins: :param amount: :return:
- def coinC... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
"""bfs AC :param coins: :param amount: :return:"""
<|body_0|>
def coinChange3(self, coins, amount):
"""完全背包问题 :param coins: :param amount: :return:"""
<|body_1|>
def coinChange2(self, coins, amount):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def coinChange(self, coins, amount):
"""bfs AC :param coins: :param amount: :return:"""
if amount == 0:
return 0
queue = collections.deque(coins)
d = {x: 1 for x in coins}
while queue:
cur = queue.popleft()
if cur == amount:... | the_stack_v2_python_sparse | 322_零钱兑换.py | lovehhf/LeetCode | train | 0 | |
ad55fd48fd54516f8401b9de7e3d8f5f7fc76c9a | [
"rv = []\nfor filename in os.listdir(cmd_folder):\n if filename.endswith('.py') and filename.startswith('cmd_'):\n rv.append(filename[4:-3])\nrv.sort()\nreturn rv",
"try:\n if sys.version_info[0] == 2:\n name = name.encode('ascii', 'replace')\n mod = __import__('popper.commands.cmd_' + name... | <|body_start_0|>
rv = []
for filename in os.listdir(cmd_folder):
if filename.endswith('.py') and filename.startswith('cmd_'):
rv.append(filename[4:-3])
rv.sort()
return rv
<|end_body_0|>
<|body_start_1|>
try:
if sys.version_info[0] == 2:
... | Provides CLI interface for Popper. | PopperCLI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopperCLI:
"""Provides CLI interface for Popper."""
def list_commands(self, ctx):
"""Returns the list of available commands in sorted order. Args: ctx(popper.cli.context): For process inter-command communication. For reference visit https://click.palletsprojects.com/en/7.x Returns: l... | stack_v2_sparse_classes_75kplus_train_066860 | 2,791 | permissive | [
{
"docstring": "Returns the list of available commands in sorted order. Args: ctx(popper.cli.context): For process inter-command communication. For reference visit https://click.palletsprojects.com/en/7.x Returns: list: Returns the list of available commands.",
"name": "list_commands",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_016264 | Implement the Python class `PopperCLI` described below.
Class description:
Provides CLI interface for Popper.
Method signatures and docstrings:
- def list_commands(self, ctx): Returns the list of available commands in sorted order. Args: ctx(popper.cli.context): For process inter-command communication. For reference ... | Implement the Python class `PopperCLI` described below.
Class description:
Provides CLI interface for Popper.
Method signatures and docstrings:
- def list_commands(self, ctx): Returns the list of available commands in sorted order. Args: ctx(popper.cli.context): For process inter-command communication. For reference ... | 9bbbe3340daea7161230a219fe2381603ba2a622 | <|skeleton|>
class PopperCLI:
"""Provides CLI interface for Popper."""
def list_commands(self, ctx):
"""Returns the list of available commands in sorted order. Args: ctx(popper.cli.context): For process inter-command communication. For reference visit https://click.palletsprojects.com/en/7.x Returns: l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PopperCLI:
"""Provides CLI interface for Popper."""
def list_commands(self, ctx):
"""Returns the list of available commands in sorted order. Args: ctx(popper.cli.context): For process inter-command communication. For reference visit https://click.palletsprojects.com/en/7.x Returns: list: Returns ... | the_stack_v2_python_sparse | cli/popper/cli.py | vipulchhabra99/popper | train | 1 |
d472d6f4e814e07b9afebb3f8314e93c7c52a355 | [
"sensor = TimerSensor(self.mudpi, config)\nself.add_component(sensor)\nreturn True",
"self.register_component_actions('start', action='start')\nself.register_component_actions('stop', action='stop')\nself.register_component_actions('reset', action='reset')\nself.register_component_actions('pause', action='pause')... | <|body_start_0|>
sensor = TimerSensor(self.mudpi, config)
self.add_component(sensor)
return True
<|end_body_0|>
<|body_start_1|>
self.register_component_actions('start', action='start')
self.register_component_actions('stop', action='stop')
self.register_component_action... | Interface | [
"BSD-4-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
def load(self, config):
"""Load timer sensor component from configs"""
<|body_0|>
def register_actions(self):
"""Register any interface actions"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sensor = TimerSensor(self.mudpi, config)
... | stack_v2_sparse_classes_75kplus_train_066861 | 4,836 | permissive | [
{
"docstring": "Load timer sensor component from configs",
"name": "load",
"signature": "def load(self, config)"
},
{
"docstring": "Register any interface actions",
"name": "register_actions",
"signature": "def register_actions(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008379 | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load timer sensor component from configs
- def register_actions(self): Register any interface actions | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load timer sensor component from configs
- def register_actions(self): Register any interface actions
<|skeleton|>
class Interface:
def load(self,... | fb206b1136f529c7197f1e6b29629ed05630d377 | <|skeleton|>
class Interface:
def load(self, config):
"""Load timer sensor component from configs"""
<|body_0|>
def register_actions(self):
"""Register any interface actions"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interface:
def load(self, config):
"""Load timer sensor component from configs"""
sensor = TimerSensor(self.mudpi, config)
self.add_component(sensor)
return True
def register_actions(self):
"""Register any interface actions"""
self.register_component_action... | the_stack_v2_python_sparse | mudpi/extensions/timer/sensor.py | mistasp0ck/mudpi-core | train | 0 | |
0633c660f6d08d3c0bd80dd0d2198ae024fab76c | [
"self.stratigraphic_log = []\nself.water_strike = []\nif self.data.get('drilling', None):\n self.form = self._make_form(self.well.drilling if self.well.drilling else Drilling(), DrillingForm, self.data['drilling'])\n if self.data['drilling'].get('stratigraphic_log', None):\n for log in self.data['drill... | <|body_start_0|>
self.stratigraphic_log = []
self.water_strike = []
if self.data.get('drilling', None):
self.form = self._make_form(self.well.drilling if self.well.drilling else Drilling(), DrillingForm, self.data['drilling'])
if self.data['drilling'].get('stratigraphic_l... | Collection form for general information section | DrillingCreateForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DrillingCreateForm:
"""Collection form for general information section"""
def create(self):
"""create form from data"""
<|body_0|>
def save(self):
"""save all available data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.stratigraphic_log ... | stack_v2_sparse_classes_75kplus_train_066862 | 2,549 | no_license | [
{
"docstring": "create form from data",
"name": "create",
"signature": "def create(self)"
},
{
"docstring": "save all available data",
"name": "save",
"signature": "def save(self)"
}
] | 2 | null | Implement the Python class `DrillingCreateForm` described below.
Class description:
Collection form for general information section
Method signatures and docstrings:
- def create(self): create form from data
- def save(self): save all available data | Implement the Python class `DrillingCreateForm` described below.
Class description:
Collection form for general information section
Method signatures and docstrings:
- def create(self): create form from data
- def save(self): save all available data
<|skeleton|>
class DrillingCreateForm:
"""Collection form for g... | fc036f9f8346dee2d40287d08375a6c2af0a1a12 | <|skeleton|>
class DrillingCreateForm:
"""Collection form for general information section"""
def create(self):
"""create form from data"""
<|body_0|>
def save(self):
"""save all available data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DrillingCreateForm:
"""Collection form for general information section"""
def create(self):
"""create form from data"""
self.stratigraphic_log = []
self.water_strike = []
if self.data.get('drilling', None):
self.form = self._make_form(self.well.drilling if self... | the_stack_v2_python_sparse | views/form_group/drilling.py | Alexia-Water/IGRAC-WellAndMonitoringDatabase | train | 0 |
820d99d5a9211eb39116a44f2c03cd59d99c5a25 | [
"cur = head\nidx = 0\npassed_dict = {}\nwhile cur:\n if cur in passed_dict:\n return cur\n passed_dict[cur] = idx\n cur = cur.next\n idx += 1\nelse:\n return None",
"fast = slow = head\nwhile slow and fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\... | <|body_start_0|>
cur = head
idx = 0
passed_dict = {}
while cur:
if cur in passed_dict:
return cur
passed_dict[cur] = idx
cur = cur.next
idx += 1
else:
return None
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle2(self, head):
"""集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle(self, head):
"""快慢指针法 :type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head
... | stack_v2_sparse_classes_75kplus_train_066863 | 2,258 | no_license | [
{
"docstring": "集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode",
"name": "detectCycle2",
"signature": "def detectCycle2(self, head)"
},
{
"docstring": "快慢指针法 :type head: ListNode :rtype: bool",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051615 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle2(self, head): 集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode
- def detectCycle(self, head): 快慢指针法 :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle2(self, head): 集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode
- def detectCycle(self, head): 快慢指针法 :type head: ListNode :rtype: bool
<|skeleton|>
class Solu... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def detectCycle2(self, head):
"""集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle(self, head):
"""快慢指针法 :type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def detectCycle2(self, head):
"""集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode"""
cur = head
idx = 0
passed_dict = {}
while cur:
if cur in passed_dict:
return cur
passed_dict[cur] = idx
cur = cur.next
... | the_stack_v2_python_sparse | leetcode/142.linked-list-cycle-ii.py | iamkissg/leetcode | train | 0 | |
e99fd102efb4cf06f571cf7ace677bb46a600cbc | [
"self.v1 = v1\nself.v2 = v2\nself.p1 = 0\nself.p2 = 0\nself.n1 = len(v1)\nself.n2 = len(v2)\nself.first = True",
"if self.first and self.p1 < self.n1 or self.p2 >= self.n2:\n self.first = False\n res = self.v1[self.p1]\n self.p1 += 1\nelse:\n self.first = True\n res = self.v2[self.p2]\n self.p2 ... | <|body_start_0|>
self.v1 = v1
self.v2 = v2
self.p1 = 0
self.p2 = 0
self.n1 = len(v1)
self.n2 = len(v2)
self.first = True
<|end_body_0|>
<|body_start_1|>
if self.first and self.p1 < self.n1 or self.p2 >= self.n2:
self.first = False
... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus_train_066864 | 1,045 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | stack_v2_sparse_classes_30k_train_002588 | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | 917bd000c2a055dfa2633440a61ca4ae2b665fe3 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.v1 = v1
self.v2 = v2
self.p1 = 0
self.p2 = 0
self.n1 = len(v1)
self.n2 = len(v2)
self.first = True
def next(s... | the_stack_v2_python_sparse | 281_zigzag-iterator.py | Khrystynka/LeetCodeProblems | train | 0 | |
c5eaae023283ae00fff03e1c139917494f88b2f0 | [
"height = DESCRIPTION_SCALE[-1] * HEIGHT_FACTOR\nself.__descriptionWindow = TextWindow(height=height, position=[0, 0])\ntop = height\nheight = AUTOCOMPLETE_SCALE[-1] * HEIGHT_FACTOR\nself.__userTextWindow = TextWindow(height=height, position=[0, top])\ntop += height\nself.__suggestionWindows = []\nfor i in range(co... | <|body_start_0|>
height = DESCRIPTION_SCALE[-1] * HEIGHT_FACTOR
self.__descriptionWindow = TextWindow(height=height, position=[0, 0])
top = height
height = AUTOCOMPLETE_SCALE[-1] * HEIGHT_FACTOR
self.__userTextWindow = TextWindow(height=height, position=[0, top])
top += h... | Implements the quasimode's display, in a multi-line transparent window. | TheQuasimodeWindow | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TheQuasimodeWindow:
"""Implements the quasimode's display, in a multi-line transparent window."""
def __init__(self):
"""Instantiates the quasimode window, creating all the necessary windows."""
<|body_0|>
def update(self, quasimode, isFullRedraw):
"""Fetches upd... | stack_v2_sparse_classes_75kplus_train_066865 | 8,326 | permissive | [
{
"docstring": "Instantiates the quasimode window, creating all the necessary windows.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Fetches updated information from the quasimode, lays out and draws the quasimode window. This should only be called when the quasimode... | 3 | stack_v2_sparse_classes_30k_train_053127 | Implement the Python class `TheQuasimodeWindow` described below.
Class description:
Implements the quasimode's display, in a multi-line transparent window.
Method signatures and docstrings:
- def __init__(self): Instantiates the quasimode window, creating all the necessary windows.
- def update(self, quasimode, isFul... | Implement the Python class `TheQuasimodeWindow` described below.
Class description:
Implements the quasimode's display, in a multi-line transparent window.
Method signatures and docstrings:
- def __init__(self): Instantiates the quasimode window, creating all the necessary windows.
- def update(self, quasimode, isFul... | 61351f52f01367439e8810d2c482a9c9897545d8 | <|skeleton|>
class TheQuasimodeWindow:
"""Implements the quasimode's display, in a multi-line transparent window."""
def __init__(self):
"""Instantiates the quasimode window, creating all the necessary windows."""
<|body_0|>
def update(self, quasimode, isFullRedraw):
"""Fetches upd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TheQuasimodeWindow:
"""Implements the quasimode's display, in a multi-line transparent window."""
def __init__(self):
"""Instantiates the quasimode window, creating all the necessary windows."""
height = DESCRIPTION_SCALE[-1] * HEIGHT_FACTOR
self.__descriptionWindow = TextWindow(h... | the_stack_v2_python_sparse | enso/enso/quasimode/window.py | GChristensen/enso-portable | train | 144 |
fe69397c12eb30c0ae414ac8f0691f2ea9bdcbe0 | [
"if not root:\n return ''\n\ndef preorder(di: dict, root: TreeNode, idx: int=0):\n di[idx] = (root.val, idx * 2 + 1 if root.left else None, idx * 2 + 2 if root.right else None)\n if root.left:\n preorder(di, root.left, idx * 2 + 1)\n if root.right:\n preorder(di, root.right, idx * 2 + 2)\n... | <|body_start_0|>
if not root:
return ''
def preorder(di: dict, root: TreeNode, idx: int=0):
di[idx] = (root.val, idx * 2 + 1 if root.left else None, idx * 2 + 2 if root.right else None)
if root.left:
preorder(di, root.left, idx * 2 + 1)
if... | Codec | [] | 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_066866 | 3,028 | no_license | [
{
"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_024233 | 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:... | 89755fc95c2bace7e644af189ec29df9a2ffb277 | <|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"""
if not root:
return ''
def preorder(di: dict, root: TreeNode, idx: int=0):
di[idx] = (root.val, idx * 2 + 1 if root.left else None, idx * 2 + 2 if root.r... | the_stack_v2_python_sparse | OnlineJudge/LeetCode/第1个进度/297.二叉树的序列化与反序列化.py | CrazyIEEE/algorithm | train | 0 | |
45cf4e8bdd242efc476bc31fafd191187711913d | [
"self._current = tree\nself._stop_parent = None\nif tree.getParent() is not None:\n self._stop_parent = tree.getParent()",
"parent = node.getParent()\nif parent == self._stop_parent:\n return (None, None)\nif parent is None:\n return (None, None)\nsiblings = parent.getChildren()\ntry:\n next_pos = sib... | <|body_start_0|>
self._current = tree
self._stop_parent = None
if tree.getParent() is not None:
self._stop_parent = tree.getParent()
<|end_body_0|>
<|body_start_1|>
parent = node.getParent()
if parent == self._stop_parent:
return (None, None)
if p... | Iterator does a depth first traversal of the associated tree. Tree may be a subtree. | TreeIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeIterator:
"""Iterator does a depth first traversal of the associated tree. Tree may be a subtree."""
def __init__(self, tree):
""":params Tree tree:"""
<|body_0|>
def _nextSibling(self, node):
"""Finds the next sibling of the current node or None :param Tree ... | stack_v2_sparse_classes_75kplus_train_066867 | 22,149 | permissive | [
{
"docstring": ":params Tree tree:",
"name": "__init__",
"signature": "def __init__(self, tree)"
},
{
"docstring": "Finds the next sibling of the current node or None :param Tree node: :return Tree,Tree: sibling, parent",
"name": "_nextSibling",
"signature": "def _nextSibling(self, node)... | 3 | stack_v2_sparse_classes_30k_train_008322 | Implement the Python class `TreeIterator` described below.
Class description:
Iterator does a depth first traversal of the associated tree. Tree may be a subtree.
Method signatures and docstrings:
- def __init__(self, tree): :params Tree tree:
- def _nextSibling(self, node): Finds the next sibling of the current node... | Implement the Python class `TreeIterator` described below.
Class description:
Iterator does a depth first traversal of the associated tree. Tree may be a subtree.
Method signatures and docstrings:
- def __init__(self, tree): :params Tree tree:
- def _nextSibling(self, node): Finds the next sibling of the current node... | d271ab1a4a84ddedf384213db4e3ca272b891967 | <|skeleton|>
class TreeIterator:
"""Iterator does a depth first traversal of the associated tree. Tree may be a subtree."""
def __init__(self, tree):
""":params Tree tree:"""
<|body_0|>
def _nextSibling(self, node):
"""Finds the next sibling of the current node or None :param Tree ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeIterator:
"""Iterator does a depth first traversal of the associated tree. Tree may be a subtree."""
def __init__(self, tree):
""":params Tree tree:"""
self._current = tree
self._stop_parent = None
if tree.getParent() is not None:
self._stop_parent = tree.g... | the_stack_v2_python_sparse | ScienceStacksCommon/Python/common_tree/tree.py | ScienceStacks/ScienceStacksCommon | train | 0 |
49fddbdba6f7fe17276a31441f877e3ef2c48bfe | [
"self._potential = potential\nself._eps = eps\nself._energy = energy\nself._energydelta = energydelta\nself._dimension = D\nself._lattice_computed = False",
"dimension = self._dimension\nlatdist = 0.75 * self._eps * sqrt(pi)\nqslicers = [slice(lims[0], lims[1] + latdist, latdist) for lims in qlimits]\npslicers = ... | <|body_start_0|>
self._potential = potential
self._eps = eps
self._energy = energy
self._energydelta = energydelta
self._dimension = D
self._lattice_computed = False
<|end_body_0|>
<|body_start_1|>
dimension = self._dimension
latdist = 0.75 * self._eps * ... | A phase space lattice centered around an energy :math:`E_0` and bounded by an energy delta :math:`\\Delta E`. | PhaseSpaceLattice | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhaseSpaceLattice:
"""A phase space lattice centered around an energy :math:`E_0` and bounded by an energy delta :math:`\\Delta E`."""
def __init__(self, potential, energy, energydelta, eps, D):
"""Configure a new phase space lattice centered around an energy :math:`E_0` and bounded ... | stack_v2_sparse_classes_75kplus_train_066868 | 4,279 | permissive | [
{
"docstring": "Configure a new phase space lattice centered around an energy :math:`E_0` and bounded by an energy delta :math:`\\\\Delta E`. The actual lattice points are computed by the member function :py:func:`compute_lattice`. :param potential: The potential :math:`V`. :type potential: Not a :py:class:`Mat... | 4 | stack_v2_sparse_classes_30k_train_042628 | Implement the Python class `PhaseSpaceLattice` described below.
Class description:
A phase space lattice centered around an energy :math:`E_0` and bounded by an energy delta :math:`\\Delta E`.
Method signatures and docstrings:
- def __init__(self, potential, energy, energydelta, eps, D): Configure a new phase space l... | Implement the Python class `PhaseSpaceLattice` described below.
Class description:
A phase space lattice centered around an energy :math:`E_0` and bounded by an energy delta :math:`\\Delta E`.
Method signatures and docstrings:
- def __init__(self, potential, energy, energydelta, eps, D): Configure a new phase space l... | 225b5dd9b1af1998bd40b5f6467ee959292b6a83 | <|skeleton|>
class PhaseSpaceLattice:
"""A phase space lattice centered around an energy :math:`E_0` and bounded by an energy delta :math:`\\Delta E`."""
def __init__(self, potential, energy, energydelta, eps, D):
"""Configure a new phase space lattice centered around an energy :math:`E_0` and bounded ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhaseSpaceLattice:
"""A phase space lattice centered around an energy :math:`E_0` and bounded by an energy delta :math:`\\Delta E`."""
def __init__(self, potential, energy, energydelta, eps, D):
"""Configure a new phase space lattice centered around an energy :math:`E_0` and bounded by an energy ... | the_stack_v2_python_sparse | WaveBlocksND/PhaseSpaceLattice.py | WaveBlocks/WaveBlocksND | train | 4 |
93fa287d8e673dd274278ef31673bb2cdb52b300 | [
"base.Action.__init__(self, self.__loadAtlas)\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx\nself.__frame = frame",
"if len(atlases.listAtlases()) == 0:\n atlases.rescanAtlases()\nloadAtlas(self.__frame)"
] | <|body_start_0|>
base.Action.__init__(self, self.__loadAtlas)
self.__overlayList = overlayList
self.__displayCtx = displayCtx
self.__frame = frame
<|end_body_0|>
<|body_start_1|>
if len(atlases.listAtlases()) == 0:
atlases.rescanAtlases()
loadAtlas(self.__fra... | The ``LoadAtlasAction`` prompts the user to select a FSL atlas specification file. This file is then passed to the :func:`.fsl.data.atlases.addAtlas` function, to add the atlas to the :class:`.AtlasRegistry`. | LoadAtlasAction | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadAtlasAction:
"""The ``LoadAtlasAction`` prompts the user to select a FSL atlas specification file. This file is then passed to the :func:`.fsl.data.atlases.addAtlas` function, to add the atlas to the :class:`.AtlasRegistry`."""
def __init__(self, overlayList, displayCtx, frame):
... | stack_v2_sparse_classes_75kplus_train_066869 | 2,121 | permissive | [
{
"docstring": "Create a ``LoadAtlasAction``. :arg overlayList: The :class:`.OverlayList`. :arg displayCtx: The :class:`.DisplayContext`. :arg frame: The :class:`.FSLeyesFrame`.",
"name": "__init__",
"signature": "def __init__(self, overlayList, displayCtx, frame)"
},
{
"docstring": "Calls the :... | 2 | stack_v2_sparse_classes_30k_train_013033 | Implement the Python class `LoadAtlasAction` described below.
Class description:
The ``LoadAtlasAction`` prompts the user to select a FSL atlas specification file. This file is then passed to the :func:`.fsl.data.atlases.addAtlas` function, to add the atlas to the :class:`.AtlasRegistry`.
Method signatures and docstr... | Implement the Python class `LoadAtlasAction` described below.
Class description:
The ``LoadAtlasAction`` prompts the user to select a FSL atlas specification file. This file is then passed to the :func:`.fsl.data.atlases.addAtlas` function, to add the atlas to the :class:`.AtlasRegistry`.
Method signatures and docstr... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class LoadAtlasAction:
"""The ``LoadAtlasAction`` prompts the user to select a FSL atlas specification file. This file is then passed to the :func:`.fsl.data.atlases.addAtlas` function, to add the atlas to the :class:`.AtlasRegistry`."""
def __init__(self, overlayList, displayCtx, frame):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadAtlasAction:
"""The ``LoadAtlasAction`` prompts the user to select a FSL atlas specification file. This file is then passed to the :func:`.fsl.data.atlases.addAtlas` function, to add the atlas to the :class:`.AtlasRegistry`."""
def __init__(self, overlayList, displayCtx, frame):
"""Create a `... | the_stack_v2_python_sparse | fsleyes/actions/loadatlas.py | sanjayankur31/fsleyes | train | 1 |
01c70a3ce64a35861398a6fded9db64d12ec285e | [
"if arch_code is None:\n warnings.warn('arch_code not provided when not searching.')\nsuper().__init__(arch_code=arch_code, channel_mul=channel_mul, cell=cell, num_blocks=num_blocks, num_depths=num_depths, spatial_dims=spatial_dims, act_name=act_name, norm_name=norm_name, use_downsample=use_downsample, device=de... | <|body_start_0|>
if arch_code is None:
warnings.warn('arch_code not provided when not searching.')
super().__init__(arch_code=arch_code, channel_mul=channel_mul, cell=cell, num_blocks=num_blocks, num_depths=num_depths, spatial_dims=spatial_dims, act_name=act_name, norm_name=norm_name, use_do... | Instance of the final searched architecture. Only used in re-training/inference stage. | TopologyInstance | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologyInstance:
"""Instance of the final searched architecture. Only used in re-training/inference stage."""
def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str... | stack_v2_sparse_classes_75kplus_train_066870 | 44,771 | permissive | [
{
"docstring": "Initialize DiNTS topology search space of neural architectures.",
"name": "__init__",
"signature": "def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str=('INST... | 2 | stack_v2_sparse_classes_30k_train_016414 | Implement the Python class `TopologyInstance` described below.
Class description:
Instance of the final searched architecture. Only used in re-training/inference stage.
Method signatures and docstrings:
- def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spati... | Implement the Python class `TopologyInstance` described below.
Class description:
Instance of the final searched architecture. Only used in re-training/inference stage.
Method signatures and docstrings:
- def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spati... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class TopologyInstance:
"""Instance of the final searched architecture. Only used in re-training/inference stage."""
def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopologyInstance:
"""Instance of the final searched architecture. Only used in re-training/inference stage."""
def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str=('INSTANCE',... | the_stack_v2_python_sparse | monai/networks/nets/dints.py | Project-MONAI/MONAI | train | 4,805 |
ff542d078579fdbaf474c289ad0cddf59dec1392 | [
"logger.info('Uploading file {} to {}'.format(url, destination))\ntmpfile = 'tmp.json'\nzipfile = tmpfile + '.gz'\nurllib.request.urlretrieve(url, tmpfile)\nwith open(tmpfile, 'rb') as f_in:\n with gzip.open(zipfile, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\nself._client.upload_file(zipfile, conf... | <|body_start_0|>
logger.info('Uploading file {} to {}'.format(url, destination))
tmpfile = 'tmp.json'
zipfile = tmpfile + '.gz'
urllib.request.urlretrieve(url, tmpfile)
with open(tmpfile, 'rb') as f_in:
with gzip.open(zipfile, 'wb') as f_out:
shutil.co... | S3Client | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3Client:
def upload_file_from_url(self, url: str, destination: str):
"""Pulls data from a certain URL, compresses it, and uploads it to S3. :param url: URL to pull data from. :param destination: Path within S3 to store data :return:"""
<|body_0|>
def upload_file_from_variab... | stack_v2_sparse_classes_75kplus_train_066871 | 1,960 | permissive | [
{
"docstring": "Pulls data from a certain URL, compresses it, and uploads it to S3. :param url: URL to pull data from. :param destination: Path within S3 to store data :return:",
"name": "upload_file_from_url",
"signature": "def upload_file_from_url(self, url: str, destination: str)"
},
{
"docst... | 2 | null | Implement the Python class `S3Client` described below.
Class description:
Implement the S3Client class.
Method signatures and docstrings:
- def upload_file_from_url(self, url: str, destination: str): Pulls data from a certain URL, compresses it, and uploads it to S3. :param url: URL to pull data from. :param destinat... | Implement the Python class `S3Client` described below.
Class description:
Implement the S3Client class.
Method signatures and docstrings:
- def upload_file_from_url(self, url: str, destination: str): Pulls data from a certain URL, compresses it, and uploads it to S3. :param url: URL to pull data from. :param destinat... | e9bcd9367dfcf4984f64c61a526746abcf980715 | <|skeleton|>
class S3Client:
def upload_file_from_url(self, url: str, destination: str):
"""Pulls data from a certain URL, compresses it, and uploads it to S3. :param url: URL to pull data from. :param destination: Path within S3 to store data :return:"""
<|body_0|>
def upload_file_from_variab... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class S3Client:
def upload_file_from_url(self, url: str, destination: str):
"""Pulls data from a certain URL, compresses it, and uploads it to S3. :param url: URL to pull data from. :param destination: Path within S3 to store data :return:"""
logger.info('Uploading file {} to {}'.format(url, destina... | the_stack_v2_python_sparse | contrail/crawler/s3upload.py | joshuaprince/Contrail | train | 6 | |
db4941b12e726142cad9ca966f5fca73544be29d | [
"dice = randint(1, 6)\nif self.fullness <= 20:\n self.eat()\nelif self.house.money <= 50:\n self.work()\nelif dice == 1:\n self.work()\nelif dice == 2:\n self.eat()\nelif dice == 3:\n self.gaming()\nelif dice == 4:\n self.pet_the_cat()\nelse:\n self.work()",
"cprint('{} сходил на работу'.form... | <|body_start_0|>
dice = randint(1, 6)
if self.fullness <= 20:
self.eat()
elif self.house.money <= 50:
self.work()
elif dice == 1:
self.work()
elif dice == 2:
self.eat()
elif dice == 3:
self.gaming()
elif ... | класс муж | Husband | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Husband:
"""класс муж"""
def act(self):
"""метод активности человека"""
<|body_0|>
def work(self):
"""метод работа"""
<|body_1|>
def gaming(self):
"""метод отдых"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
dice = randint... | stack_v2_sparse_classes_75kplus_train_066872 | 19,016 | no_license | [
{
"docstring": "метод активности человека",
"name": "act",
"signature": "def act(self)"
},
{
"docstring": "метод работа",
"name": "work",
"signature": "def work(self)"
},
{
"docstring": "метод отдых",
"name": "gaming",
"signature": "def gaming(self)"
}
] | 3 | stack_v2_sparse_classes_30k_val_002076 | Implement the Python class `Husband` described below.
Class description:
класс муж
Method signatures and docstrings:
- def act(self): метод активности человека
- def work(self): метод работа
- def gaming(self): метод отдых | Implement the Python class `Husband` described below.
Class description:
класс муж
Method signatures and docstrings:
- def act(self): метод активности человека
- def work(self): метод работа
- def gaming(self): метод отдых
<|skeleton|>
class Husband:
"""класс муж"""
def act(self):
"""метод активност... | dd9edc250511941163034d9368a54db69b986fb0 | <|skeleton|>
class Husband:
"""класс муж"""
def act(self):
"""метод активности человека"""
<|body_0|>
def work(self):
"""метод работа"""
<|body_1|>
def gaming(self):
"""метод отдых"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Husband:
"""класс муж"""
def act(self):
"""метод активности человека"""
dice = randint(1, 6)
if self.fullness <= 20:
self.eat()
elif self.house.money <= 50:
self.work()
elif dice == 1:
self.work()
elif dice == 2:
... | the_stack_v2_python_sparse | lesson_008/01_family.py | Fusy123/python_base | train | 0 |
1c0295519a9db791317d2e0352c3cd228a78e49e | [
"if not nums:\n return ''\nif len(nums) == 1:\n return str(nums[0])\nres = []\nwhile nums:\n for i in range(len(nums) - 1):\n if not self.larger(str(nums[i]), str(nums[i + 1])):\n nums[i], nums[i + 1] = (nums[i + 1], nums[i])\n res.insert(0, str(nums[-1]))\n nums = nums[:-1]\nif res... | <|body_start_0|>
if not nums:
return ''
if len(nums) == 1:
return str(nums[0])
res = []
while nums:
for i in range(len(nums) - 1):
if not self.larger(str(nums[i]), str(nums[i + 1])):
nums[i], nums[i + 1] = (nums[i + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestNumber(self, nums):
""":type nums: List[int] :rtype: str"""
<|body_0|>
def larger(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return ''
... | stack_v2_sparse_classes_75kplus_train_066873 | 912 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: str",
"name": "largestNumber",
"signature": "def largestNumber(self, nums)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "larger",
"signature": "def larger(self, s1, s2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestNumber(self, nums): :type nums: List[int] :rtype: str
- def larger(self, s1, s2): :type s1: str :type s2: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestNumber(self, nums): :type nums: List[int] :rtype: str
- def larger(self, s1, s2): :type s1: str :type s2: str :rtype: bool
<|skeleton|>
class Solution:
def large... | 0584b86642dff667f5bf6b7acfbbce86a41a55b6 | <|skeleton|>
class Solution:
def largestNumber(self, nums):
""":type nums: List[int] :rtype: str"""
<|body_0|>
def larger(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def largestNumber(self, nums):
""":type nums: List[int] :rtype: str"""
if not nums:
return ''
if len(nums) == 1:
return str(nums[0])
res = []
while nums:
for i in range(len(nums) - 1):
if not self.larger(str(... | the_stack_v2_python_sparse | python_solution/171_180/LargestNumber.py | CescWang1991/LeetCode-Python | train | 1 | |
c10d8c23f1b8fdccbe58601c8cff369a262b069a | [
"pb_obj = ObjectInfo()\npb_obj.Clear()\npb_obj.ParseFromString(msg.value)\nreturn MessageToDict(pb_obj, including_default_value_fields=True, preserving_proto_field_name=True)",
"try:\n while True:\n msg = next(consumer_obj, None)\n if not msg:\n continue\n content = self.deseria... | <|body_start_0|>
pb_obj = ObjectInfo()
pb_obj.Clear()
pb_obj.ParseFromString(msg.value)
return MessageToDict(pb_obj, including_default_value_fields=True, preserving_proto_field_name=True)
<|end_body_0|>
<|body_start_1|>
try:
while True:
msg = next(con... | ReadKafkaContent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadKafkaContent:
def deserialize(msg):
"""反序列化 :param msg: :return:"""
<|body_0|>
def consume_msg(self, consumer_obj):
"""逐条消费,返回反序列化后的内容 :param consumer_obj: :return:"""
<|body_1|>
def entry(self, topic, ip, count=10, log='log_read_kafka_content.json')... | stack_v2_sparse_classes_75kplus_train_066874 | 2,556 | no_license | [
{
"docstring": "反序列化 :param msg: :return:",
"name": "deserialize",
"signature": "def deserialize(msg)"
},
{
"docstring": "逐条消费,返回反序列化后的内容 :param consumer_obj: :return:",
"name": "consume_msg",
"signature": "def consume_msg(self, consumer_obj)"
},
{
"docstring": ":param topic:topi... | 3 | stack_v2_sparse_classes_30k_train_050326 | Implement the Python class `ReadKafkaContent` described below.
Class description:
Implement the ReadKafkaContent class.
Method signatures and docstrings:
- def deserialize(msg): 反序列化 :param msg: :return:
- def consume_msg(self, consumer_obj): 逐条消费,返回反序列化后的内容 :param consumer_obj: :return:
- def entry(self, topic, ip, ... | Implement the Python class `ReadKafkaContent` described below.
Class description:
Implement the ReadKafkaContent class.
Method signatures and docstrings:
- def deserialize(msg): 反序列化 :param msg: :return:
- def consume_msg(self, consumer_obj): 逐条消费,返回反序列化后的内容 :param consumer_obj: :return:
- def entry(self, topic, ip, ... | 269a9c0e23c084d9d6b784f700643de8e913314e | <|skeleton|>
class ReadKafkaContent:
def deserialize(msg):
"""反序列化 :param msg: :return:"""
<|body_0|>
def consume_msg(self, consumer_obj):
"""逐条消费,返回反序列化后的内容 :param consumer_obj: :return:"""
<|body_1|>
def entry(self, topic, ip, count=10, log='log_read_kafka_content.json')... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReadKafkaContent:
def deserialize(msg):
"""反序列化 :param msg: :return:"""
pb_obj = ObjectInfo()
pb_obj.Clear()
pb_obj.ParseFromString(msg.value)
return MessageToDict(pb_obj, including_default_value_fields=True, preserving_proto_field_name=True)
def consume_msg(self, ... | the_stack_v2_python_sparse | kafka/demo.py | wangrongming/block | train | 0 | |
2cd17d962d642c286680e94048d88eb91718c769 | [
"list_file = []\ndirs = os.listdir(path=ReadSchoolList.path)\nfor dir in dirs:\n list_file.append(dir)\nreturn list_file",
"file_name_list = ReadSchoolList.getFileNameList()\nfile_dict = {}\nfor file in file_name_list:\n file_content_list = []\n for line in open(ReadSchoolList.path + '\\\\' + file):\n ... | <|body_start_0|>
list_file = []
dirs = os.listdir(path=ReadSchoolList.path)
for dir in dirs:
list_file.append(dir)
return list_file
<|end_body_0|>
<|body_start_1|>
file_name_list = ReadSchoolList.getFileNameList()
file_dict = {}
for file in file_name_... | ReadSchoolList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadSchoolList:
def getFileNameList(cls):
""":return:文件名列表"""
<|body_0|>
def getFileAllData(cls):
""":return:{'学校_学院名1':[url1,url2...],'学校_学院名2':[url1,url2...]}"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
list_file = []
dirs = os.listdir... | stack_v2_sparse_classes_75kplus_train_066875 | 1,216 | no_license | [
{
"docstring": ":return:文件名列表",
"name": "getFileNameList",
"signature": "def getFileNameList(cls)"
},
{
"docstring": ":return:{'学校_学院名1':[url1,url2...],'学校_学院名2':[url1,url2...]}",
"name": "getFileAllData",
"signature": "def getFileAllData(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023736 | Implement the Python class `ReadSchoolList` described below.
Class description:
Implement the ReadSchoolList class.
Method signatures and docstrings:
- def getFileNameList(cls): :return:文件名列表
- def getFileAllData(cls): :return:{'学校_学院名1':[url1,url2...],'学校_学院名2':[url1,url2...]} | Implement the Python class `ReadSchoolList` described below.
Class description:
Implement the ReadSchoolList class.
Method signatures and docstrings:
- def getFileNameList(cls): :return:文件名列表
- def getFileAllData(cls): :return:{'学校_学院名1':[url1,url2...],'学校_学院名2':[url1,url2...]}
<|skeleton|>
class ReadSchoolList:
... | 550beaf7063b2b14d996fbf9fc03aa678b5d4cbb | <|skeleton|>
class ReadSchoolList:
def getFileNameList(cls):
""":return:文件名列表"""
<|body_0|>
def getFileAllData(cls):
""":return:{'学校_学院名1':[url1,url2...],'学校_学院名2':[url1,url2...]}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReadSchoolList:
def getFileNameList(cls):
""":return:文件名列表"""
list_file = []
dirs = os.listdir(path=ReadSchoolList.path)
for dir in dirs:
list_file.append(dir)
return list_file
def getFileAllData(cls):
""":return:{'学校_学院名1':[url1,url2...],'学校_学院... | the_stack_v2_python_sparse | TeachSpider/TeachSpider/tools/ReadSchoolList.py | darkhorsecmd/Teach_intelligence | train | 1 | |
7f0b936f620be94e04564f0ad3abbe602dfae87b | [
"super(BahdanauAttention, self).__init__()\nself._hidden_size = hidden_size\nself._dense_query = tf.keras.layers.Dense(self._hidden_size, use_bias=False, kernel_initializer='glorot_uniform')\nself._dense_memory = tf.keras.layers.Dense(self._hidden_size, use_bias=False, kernel_initializer='glorot_uniform')\nself._de... | <|body_start_0|>
super(BahdanauAttention, self).__init__()
self._hidden_size = hidden_size
self._dense_query = tf.keras.layers.Dense(self._hidden_size, use_bias=False, kernel_initializer='glorot_uniform')
self._dense_memory = tf.keras.layers.Dense(self._hidden_size, use_bias=False, kerne... | Bahdanau-style additive attention mechanism. | BahdanauAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BahdanauAttention:
"""Bahdanau-style additive attention mechanism."""
def __init__(self, hidden_size):
"""Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation."""
<|body_0|>
def call(self, query, encoder_outputs, padding_mask):
... | stack_v2_sparse_classes_75kplus_train_066876 | 20,679 | no_license | [
{
"docstring": "Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation.",
"name": "__init__",
"signature": "def __init__(self, hidden_size)"
},
{
"docstring": "Computes the outputs of Bahdanau-style attention mechanism. Args: query: float tensor of shape [batch_... | 2 | stack_v2_sparse_classes_30k_train_012393 | Implement the Python class `BahdanauAttention` described below.
Class description:
Bahdanau-style additive attention mechanism.
Method signatures and docstrings:
- def __init__(self, hidden_size): Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation.
- def call(self, query, encoder... | Implement the Python class `BahdanauAttention` described below.
Class description:
Bahdanau-style additive attention mechanism.
Method signatures and docstrings:
- def __init__(self, hidden_size): Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation.
- def call(self, query, encoder... | 63cd17dd38234d47d5d992930d8136e2c30f5de7 | <|skeleton|>
class BahdanauAttention:
"""Bahdanau-style additive attention mechanism."""
def __init__(self, hidden_size):
"""Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation."""
<|body_0|>
def call(self, query, encoder_outputs, padding_mask):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BahdanauAttention:
"""Bahdanau-style additive attention mechanism."""
def __init__(self, hidden_size):
"""Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation."""
super(BahdanauAttention, self).__init__()
self._hidden_size = hidden_size
... | the_stack_v2_python_sparse | model.py | chao-ji/tf-seq2seq | train | 3 |
4562e226437382e36b300ad8fc1885b738f0de67 | [
"super().__init__(x_ref=x_ref, p_val=p_val, x_ref_preprocessed=x_ref_preprocessed, preprocess_at_init=preprocess_at_init, update_x_ref=update_x_ref, preprocess_fn=preprocess_fn, sigma=sigma, configure_kernel_from_x_ref=configure_kernel_from_x_ref, n_permutations=n_permutations, input_shape=input_shape, data_type=da... | <|body_start_0|>
super().__init__(x_ref=x_ref, p_val=p_val, x_ref_preprocessed=x_ref_preprocessed, preprocess_at_init=preprocess_at_init, update_x_ref=update_x_ref, preprocess_fn=preprocess_fn, sigma=sigma, configure_kernel_from_x_ref=configure_kernel_from_x_ref, n_permutations=n_permutations, input_shape=input... | MMDDriftKeops | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMDDriftKeops:
def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=None, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None,... | stack_v2_sparse_classes_75kplus_train_066877 | 8,750 | permissive | [
{
"docstring": "Maximum Mean Discrepancy (MMD) data drift detector using a permutation test. Parameters ---------- x_ref Data used as reference distribution. p_val p-value used for the significance of the permutation test. x_ref_preprocessed Whether the given reference data `x_ref` has been preprocessed yet. If... | 3 | stack_v2_sparse_classes_30k_train_035877 | Implement the Python class `MMDDriftKeops` described below.
Class description:
Implement the MMDDriftKeops class.
Method signatures and docstrings:
- def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, in... | Implement the Python class `MMDDriftKeops` described below.
Class description:
Implement the MMDDriftKeops class.
Method signatures and docstrings:
- def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, in... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class MMDDriftKeops:
def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=None, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MMDDriftKeops:
def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=None, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None, configure_ker... | the_stack_v2_python_sparse | alibi_detect/cd/keops/mmd.py | SeldonIO/alibi-detect | train | 1,922 | |
93ce6aa9c4d8839a4ea14d094083966e4f8808cd | [
"self.timeout = timeout\nself.calibrate_time = None\nself.lock = threading.Lock()\nself.disabled = False\nself.delayed_call = None\nself.service_name = '<unknown>'\nself.func = func",
"kwargs = kwargs.copy()\ntry:\n kwargs.pop(EXPOSED_SERVICE_NAME_KWARG)\nexcept KeyError:\n pass\nreturn self.func(*args, **k... | <|body_start_0|>
self.timeout = timeout
self.calibrate_time = None
self.lock = threading.Lock()
self.disabled = False
self.delayed_call = None
self.service_name = '<unknown>'
self.func = func
<|end_body_0|>
<|body_start_1|>
kwargs = kwargs.copy()
... | Implementation of a single cron job | Job | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Job:
"""Implementation of a single cron job"""
def __init__(self, func, timeout):
"""Initialize a new job @param func: Function to execute @type func: callable @param timeout: Timeout (in seconds) between job invocations @type timeout: number"""
<|body_0|>
def __call__(s... | stack_v2_sparse_classes_75kplus_train_066878 | 9,635 | no_license | [
{
"docstring": "Initialize a new job @param func: Function to execute @type func: callable @param timeout: Timeout (in seconds) between job invocations @type timeout: number",
"name": "__init__",
"signature": "def __init__(self, func, timeout)"
},
{
"docstring": "Execute the job function",
"... | 5 | null | Implement the Python class `Job` described below.
Class description:
Implementation of a single cron job
Method signatures and docstrings:
- def __init__(self, func, timeout): Initialize a new job @param func: Function to execute @type func: callable @param timeout: Timeout (in seconds) between job invocations @type ... | Implement the Python class `Job` described below.
Class description:
Implementation of a single cron job
Method signatures and docstrings:
- def __init__(self, func, timeout): Initialize a new job @param func: Function to execute @type func: callable @param timeout: Timeout (in seconds) between job invocations @type ... | 53d349fa6bee0ccead29afd6676979b44c109a61 | <|skeleton|>
class Job:
"""Implementation of a single cron job"""
def __init__(self, func, timeout):
"""Initialize a new job @param func: Function to execute @type func: callable @param timeout: Timeout (in seconds) between job invocations @type timeout: number"""
<|body_0|>
def __call__(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Job:
"""Implementation of a single cron job"""
def __init__(self, func, timeout):
"""Initialize a new job @param func: Function to execute @type func: callable @param timeout: Timeout (in seconds) between job invocations @type timeout: number"""
self.timeout = timeout
self.calibra... | the_stack_v2_python_sparse | apps/applicationserver/lib/applicationserver/cron.py | racktivity/ext-pylabs-core | train | 0 |
40a3000aab3196e620001c8f3fbef456270afc35 | [
"for i in range(len(nums) - 1):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]",
"d = dict()\nfor i in range(len(nums)):\n if target - nums[i] in d:\n return [d[target - nums[i]], i]\n d[nums[i]] = i"
] | <|body_start_0|>
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
d = dict()
for i in range(len(nums)):
if target - nums[i] in d:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_v1(self, nums: List[int], target: int) -> List[int]:
"""两重循环 时间复杂度为O(n^2),空间复杂度O(1) :param nums: :param target: :return:"""
<|body_0|>
def twoSum_v2(self, nums: List[int], target: int) -> List[int]:
"""利用哈希表,一次遍历 这里把检测差值是否在字典中与把当前值添加到字典在同一个循环里实现,... | stack_v2_sparse_classes_75kplus_train_066879 | 1,874 | no_license | [
{
"docstring": "两重循环 时间复杂度为O(n^2),空间复杂度O(1) :param nums: :param target: :return:",
"name": "twoSum_v1",
"signature": "def twoSum_v1(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "利用哈希表,一次遍历 这里把检测差值是否在字典中与把当前值添加到字典在同一个循环里实现,天然地避免了对同一元素重复考虑的问题。对于数组中的重复元素来说,若重复元素是要寻找的元素,则会返回,否... | 2 | stack_v2_sparse_classes_30k_train_003018 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_v1(self, nums: List[int], target: int) -> List[int]: 两重循环 时间复杂度为O(n^2),空间复杂度O(1) :param nums: :param target: :return:
- def twoSum_v2(self, nums: List[int], target: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_v1(self, nums: List[int], target: int) -> List[int]: 两重循环 时间复杂度为O(n^2),空间复杂度O(1) :param nums: :param target: :return:
- def twoSum_v2(self, nums: List[int], target: in... | 7bf9b992acb5c3db22b52f1ee70816296a41af9d | <|skeleton|>
class Solution:
def twoSum_v1(self, nums: List[int], target: int) -> List[int]:
"""两重循环 时间复杂度为O(n^2),空间复杂度O(1) :param nums: :param target: :return:"""
<|body_0|>
def twoSum_v2(self, nums: List[int], target: int) -> List[int]:
"""利用哈希表,一次遍历 这里把检测差值是否在字典中与把当前值添加到字典在同一个循环里实现,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum_v1(self, nums: List[int], target: int) -> List[int]:
"""两重循环 时间复杂度为O(n^2),空间复杂度O(1) :param nums: :param target: :return:"""
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
retu... | the_stack_v2_python_sparse | 001twoSum.py | slsefe/leetcode | train | 0 | |
0225f5e89c20dc4872df58ce19f9c154f6262dd4 | [
"super(StyleGan2Generator, self).__init__(**kwargs)\nself.resolution = resolution\nif weights is not None:\n self.__adjust_resolution(weights)\nself.mapping_network = MappingNetwork(resolution=self.resolution, name='Mapping_network')\nself.synthesis_network = SynthesisNetwork(resolution=self.resolution, impl=imp... | <|body_start_0|>
super(StyleGan2Generator, self).__init__(**kwargs)
self.resolution = resolution
if weights is not None:
self.__adjust_resolution(weights)
self.mapping_network = MappingNetwork(resolution=self.resolution, name='Mapping_network')
self.synthesis_network ... | StyleGan2 generator config f for tensorflow 2.x | StyleGan2Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleGan2Generator:
"""StyleGan2 generator config f for tensorflow 2.x"""
def __init__(self, resolution=1024, weights=None, impl='cuda', gpu=True, **kwargs):
"""Parameters ---------- resolution : int, optional Resolution output of the synthesis network, will be parsed to the floor in... | stack_v2_sparse_classes_75kplus_train_066880 | 8,137 | no_license | [
{
"docstring": "Parameters ---------- resolution : int, optional Resolution output of the synthesis network, will be parsed to the floor integer power of 2. The default is 1024. weights : string, optional weights name in weights dir to be loaded. The default is None. impl : str, optional Wether to run some conv... | 4 | stack_v2_sparse_classes_30k_train_029482 | Implement the Python class `StyleGan2Generator` described below.
Class description:
StyleGan2 generator config f for tensorflow 2.x
Method signatures and docstrings:
- def __init__(self, resolution=1024, weights=None, impl='cuda', gpu=True, **kwargs): Parameters ---------- resolution : int, optional Resolution output... | Implement the Python class `StyleGan2Generator` described below.
Class description:
StyleGan2 generator config f for tensorflow 2.x
Method signatures and docstrings:
- def __init__(self, resolution=1024, weights=None, impl='cuda', gpu=True, **kwargs): Parameters ---------- resolution : int, optional Resolution output... | 3034e6f6ffc39b58446e384556c351a74593d972 | <|skeleton|>
class StyleGan2Generator:
"""StyleGan2 generator config f for tensorflow 2.x"""
def __init__(self, resolution=1024, weights=None, impl='cuda', gpu=True, **kwargs):
"""Parameters ---------- resolution : int, optional Resolution output of the synthesis network, will be parsed to the floor in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StyleGan2Generator:
"""StyleGan2 generator config f for tensorflow 2.x"""
def __init__(self, resolution=1024, weights=None, impl='cuda', gpu=True, **kwargs):
"""Parameters ---------- resolution : int, optional Resolution output of the synthesis network, will be parsed to the floor integer power o... | the_stack_v2_python_sparse | stylegan2_generator.py | patrickxia/StyleGAN2-TensorFlow-2.x | train | 8 |
9a873bd48f0ccc9b549fbc76976d7996f78a1f4b | [
"def mergeIslands(i, j):\n if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and (grid[i][j] == '1'):\n grid[i][j] = '0'\n map(mergeIslands, (i + 1, i - 1, i, i), (j, j, j + 1, j - 1))\n return 1\n return 0\nreturn sum((mergeIslands(i, j) for i in range(len(grid)) for j in range(len(grid[0]... | <|body_start_0|>
def mergeIslands(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and (grid[i][j] == '1'):
grid[i][j] = '0'
map(mergeIslands, (i + 1, i - 1, i, i), (j, j, j + 1, j - 1))
return 1
return 0
return sum((mergeIsla... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands2(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def mergeIslands(i, j):
... | stack_v2_sparse_classes_75kplus_train_066881 | 2,269 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands2",
"signature": "def numIslands2(self, grid)"
},
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands2(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands2(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
def ... | 45e6ba66104bb43efcce39adc92a4904f50c605d | <|skeleton|>
class Solution:
def numIslands2(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numIslands2(self, grid):
""":type grid: List[List[str]] :rtype: int"""
def mergeIslands(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and (grid[i][j] == '1'):
grid[i][j] = '0'
map(mergeIslands, (i + 1, i - 1, i, i), (j, j, j + ... | the_stack_v2_python_sparse | LeetCode/pythonSols/UnionFind/numOfIslands1.py | abhitrip/scratchpad | train | 0 | |
1ce3d438b605e52593293b222b405f2f337b4f2c | [
"self._provider = provider\nself._mutations = mutations\nself.df_group = ud.makeMutationGroupDF(self._provider.df_X, self._provider.df_y, self._mutations)\nself.df_stat = self.makeGroupStatisticDF()\nself.sl_min = SignificanceLevel()\nself.sl_max = SignificanceLevel()\nself._initSignificanceLevels()",
"df_result ... | <|body_start_0|>
self._provider = provider
self._mutations = mutations
self.df_group = ud.makeMutationGroupDF(self._provider.df_X, self._provider.df_y, self._mutations)
self.df_stat = self.makeGroupStatisticDF()
self.sl_min = SignificanceLevel()
self.sl_max = Significance... | GroupSignificanceLevel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupSignificanceLevel:
def __init__(self, provider, mutations):
""":param ModelDataProvider provider: data source :param list-str mutations: subset of mutations know to provider"""
<|body_0|>
def makeGroupStatisticDF(self, group_column=cn.GROUP, value_column=cn.DEPVAR):
... | stack_v2_sparse_classes_75kplus_train_066882 | 7,153 | permissive | [
{
"docstring": ":param ModelDataProvider provider: data source :param list-str mutations: subset of mutations know to provider",
"name": "__init__",
"signature": "def __init__(self, provider, mutations)"
},
{
"docstring": ":param str group_column: column with the grouping data :param str value_c... | 6 | null | Implement the Python class `GroupSignificanceLevel` described below.
Class description:
Implement the GroupSignificanceLevel class.
Method signatures and docstrings:
- def __init__(self, provider, mutations): :param ModelDataProvider provider: data source :param list-str mutations: subset of mutations know to provide... | Implement the Python class `GroupSignificanceLevel` described below.
Class description:
Implement the GroupSignificanceLevel class.
Method signatures and docstrings:
- def __init__(self, provider, mutations): :param ModelDataProvider provider: data source :param list-str mutations: subset of mutations know to provide... | 704435e66c58677bab24f27820458870092924e2 | <|skeleton|>
class GroupSignificanceLevel:
def __init__(self, provider, mutations):
""":param ModelDataProvider provider: data source :param list-str mutations: subset of mutations know to provider"""
<|body_0|>
def makeGroupStatisticDF(self, group_column=cn.GROUP, value_column=cn.DEPVAR):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupSignificanceLevel:
def __init__(self, provider, mutations):
""":param ModelDataProvider provider: data source :param list-str mutations: subset of mutations know to provider"""
self._provider = provider
self._mutations = mutations
self.df_group = ud.makeMutationGroupDF(sel... | the_stack_v2_python_sparse | microbepy/statistics/group_significance_level.py | ScienceStacks/microbepy | train | 1 | |
111768a0f512b5f23af9368daf0c3aa7525df830 | [
"self.ha_version: AwesomeVersion = ha_version\nself.client: aiohttp.ClientWebSocketResponse = client\nself.message_id: int = 0\nself._lock: asyncio.Lock = asyncio.Lock()",
"async with self._lock:\n self.message_id += 1\n message['id'] = self.message_id\n _LOGGER.debug('Sending: %s', message)\n try:\n ... | <|body_start_0|>
self.ha_version: AwesomeVersion = ha_version
self.client: aiohttp.ClientWebSocketResponse = client
self.message_id: int = 0
self._lock: asyncio.Lock = asyncio.Lock()
<|end_body_0|>
<|body_start_1|>
async with self._lock:
self.message_id += 1
... | Home Assistant Websocket client. | WSClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WSClient:
"""Home Assistant Websocket client."""
def __init__(self, ha_version: AwesomeVersion, client: aiohttp.ClientWebSocketResponse):
"""Initialise the WS client."""
<|body_0|>
async def async_send_command(self, message: Dict[str, Any]):
"""Send a websocket c... | stack_v2_sparse_classes_75kplus_train_066883 | 5,664 | permissive | [
{
"docstring": "Initialise the WS client.",
"name": "__init__",
"signature": "def __init__(self, ha_version: AwesomeVersion, client: aiohttp.ClientWebSocketResponse)"
},
{
"docstring": "Send a websocket command.",
"name": "async_send_command",
"signature": "async def async_send_command(s... | 3 | null | Implement the Python class `WSClient` described below.
Class description:
Home Assistant Websocket client.
Method signatures and docstrings:
- def __init__(self, ha_version: AwesomeVersion, client: aiohttp.ClientWebSocketResponse): Initialise the WS client.
- async def async_send_command(self, message: Dict[str, Any]... | Implement the Python class `WSClient` described below.
Class description:
Home Assistant Websocket client.
Method signatures and docstrings:
- def __init__(self, ha_version: AwesomeVersion, client: aiohttp.ClientWebSocketResponse): Initialise the WS client.
- async def async_send_command(self, message: Dict[str, Any]... | fa7140fd9a5ee1316d103628f1f7f4c6db05b158 | <|skeleton|>
class WSClient:
"""Home Assistant Websocket client."""
def __init__(self, ha_version: AwesomeVersion, client: aiohttp.ClientWebSocketResponse):
"""Initialise the WS client."""
<|body_0|>
async def async_send_command(self, message: Dict[str, Any]):
"""Send a websocket c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WSClient:
"""Home Assistant Websocket client."""
def __init__(self, ha_version: AwesomeVersion, client: aiohttp.ClientWebSocketResponse):
"""Initialise the WS client."""
self.ha_version: AwesomeVersion = ha_version
self.client: aiohttp.ClientWebSocketResponse = client
self... | the_stack_v2_python_sparse | supervisor/homeassistant/websocket.py | BigElkHunter/cyberockit | train | 1 |
aca1ca176e186147cd154092535529a837d984a3 | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.stride = stride",
"for p in self.parameters():\n p.requires_grad = False\nFrozenBatchNorm2d.convert_frozen_batchnorm(self)\nreturn self"
] | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.stride = stride
<|end_body_0|>
<|body_start_1|>
for p in self.parameters():
p.requires_grad = False
FrozenBatchNorm2d.convert_frozen_batchnorm(self)
... | A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out_channels (int): stride (int): | CNNBlockBase | [
"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 CNNBlockBase:
"""A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out... | stack_v2_sparse_classes_75kplus_train_066884 | 4,708 | permissive | [
{
"docstring": "The `__init__` method of any subclass should also contain these arguments. Args: in_channels (int): out_channels (int): stride (int):",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, stride)"
},
{
"docstring": "Make this block not trainable. This ... | 2 | stack_v2_sparse_classes_30k_train_010831 | Implement the Python class `CNNBlockBase` described below.
Class description:
A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specifica... | Implement the Python class `CNNBlockBase` described below.
Class description:
A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specifica... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class CNNBlockBase:
"""A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNNBlockBase:
"""A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out_channels (in... | the_stack_v2_python_sparse | PyTorch/dev/cv/image_classification/SlowFast_ID0646_for_PyTorch/detectron2/detectron2/layers/blocks.py | Ascend/ModelZoo-PyTorch | train | 23 |
624a0723b90324fdc737f34bb8ec9d0fe32a5e20 | [
"v = utils.splitpath_root_file_ext('F:\\\\foo\\\\bar.py')\nself.assertEqual(v, ('F:\\\\foo', 'bar', '.py'))\nv = utils.splitpath_root_file_ext('J:\\\\spam.py')\nself.assertEqual(v, ('J:\\\\', 'spam', '.py'))",
"v = utils.splitpath_root_file_ext('C:\\\\foo\\\\bar')\nself.assertEqual(v, ('C:\\\\foo', 'bar', ''))\nv... | <|body_start_0|>
v = utils.splitpath_root_file_ext('F:\\foo\\bar.py')
self.assertEqual(v, ('F:\\foo', 'bar', '.py'))
v = utils.splitpath_root_file_ext('J:\\spam.py')
self.assertEqual(v, ('J:\\', 'spam', '.py'))
<|end_body_0|>
<|body_start_1|>
v = utils.splitpath_root_file_ext('C... | TestSplitRootFileExt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSplitRootFileExt:
def testRegularPath(self):
"""Test the method's behavior on regular paths."""
<|body_0|>
def testDirOnly(self):
"""Test behavior when passed a path only."""
<|body_1|>
def testFileOnly(self):
"""Test behavior when passed a f... | stack_v2_sparse_classes_75kplus_train_066885 | 2,610 | permissive | [
{
"docstring": "Test the method's behavior on regular paths.",
"name": "testRegularPath",
"signature": "def testRegularPath(self)"
},
{
"docstring": "Test behavior when passed a path only.",
"name": "testDirOnly",
"signature": "def testDirOnly(self)"
},
{
"docstring": "Test behav... | 3 | stack_v2_sparse_classes_30k_train_015286 | Implement the Python class `TestSplitRootFileExt` described below.
Class description:
Implement the TestSplitRootFileExt class.
Method signatures and docstrings:
- def testRegularPath(self): Test the method's behavior on regular paths.
- def testDirOnly(self): Test behavior when passed a path only.
- def testFileOnly... | Implement the Python class `TestSplitRootFileExt` described below.
Class description:
Implement the TestSplitRootFileExt class.
Method signatures and docstrings:
- def testRegularPath(self): Test the method's behavior on regular paths.
- def testDirOnly(self): Test behavior when passed a path only.
- def testFileOnly... | 679397c86992fe434e3aabff7edf4f6867424bc9 | <|skeleton|>
class TestSplitRootFileExt:
def testRegularPath(self):
"""Test the method's behavior on regular paths."""
<|body_0|>
def testDirOnly(self):
"""Test behavior when passed a path only."""
<|body_1|>
def testFileOnly(self):
"""Test behavior when passed a f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSplitRootFileExt:
def testRegularPath(self):
"""Test the method's behavior on regular paths."""
v = utils.splitpath_root_file_ext('F:\\foo\\bar.py')
self.assertEqual(v, ('F:\\foo', 'bar', '.py'))
v = utils.splitpath_root_file_ext('J:\\spam.py')
self.assertEqual(v, (... | the_stack_v2_python_sparse | pynocle-0.3.2/build/lib.linux-x86_64-2.7/pynocle/test_utils.py | 1147279/SoftwareProject | train | 0 | |
ebb252b6fdf4d91cd4ac6fb6819089a68f0a6559 | [
"if not A:\n return 0\nn = len(A)\nrange_sum, score, cut = self.init_helper_arrays(A)\nfor delta in xrange(2, n):\n for i in xrange(n - delta):\n j = i + delta\n score[i][j] = sys.maxsize\n for mid in xrange(cut[i][j - 1], cut[i + 1][j] + 1):\n cur_score = score[i][mid] + score... | <|body_start_0|>
if not A:
return 0
n = len(A)
range_sum, score, cut = self.init_helper_arrays(A)
for delta in xrange(2, n):
for i in xrange(n - delta):
j = i + delta
score[i][j] = sys.maxsize
for mid in xrange(cut[i... | 四边形不等式证明:https://blog.csdn.net/NOIAu/article/details/72514812 原答案来自https://www.jiuzhang.com/solution/stone-game/#tag-highlight-lang-python Time: O(N^2) 四边形不等式cut[i][j - 1] <= cut[i][j] <= cut[i + 1][j] todo: 还需要深入理解能够适用四边形不等式的条件 | StoneGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoneGame:
"""四边形不等式证明:https://blog.csdn.net/NOIAu/article/details/72514812 原答案来自https://www.jiuzhang.com/solution/stone-game/#tag-highlight-lang-python Time: O(N^2) 四边形不等式cut[i][j - 1] <= cut[i][j] <= cut[i + 1][j] todo: 还需要深入理解能够适用四边形不等式的条件"""
def stone_game(self, A):
""":type A: L... | stack_v2_sparse_classes_75kplus_train_066886 | 4,876 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "stone_game",
"signature": "def stone_game(self, A)"
},
{
"docstring": ":param A: List[int]: the input numbers of stone game :return: List[List[int]], List[List[int]], List[List[int]]: range_sum[i][j] = sum(A[i:j+1] score[i][j] = min score... | 3 | stack_v2_sparse_classes_30k_train_015728 | Implement the Python class `StoneGame` described below.
Class description:
四边形不等式证明:https://blog.csdn.net/NOIAu/article/details/72514812 原答案来自https://www.jiuzhang.com/solution/stone-game/#tag-highlight-lang-python Time: O(N^2) 四边形不等式cut[i][j - 1] <= cut[i][j] <= cut[i + 1][j] todo: 还需要深入理解能够适用四边形不等式的条件
Method signatu... | Implement the Python class `StoneGame` described below.
Class description:
四边形不等式证明:https://blog.csdn.net/NOIAu/article/details/72514812 原答案来自https://www.jiuzhang.com/solution/stone-game/#tag-highlight-lang-python Time: O(N^2) 四边形不等式cut[i][j - 1] <= cut[i][j] <= cut[i + 1][j] todo: 还需要深入理解能够适用四边形不等式的条件
Method signatu... | ea10ce7fe465431399e444c6ecb0b7560b17e1e4 | <|skeleton|>
class StoneGame:
"""四边形不等式证明:https://blog.csdn.net/NOIAu/article/details/72514812 原答案来自https://www.jiuzhang.com/solution/stone-game/#tag-highlight-lang-python Time: O(N^2) 四边形不等式cut[i][j - 1] <= cut[i][j] <= cut[i + 1][j] todo: 还需要深入理解能够适用四边形不等式的条件"""
def stone_game(self, A):
""":type A: L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoneGame:
"""四边形不等式证明:https://blog.csdn.net/NOIAu/article/details/72514812 原答案来自https://www.jiuzhang.com/solution/stone-game/#tag-highlight-lang-python Time: O(N^2) 四边形不等式cut[i][j - 1] <= cut[i][j] <= cut[i + 1][j] todo: 还需要深入理解能够适用四边形不等式的条件"""
def stone_game(self, A):
""":type A: List[int] :rty... | the_stack_v2_python_sparse | leetcode_python2/li476_stone_game.py | garderobin/Leetcode | train | 0 |
d18cae89cb67880573e19c7f81fcf8a97aae4f7b | [
"lst = []\nfor i in range(len(df)):\n if i < periods:\n lst.append(np.nan)\n else:\n lst.append(round(np.mean(df[i:periods + i]), 2))\nreturn lst",
"k_lst = []\nd_lst = []\nfor i in range(len(closes)):\n if i < periods:\n k_lst.append(np.nan)\n d_lst.append(np.nan)\n else:\... | <|body_start_0|>
lst = []
for i in range(len(df)):
if i < periods:
lst.append(np.nan)
else:
lst.append(round(np.mean(df[i:periods + i]), 2))
return lst
<|end_body_0|>
<|body_start_1|>
k_lst = []
d_lst = []
for i in ... | Indicators | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Indicators:
def SMA(df, periods=50):
"""Calculating the Simple Moving Average for the past n days **Values must be descending**"""
<|body_0|>
def Stoch(closes, lows, highs, periods=14, d_periods=3):
"""Calculating the Stochastic Oscillator for the past n days **Value... | stack_v2_sparse_classes_75kplus_train_066887 | 2,704 | no_license | [
{
"docstring": "Calculating the Simple Moving Average for the past n days **Values must be descending**",
"name": "SMA",
"signature": "def SMA(df, periods=50)"
},
{
"docstring": "Calculating the Stochastic Oscillator for the past n days **Values must be descending**",
"name": "Stoch",
"s... | 3 | null | Implement the Python class `Indicators` described below.
Class description:
Implement the Indicators class.
Method signatures and docstrings:
- def SMA(df, periods=50): Calculating the Simple Moving Average for the past n days **Values must be descending**
- def Stoch(closes, lows, highs, periods=14, d_periods=3): Ca... | Implement the Python class `Indicators` described below.
Class description:
Implement the Indicators class.
Method signatures and docstrings:
- def SMA(df, periods=50): Calculating the Simple Moving Average for the past n days **Values must be descending**
- def Stoch(closes, lows, highs, periods=14, d_periods=3): Ca... | c2a4eb0d753808875c1131bc675a2d6adf5d51d0 | <|skeleton|>
class Indicators:
def SMA(df, periods=50):
"""Calculating the Simple Moving Average for the past n days **Values must be descending**"""
<|body_0|>
def Stoch(closes, lows, highs, periods=14, d_periods=3):
"""Calculating the Stochastic Oscillator for the past n days **Value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Indicators:
def SMA(df, periods=50):
"""Calculating the Simple Moving Average for the past n days **Values must be descending**"""
lst = []
for i in range(len(df)):
if i < periods:
lst.append(np.nan)
else:
lst.append(round(np.mean... | the_stack_v2_python_sparse | indicators.py | rw6869/trading | train | 0 | |
700bd9de354e9003dd116be0ed618626b1a1e6ab | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.incomingCallOptions'.casefold():\n from ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | CallOptions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallOptions:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions:
"""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: Ca... | stack_v2_sparse_classes_75kplus_train_066888 | 3,943 | 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: CallOptions",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | stack_v2_sparse_classes_30k_train_048145 | Implement the Python class `CallOptions` described below.
Class description:
Implement the CallOptions class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions: Creates a new instance of the appropriate class based on discriminator value Args:... | Implement the Python class `CallOptions` described below.
Class description:
Implement the CallOptions class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions: Creates a new instance of the appropriate class based on discriminator value Args:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CallOptions:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions:
"""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: Ca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CallOptions:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions:
"""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: CallOptions"""
... | the_stack_v2_python_sparse | msgraph/generated/models/call_options.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
184e38dc1143827c3c96dec43c1af91bafd06471 | [
"super().__init__()\nself.normalized = normalized\nif normalized:\n scaler = StandardScaler()\n scaler.mean_, scaler.scale_ = np.load(stats_path)\n self.scaler = scaler\nself.ds_config = dataset_config\nself.mel_basis = librosa.filters.mel(self.ds_config['sampling_rate'], n_fft=self.ds_config['fft_size'], ... | <|body_start_0|>
super().__init__()
self.normalized = normalized
if normalized:
scaler = StandardScaler()
scaler.mean_, scaler.scale_ = np.load(stats_path)
self.scaler = scaler
self.ds_config = dataset_config
self.mel_basis = librosa.filters.me... | Griffin-Lim algorithm for phase reconstruction from mel spectrogram magnitude. | TFGriffinLim | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFGriffinLim:
"""Griffin-Lim algorithm for phase reconstruction from mel spectrogram magnitude."""
def __init__(self, stats_path, dataset_config, normalized: bool=True):
"""Init GL params. Args: stats_path (str): path to the `stats.npy` file containing norm statistics. dataset_config... | stack_v2_sparse_classes_75kplus_train_066889 | 6,824 | permissive | [
{
"docstring": "Init GL params. Args: stats_path (str): path to the `stats.npy` file containing norm statistics. dataset_config (Dict): dataset configuration parameters.",
"name": "__init__",
"signature": "def __init__(self, stats_path, dataset_config, normalized: bool=True)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_test_000536 | Implement the Python class `TFGriffinLim` described below.
Class description:
Griffin-Lim algorithm for phase reconstruction from mel spectrogram magnitude.
Method signatures and docstrings:
- def __init__(self, stats_path, dataset_config, normalized: bool=True): Init GL params. Args: stats_path (str): path to the `s... | Implement the Python class `TFGriffinLim` described below.
Class description:
Griffin-Lim algorithm for phase reconstruction from mel spectrogram magnitude.
Method signatures and docstrings:
- def __init__(self, stats_path, dataset_config, normalized: bool=True): Init GL params. Args: stats_path (str): path to the `s... | 136877136355c82d7ba474ceb7a8f133bd84767e | <|skeleton|>
class TFGriffinLim:
"""Griffin-Lim algorithm for phase reconstruction from mel spectrogram magnitude."""
def __init__(self, stats_path, dataset_config, normalized: bool=True):
"""Init GL params. Args: stats_path (str): path to the `stats.npy` file containing norm statistics. dataset_config... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TFGriffinLim:
"""Griffin-Lim algorithm for phase reconstruction from mel spectrogram magnitude."""
def __init__(self, stats_path, dataset_config, normalized: bool=True):
"""Init GL params. Args: stats_path (str): path to the `stats.npy` file containing norm statistics. dataset_config (Dict): data... | the_stack_v2_python_sparse | tensorflow_tts/utils/griffin_lim.py | TensorSpeech/TensorFlowTTS | train | 2,889 |
e28472885a15d1529dfba923bd44e6309c9b4222 | [
"if not model_cfg:\n model_cfg = {}\nsuper(Dummy, self).__init__(**model_cfg)\nself._logger = logging.getLogger(__name__)",
"y_train = np.array(y_train)\ny_test = np.array(y_test)\nself._logger.info(f'Fitting {__name__} classifier to data')\nself.fit(X_train, y_train)\nself._logger.info('Done fitting to data, ... | <|body_start_0|>
if not model_cfg:
model_cfg = {}
super(Dummy, self).__init__(**model_cfg)
self._logger = logging.getLogger(__name__)
<|end_body_0|>
<|body_start_1|>
y_train = np.array(y_train)
y_test = np.array(y_test)
self._logger.info(f'Fitting {__name__} ... | Dummy | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dummy:
def __init__(self, model_cfg: Dict[str, Any]=None) -> None:
"""Initialize class, pass config to parent :param model_cfg: model config :type model_cfg: Dict[str, Any], default None :return: None :rtype: None"""
<|body_0|>
def train_test(self, X_train: 'np.array[np.int6... | stack_v2_sparse_classes_75kplus_train_066890 | 2,234 | permissive | [
{
"docstring": "Initialize class, pass config to parent :param model_cfg: model config :type model_cfg: Dict[str, Any], default None :return: None :rtype: None",
"name": "__init__",
"signature": "def __init__(self, model_cfg: Dict[str, Any]=None) -> None"
},
{
"docstring": "Train a dummy classif... | 2 | null | Implement the Python class `Dummy` described below.
Class description:
Implement the Dummy class.
Method signatures and docstrings:
- def __init__(self, model_cfg: Dict[str, Any]=None) -> None: Initialize class, pass config to parent :param model_cfg: model config :type model_cfg: Dict[str, Any], default None :return... | Implement the Python class `Dummy` described below.
Class description:
Implement the Dummy class.
Method signatures and docstrings:
- def __init__(self, model_cfg: Dict[str, Any]=None) -> None: Initialize class, pass config to parent :param model_cfg: model config :type model_cfg: Dict[str, Any], default None :return... | bd8599228d95ef42b5879370cdcbc03333b4e461 | <|skeleton|>
class Dummy:
def __init__(self, model_cfg: Dict[str, Any]=None) -> None:
"""Initialize class, pass config to parent :param model_cfg: model config :type model_cfg: Dict[str, Any], default None :return: None :rtype: None"""
<|body_0|>
def train_test(self, X_train: 'np.array[np.int6... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dummy:
def __init__(self, model_cfg: Dict[str, Any]=None) -> None:
"""Initialize class, pass config to parent :param model_cfg: model config :type model_cfg: Dict[str, Any], default None :return: None :rtype: None"""
if not model_cfg:
model_cfg = {}
super(Dummy, self).__ini... | the_stack_v2_python_sparse | WP3/Task3.1/src/models/dummy.py | on-merrit/ON-MERRIT | train | 2 | |
afe0d9490691e77ae33bc2729289bbbc67ce7260 | [
"if not root:\n return 'None'\nleft = self.serialize(root.left)\nright = self.serialize(root.right)\nreturn str(root.val) + ',' + left + ',' + right",
"tree_list = data.split(',')\ntree_list = tree_list[::-1]\n\ndef preorder():\n curr_val = tree_list.pop()\n if curr_val == 'None':\n return\n no... | <|body_start_0|>
if not root:
return 'None'
left = self.serialize(root.left)
right = self.serialize(root.right)
return str(root.val) + ',' + left + ',' + right
<|end_body_0|>
<|body_start_1|>
tree_list = data.split(',')
tree_list = tree_list[::-1]
de... | Codec | [] | 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_066891 | 1,363 | no_license | [
{
"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_050082 | 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:... | b6589ede25aa20ee96b20ed65f0cb7459c740034 | <|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"""
if not root:
return 'None'
left = self.serialize(root.left)
right = self.serialize(root.right)
return str(root.val) + ',' + left + ',' + right
de... | the_stack_v2_python_sparse | Serialize_Deserialize_BT.py | akarshn95/Coding_Challenges | train | 0 | |
76da9619135ec92ebc0dfec1d9b5d53a6f8e07d6 | [
"self._front = self._rear = -1\nself._items = Array(ArrayQueue.DEFAULT_CAPACITY)\nAbstractCollection.__init__(self, sourceCollection)",
"cursor = self._front\nif self._front <= self._rear:\n while cursor <= self._rear:\n yield self._items[cursor]\n cursor += 1\nelse:\n while cursor < len(self.... | <|body_start_0|>
self._front = self._rear = -1
self._items = Array(ArrayQueue.DEFAULT_CAPACITY)
AbstractCollection.__init__(self, sourceCollection)
<|end_body_0|>
<|body_start_1|>
cursor = self._front
if self._front <= self._rear:
while cursor <= self._rear:
... | An array-based queue implementation. | ArrayQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayQueue:
"""An array-based queue implementation."""
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection, if it's present."""
<|body_0|>
def __iter__(self):
"""Supports iteration over a v... | stack_v2_sparse_classes_75kplus_train_066892 | 3,324 | no_license | [
{
"docstring": "Sets the initial state of self, which includes the contents of sourceCollection, if it's present.",
"name": "__init__",
"signature": "def __init__(self, sourceCollection=None)"
},
{
"docstring": "Supports iteration over a view of self.",
"name": "__iter__",
"signature": "... | 6 | stack_v2_sparse_classes_30k_test_002968 | Implement the Python class `ArrayQueue` described below.
Class description:
An array-based queue implementation.
Method signatures and docstrings:
- def __init__(self, sourceCollection=None): Sets the initial state of self, which includes the contents of sourceCollection, if it's present.
- def __iter__(self): Suppor... | Implement the Python class `ArrayQueue` described below.
Class description:
An array-based queue implementation.
Method signatures and docstrings:
- def __init__(self, sourceCollection=None): Sets the initial state of self, which includes the contents of sourceCollection, if it's present.
- def __iter__(self): Suppor... | 8e59542d2e46854f452aa62514b8f951df478d77 | <|skeleton|>
class ArrayQueue:
"""An array-based queue implementation."""
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection, if it's present."""
<|body_0|>
def __iter__(self):
"""Supports iteration over a v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArrayQueue:
"""An array-based queue implementation."""
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection, if it's present."""
self._front = self._rear = -1
self._items = Array(ArrayQueue.DEFAULT_CAPACITY)
... | the_stack_v2_python_sparse | arrayqueue.py | staufferl16/Programming112 | train | 0 |
3b6c62298c4b3cffe7bd51811a1d05a66cba2aad | [
"response = self.client.get(reverse('polls:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'No polls are available.')\nself.assertQuerysetEqual(response.context['latest_question_list'], [])",
"create_question('past question.', days=-30)\nresponse = self.client.get(reverse('pol... | <|body_start_0|>
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No polls are available.')
self.assertQuerysetEqual(response.context['latest_question_list'], [])
<|end_body_0|>
<|body_start_1|>
create_... | QuestionIndexViewTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionIndexViewTests:
def test_no_questions(self):
"""if no questions, appropriate error displayed"""
<|body_0|>
def test_past_question(self):
"""questions with past pub_date displayed"""
<|body_1|>
def test_future_question(self):
"""questions ... | stack_v2_sparse_classes_75kplus_train_066893 | 5,466 | permissive | [
{
"docstring": "if no questions, appropriate error displayed",
"name": "test_no_questions",
"signature": "def test_no_questions(self)"
},
{
"docstring": "questions with past pub_date displayed",
"name": "test_past_question",
"signature": "def test_past_question(self)"
},
{
"docst... | 5 | stack_v2_sparse_classes_30k_train_011745 | Implement the Python class `QuestionIndexViewTests` described below.
Class description:
Implement the QuestionIndexViewTests class.
Method signatures and docstrings:
- def test_no_questions(self): if no questions, appropriate error displayed
- def test_past_question(self): questions with past pub_date displayed
- def... | Implement the Python class `QuestionIndexViewTests` described below.
Class description:
Implement the QuestionIndexViewTests class.
Method signatures and docstrings:
- def test_no_questions(self): if no questions, appropriate error displayed
- def test_past_question(self): questions with past pub_date displayed
- def... | 6a9532d03d8a1cac38cc9128336fa17c433fe19c | <|skeleton|>
class QuestionIndexViewTests:
def test_no_questions(self):
"""if no questions, appropriate error displayed"""
<|body_0|>
def test_past_question(self):
"""questions with past pub_date displayed"""
<|body_1|>
def test_future_question(self):
"""questions ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionIndexViewTests:
def test_no_questions(self):
"""if no questions, appropriate error displayed"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No polls are available.')
self.assertQue... | the_stack_v2_python_sparse | python/django_projects/mysite/polls/tests.py | quasarbright/quasarbright.github.io | train | 1 | |
1b25abac5a74b2864a01036f9253f17cc4b70427 | [
"self.user = user\nself.connection = conn\nself.buffer_size = buffer_size\nself.message_encoding = message_encoding\nself.message_decoding = message_decoding\nself.verbose = verbose\nthreading.Thread.__init__(self)",
"while True:\n try:\n data = self.connection.recv(self.buffer_size).decode(self.message... | <|body_start_0|>
self.user = user
self.connection = conn
self.buffer_size = buffer_size
self.message_encoding = message_encoding
self.message_decoding = message_decoding
self.verbose = verbose
threading.Thread.__init__(self)
<|end_body_0|>
<|body_start_1|>
... | This class defines a thread which handles the incoming messages (e.g. chat, lobby/game messages) TODO: Extend range of received and sent message types | MessageHandlingThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageHandlingThread:
"""This class defines a thread which handles the incoming messages (e.g. chat, lobby/game messages) TODO: Extend range of received and sent message types"""
def __init__(self, conn, user, buffer_size, message_encoding, message_decoding, verbose=False):
"""Initi... | stack_v2_sparse_classes_75kplus_train_066894 | 6,370 | no_license | [
{
"docstring": "Initialization of the message handling thread (Use of multiple attributes instead of global variables to enable dynamic tests and expandability (e.g. load balancing, etc.)) :param conn: Socket specifying the TCP connection to the server :param user: String specifying the name of the user :param ... | 2 | stack_v2_sparse_classes_30k_train_049200 | Implement the Python class `MessageHandlingThread` described below.
Class description:
This class defines a thread which handles the incoming messages (e.g. chat, lobby/game messages) TODO: Extend range of received and sent message types
Method signatures and docstrings:
- def __init__(self, conn, user, buffer_size, ... | Implement the Python class `MessageHandlingThread` described below.
Class description:
This class defines a thread which handles the incoming messages (e.g. chat, lobby/game messages) TODO: Extend range of received and sent message types
Method signatures and docstrings:
- def __init__(self, conn, user, buffer_size, ... | c3f8783884fe24b82919f8904e0b7aa5f7f6db88 | <|skeleton|>
class MessageHandlingThread:
"""This class defines a thread which handles the incoming messages (e.g. chat, lobby/game messages) TODO: Extend range of received and sent message types"""
def __init__(self, conn, user, buffer_size, message_encoding, message_decoding, verbose=False):
"""Initi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageHandlingThread:
"""This class defines a thread which handles the incoming messages (e.g. chat, lobby/game messages) TODO: Extend range of received and sent message types"""
def __init__(self, conn, user, buffer_size, message_encoding, message_decoding, verbose=False):
"""Initialization of ... | the_stack_v2_python_sparse | PongLobbyClient.py | A-Sen98/Pingpong | train | 0 |
968026e1a57b999ee74cf8ed4c9dc0a6672036f5 | [
"def preOrderHelper(node, orderarr):\n if not node:\n orderarr.append('#')\n return\n orderarr.append(str(node.val))\n preOrderHelper(node.left, orderarr)\n preOrderHelper(node.right, orderarr)\ndic = {}\nret = []\n\ndef preOrderjudge(root):\n if root:\n orderarr = []\n pr... | <|body_start_0|>
def preOrderHelper(node, orderarr):
if not node:
orderarr.append('#')
return
orderarr.append(str(node.val))
preOrderHelper(node.left, orderarr)
preOrderHelper(node.right, orderarr)
dic = {}
ret = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_0|>
def findDuplicateSubtrees2(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def ... | stack_v2_sparse_classes_75kplus_train_066895 | 2,356 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[TreeNode]",
"name": "findDuplicateSubtrees",
"signature": "def findDuplicateSubtrees(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[TreeNode]",
"name": "findDuplicateSubtrees2",
"signature": "def findDuplicateSubtrees2(... | 2 | stack_v2_sparse_classes_30k_train_022608 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root): :type root: TreeNode :rtype: List[TreeNode]
- def findDuplicateSubtrees2(self, root): :type root: TreeNode :rtype: List[TreeNode] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root): :type root: TreeNode :rtype: List[TreeNode]
- def findDuplicateSubtrees2(self, root): :type root: TreeNode :rtype: List[TreeNode]
<|skelet... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_0|>
def findDuplicateSubtrees2(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
def preOrderHelper(node, orderarr):
if not node:
orderarr.append('#')
return
orderarr.append(str(node.val))
preOrderHelper(node... | the_stack_v2_python_sparse | src/findDuplicateSubtrees.py | jsdiuf/leetcode | train | 1 | |
ea39530987918fa76c39b5a057d092b60079e0e7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TargetResource()",
"from .group_type import GroupType\nfrom .modified_property import ModifiedProperty\nfrom .group_type import GroupType\nfrom .modified_property import ModifiedProperty\nfields: Dict[str, Callable[[Any], None]] = {'di... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TargetResource()
<|end_body_0|>
<|body_start_1|>
from .group_type import GroupType
from .modified_property import ModifiedProperty
from .group_type import GroupType
from ... | TargetResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource:
"""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 Retur... | stack_v2_sparse_classes_75kplus_train_066896 | 4,380 | 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: TargetResource",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_039674 | Implement the Python class `TargetResource` described below.
Class description:
Implement the TargetResource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `TargetResource` described below.
Class description:
Implement the TargetResource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TargetResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource:
"""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 Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TargetResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource:
"""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: TargetReso... | the_stack_v2_python_sparse | msgraph/generated/models/target_resource.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
835d68e243fa3eb7afdc86b033161d4125476212 | [
"AbstractSelection.__init__(self, mutator, crossover, repairer)\nif num_competitors < 2:\n raise ValueError('Must have at least 2 competitors!')\nself._num_competitors = num_competitors",
"new_population = []\nwhile len(new_population) < len(population):\n new_orgs = []\n for round_num in range(2):\n ... | <|body_start_0|>
AbstractSelection.__init__(self, mutator, crossover, repairer)
if num_competitors < 2:
raise ValueError('Must have at least 2 competitors!')
self._num_competitors = num_competitors
<|end_body_0|>
<|body_start_1|>
new_population = []
while len(new_pop... | Implement tournament style selection. | TournamentSelection | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TournamentSelection:
"""Implement tournament style selection."""
def __init__(self, mutator, crossover, repairer, num_competitors=2):
"""Initialize the tournament selector. Arguments: o num_competitors-- The number of individiuals that should be involved in a selection round. By defa... | stack_v2_sparse_classes_75kplus_train_066897 | 2,781 | permissive | [
{
"docstring": "Initialize the tournament selector. Arguments: o num_competitors-- The number of individiuals that should be involved in a selection round. By default we just have two individuals (head to head!). See AbstractSelection for a description of the arguments to the initializer.",
"name": "__init_... | 2 | null | Implement the Python class `TournamentSelection` described below.
Class description:
Implement tournament style selection.
Method signatures and docstrings:
- def __init__(self, mutator, crossover, repairer, num_competitors=2): Initialize the tournament selector. Arguments: o num_competitors-- The number of individiu... | Implement the Python class `TournamentSelection` described below.
Class description:
Implement tournament style selection.
Method signatures and docstrings:
- def __init__(self, mutator, crossover, repairer, num_competitors=2): Initialize the tournament selector. Arguments: o num_competitors-- The number of individiu... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class TournamentSelection:
"""Implement tournament style selection."""
def __init__(self, mutator, crossover, repairer, num_competitors=2):
"""Initialize the tournament selector. Arguments: o num_competitors-- The number of individiuals that should be involved in a selection round. By defa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TournamentSelection:
"""Implement tournament style selection."""
def __init__(self, mutator, crossover, repairer, num_competitors=2):
"""Initialize the tournament selector. Arguments: o num_competitors-- The number of individiuals that should be involved in a selection round. By default we just h... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/GA/Selection/Tournament.py | LyonsLab/coge | train | 41 |
275eaeb2054bf3ba9e780274524c8d24ab4ad084 | [
"log.debug('GET request from user %s for deliverable %s' % (request.user, deliverable_id))\nproj = Project.objects.get(project_number=project_number)\ndeliverable = Deliverable.objects.get(id=deliverable_id)\nif not check_project_read_acl(proj, request.user):\n log.debug('Refusing GET request for project %s from... | <|body_start_0|>
log.debug('GET request from user %s for deliverable %s' % (request.user, deliverable_id))
proj = Project.objects.get(project_number=project_number)
deliverable = Deliverable.objects.get(id=deliverable_id)
if not check_project_read_acl(proj, request.user):
log... | URI: /api/deliverables/%project_number%/%deliverable_id%/ VERBS: GET, PUT, DELETE Handles a single instance of Deliverable | DeliverableResourceHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeliverableResourceHandler:
"""URI: /api/deliverables/%project_number%/%deliverable_id%/ VERBS: GET, PUT, DELETE Handles a single instance of Deliverable"""
def read(self, request, project_number, deliverable_id):
"""View a deliverable"""
<|body_0|>
def update(self, requ... | stack_v2_sparse_classes_75kplus_train_066898 | 4,573 | no_license | [
{
"docstring": "View a deliverable",
"name": "read",
"signature": "def read(self, request, project_number, deliverable_id)"
},
{
"docstring": "Update the deliverable",
"name": "update",
"signature": "def update(self, request, project_number, deliverable_id)"
},
{
"docstring": "Di... | 3 | stack_v2_sparse_classes_30k_train_051989 | Implement the Python class `DeliverableResourceHandler` described below.
Class description:
URI: /api/deliverables/%project_number%/%deliverable_id%/ VERBS: GET, PUT, DELETE Handles a single instance of Deliverable
Method signatures and docstrings:
- def read(self, request, project_number, deliverable_id): View a del... | Implement the Python class `DeliverableResourceHandler` described below.
Class description:
URI: /api/deliverables/%project_number%/%deliverable_id%/ VERBS: GET, PUT, DELETE Handles a single instance of Deliverable
Method signatures and docstrings:
- def read(self, request, project_number, deliverable_id): View a del... | 106a96307612318fb66246486e7226069e5508ac | <|skeleton|>
class DeliverableResourceHandler:
"""URI: /api/deliverables/%project_number%/%deliverable_id%/ VERBS: GET, PUT, DELETE Handles a single instance of Deliverable"""
def read(self, request, project_number, deliverable_id):
"""View a deliverable"""
<|body_0|>
def update(self, requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeliverableResourceHandler:
"""URI: /api/deliverables/%project_number%/%deliverable_id%/ VERBS: GET, PUT, DELETE Handles a single instance of Deliverable"""
def read(self, request, project_number, deliverable_id):
"""View a deliverable"""
log.debug('GET request from user %s for deliverabl... | the_stack_v2_python_sparse | api-example/deliverables/api_views.py | NhaTrang/django-project-management | train | 0 |
8748a1c009db8a960d118c2d66f4417204b05188 | [
"pl = PageLogin(self.driver)\npl.quick_login()\npse = PageSendMail(self.driver)\npse.goto_letter()\nself.driver.switch_to.frame('mainFrame')\npse.type_exit()\ntime.sleep(1)\nassert self.driver.title == 'QQ邮箱', '写信未关闭'",
"pl = PageLogin(self.driver)\npl.quick_login()\npse = PageSendMail(self.driver)\npse.goto_lett... | <|body_start_0|>
pl = PageLogin(self.driver)
pl.quick_login()
pse = PageSendMail(self.driver)
pse.goto_letter()
self.driver.switch_to.frame('mainFrame')
pse.type_exit()
time.sleep(1)
assert self.driver.title == 'QQ邮箱', '写信未关闭'
<|end_body_0|>
<|body_start_... | 关闭写信页面测试 | TestWriteOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestWriteOut:
"""关闭写信页面测试"""
def test1_write_out(self):
"""未添加任何邮件内容,关闭写信页面"""
<|body_0|>
def test2_write_out(self):
"""添加了邮件主题或正文,关闭写信页面,且不将改动存为草稿"""
<|body_1|>
def test3_write_out(self):
"""添加了邮件主题或正文,关闭写信页面,且将改动存为草稿"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_066899 | 2,848 | no_license | [
{
"docstring": "未添加任何邮件内容,关闭写信页面",
"name": "test1_write_out",
"signature": "def test1_write_out(self)"
},
{
"docstring": "添加了邮件主题或正文,关闭写信页面,且不将改动存为草稿",
"name": "test2_write_out",
"signature": "def test2_write_out(self)"
},
{
"docstring": "添加了邮件主题或正文,关闭写信页面,且将改动存为草稿",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_031569 | Implement the Python class `TestWriteOut` described below.
Class description:
关闭写信页面测试
Method signatures and docstrings:
- def test1_write_out(self): 未添加任何邮件内容,关闭写信页面
- def test2_write_out(self): 添加了邮件主题或正文,关闭写信页面,且不将改动存为草稿
- def test3_write_out(self): 添加了邮件主题或正文,关闭写信页面,且将改动存为草稿 | Implement the Python class `TestWriteOut` described below.
Class description:
关闭写信页面测试
Method signatures and docstrings:
- def test1_write_out(self): 未添加任何邮件内容,关闭写信页面
- def test2_write_out(self): 添加了邮件主题或正文,关闭写信页面,且不将改动存为草稿
- def test3_write_out(self): 添加了邮件主题或正文,关闭写信页面,且将改动存为草稿
<|skeleton|>
class TestWriteOut:
... | d6fb7c64903dfbf89f9b10f4bc3beb72e7c251f5 | <|skeleton|>
class TestWriteOut:
"""关闭写信页面测试"""
def test1_write_out(self):
"""未添加任何邮件内容,关闭写信页面"""
<|body_0|>
def test2_write_out(self):
"""添加了邮件主题或正文,关闭写信页面,且不将改动存为草稿"""
<|body_1|>
def test3_write_out(self):
"""添加了邮件主题或正文,关闭写信页面,且将改动存为草稿"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestWriteOut:
"""关闭写信页面测试"""
def test1_write_out(self):
"""未添加任何邮件内容,关闭写信页面"""
pl = PageLogin(self.driver)
pl.quick_login()
pse = PageSendMail(self.driver)
pse.goto_letter()
self.driver.switch_to.frame('mainFrame')
pse.type_exit()
time.sleep... | the_stack_v2_python_sparse | QQ_mail_auto_test/mail_auto_test/test_case/testE_write_out.py | jianghualuo/python_selenium | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.