blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1caa34bbc6c112da13ea9762e522e358bdcda853 | [
"slower = head\nfaster = head\nwhile True:\n if faster == None or faster.next == None:\n return None\n slower = slower.next\n faster = faster.next.next\n if slower == faster:\n break\nslower = head\nwhile True:\n if slower == faster:\n return slower\n else:\n slower = s... | <|body_start_0|>
slower = head
faster = head
while True:
if faster == None or faster.next == None:
return None
slower = slower.next
faster = faster.next.next
if slower == faster:
break
slower = head
w... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle_self(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
slower = head
faster = h... | stack_v2_sparse_classes_36k_train_004900 | 1,255 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "detectCycle_self",
"signature": "def detectCycle_self(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle_self(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle_self(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
de... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle_self(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
slower = head
faster = head
while True:
if faster == None or faster.next == None:
return None
slower = slower.next
faster = faster.next.next
... | the_stack_v2_python_sparse | 142_linked_list_cycle_2/sol.py | lianke123321/leetcode_sol | train | 0 | |
6605427a8264d328cdaa14128510899dcedb5d7e | [
"if config is None:\n self.config = configuration.BossConfig()\nelse:\n self.config = config\nself.vault = Vault(config)\nself.domain = self.config['system']['fqdn'].split('.', 1)[1]\nself.iam = boto3.resource('iam', region_name=aws.get_region())",
"sanitized_domain = self.domain.replace('.', '-')\npath = I... | <|body_start_0|>
if config is None:
self.config = configuration.BossConfig()
else:
self.config = config
self.vault = Vault(config)
self.domain = self.config['system']['fqdn'].split('.', 1)[1]
self.iam = boto3.resource('iam', region_name=aws.get_region())
<... | Manages temporary AWS credentials used by ingest clients. Typical usage: ingest_creds = IngestCredentials() #### On POST to endpoint from ingest client. # If supplying a custom policy: arn = ingest_creds.create_policy(policy_doc, job_id) # Otherwise generate the policy using ndingest.util.bossutil.generate_ingest_polic... | IngestCredentials | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IngestCredentials:
"""Manages temporary AWS credentials used by ingest clients. Typical usage: ingest_creds = IngestCredentials() #### On POST to endpoint from ingest client. # If supplying a custom policy: arn = ingest_creds.create_policy(policy_doc, job_id) # Otherwise generate the policy using... | stack_v2_sparse_classes_36k_train_004901 | 5,930 | permissive | [
{
"docstring": "Args: config (optional[configuration.BossConfig]): Boss configuration. Defaults to loading from /etc/boss/boss.config.",
"name": "__init__",
"signature": "def __init__(self, config=None)"
},
{
"docstring": "Create a new IAM policy for the given ingest job. Args: policy_document (... | 6 | stack_v2_sparse_classes_30k_train_020031 | Implement the Python class `IngestCredentials` described below.
Class description:
Manages temporary AWS credentials used by ingest clients. Typical usage: ingest_creds = IngestCredentials() #### On POST to endpoint from ingest client. # If supplying a custom policy: arn = ingest_creds.create_policy(policy_doc, job_id... | Implement the Python class `IngestCredentials` described below.
Class description:
Manages temporary AWS credentials used by ingest clients. Typical usage: ingest_creds = IngestCredentials() #### On POST to endpoint from ingest client. # If supplying a custom policy: arn = ingest_creds.create_policy(policy_doc, job_id... | 2ace8ce2985ffa3c442ed85134d26c76fb5d984f | <|skeleton|>
class IngestCredentials:
"""Manages temporary AWS credentials used by ingest clients. Typical usage: ingest_creds = IngestCredentials() #### On POST to endpoint from ingest client. # If supplying a custom policy: arn = ingest_creds.create_policy(policy_doc, job_id) # Otherwise generate the policy using... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IngestCredentials:
"""Manages temporary AWS credentials used by ingest clients. Typical usage: ingest_creds = IngestCredentials() #### On POST to endpoint from ingest client. # If supplying a custom policy: arn = ingest_creds.create_policy(policy_doc, job_id) # Otherwise generate the policy using ndingest.uti... | the_stack_v2_python_sparse | bossutils/ingestcreds.py | jhuapl-boss/boss-tools | train | 1 |
bcd288a07504223350863aebc93d3e5b7953e458 | [
"parent = self.cleaned_data['parent']\nif parent is None:\n return parent\nif parent.id == self.instance.id:\n raise forms.ValidationError(\"Comment cannot be it's reply\")\nchecked_comment = parent\nwhile checked_comment is not None:\n throw = False\n if checked_comment.id == self.instance.id:\n ... | <|body_start_0|>
parent = self.cleaned_data['parent']
if parent is None:
return parent
if parent.id == self.instance.id:
raise forms.ValidationError("Comment cannot be it's reply")
checked_comment = parent
while checked_comment is not None:
thr... | CommentAdminForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentAdminForm:
def clean_parent(self):
"""Check that it doesnt refer to itself, and that theres no reply loop"""
<|body_0|>
def clean(self):
"""A Comment should not be attached to a post and a comment"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004902 | 2,510 | no_license | [
{
"docstring": "Check that it doesnt refer to itself, and that theres no reply loop",
"name": "clean_parent",
"signature": "def clean_parent(self)"
},
{
"docstring": "A Comment should not be attached to a post and a comment",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019317 | Implement the Python class `CommentAdminForm` described below.
Class description:
Implement the CommentAdminForm class.
Method signatures and docstrings:
- def clean_parent(self): Check that it doesnt refer to itself, and that theres no reply loop
- def clean(self): A Comment should not be attached to a post and a co... | Implement the Python class `CommentAdminForm` described below.
Class description:
Implement the CommentAdminForm class.
Method signatures and docstrings:
- def clean_parent(self): Check that it doesnt refer to itself, and that theres no reply loop
- def clean(self): A Comment should not be attached to a post and a co... | 8abf6b77fdf4c692b456c8c062d3114aaeb16c04 | <|skeleton|>
class CommentAdminForm:
def clean_parent(self):
"""Check that it doesnt refer to itself, and that theres no reply loop"""
<|body_0|>
def clean(self):
"""A Comment should not be attached to a post and a comment"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentAdminForm:
def clean_parent(self):
"""Check that it doesnt refer to itself, and that theres no reply loop"""
parent = self.cleaned_data['parent']
if parent is None:
return parent
if parent.id == self.instance.id:
raise forms.ValidationError("Comme... | the_stack_v2_python_sparse | api/apps/posts/admin.py | dstarner/townvisor-backend | train | 0 | |
e64e3fdafc4b1b1aad72c331d10f009c7bf4b795 | [
"self.N = N\nself.t = np.linspace(0, 1, N)\nself.h = self.t[1:] - self.t[:-1]",
"N = self.N\nu = variables[0:self.N]\nobj = 0\nfor i in range(N - 1):\n obj += 0.5 * self.h[i] * (u[i] ** 2 + u[i + 1] ** 2)\nreturn obj",
"N = self.N\nu = variables[0:N]\npos = variables[N::2]\nvel = variables[N + 1::2]\nconstra... | <|body_start_0|>
self.N = N
self.t = np.linspace(0, 1, N)
self.h = self.t[1:] - self.t[:-1]
<|end_body_0|>
<|body_start_1|>
N = self.N
u = variables[0:self.N]
obj = 0
for i in range(N - 1):
obj += 0.5 * self.h[i] * (u[i] ** 2 + u[i + 1] ** 2)
... | @brief A class that contains the functions that define the following optimization problem for a double integrator moving to position 1 with minimum squared acceleration @details The continuous version of this problem is: \\min_{u(t)} \\int_u(t)^2 dt s.t. x(0) = 0, x(1) = 1 v(0) = 0, v(1) = 0 \\dot{x}(t) = v(t) \\dot{v}... | DoubleIntegratorMinimumForceTrapezoidal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoubleIntegratorMinimumForceTrapezoidal:
"""@brief A class that contains the functions that define the following optimization problem for a double integrator moving to position 1 with minimum squared acceleration @details The continuous version of this problem is: \\min_{u(t)} \\int_u(t)^2 dt s.t... | stack_v2_sparse_classes_36k_train_004903 | 7,642 | no_license | [
{
"docstring": "@brief constructs the discrete problem @param N number of knot points to use",
"name": "__init__",
"signature": "def __init__(self, N)"
},
{
"docstring": "@brief the function to minimize \\\\sum_{k=0}^{N-1} 0.5 * (t_{k+1} - t_{k}) * (u_{k}^2 + u_{k+1}^2) @param variables The deci... | 4 | stack_v2_sparse_classes_30k_train_017437 | Implement the Python class `DoubleIntegratorMinimumForceTrapezoidal` described below.
Class description:
@brief A class that contains the functions that define the following optimization problem for a double integrator moving to position 1 with minimum squared acceleration @details The continuous version of this probl... | Implement the Python class `DoubleIntegratorMinimumForceTrapezoidal` described below.
Class description:
@brief A class that contains the functions that define the following optimization problem for a double integrator moving to position 1 with minimum squared acceleration @details The continuous version of this probl... | f991450cf50acc376d9d3eb17055c9c58302724b | <|skeleton|>
class DoubleIntegratorMinimumForceTrapezoidal:
"""@brief A class that contains the functions that define the following optimization problem for a double integrator moving to position 1 with minimum squared acceleration @details The continuous version of this problem is: \\min_{u(t)} \\int_u(t)^2 dt s.t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoubleIntegratorMinimumForceTrapezoidal:
"""@brief A class that contains the functions that define the following optimization problem for a double integrator moving to position 1 with minimum squared acceleration @details The continuous version of this problem is: \\min_{u(t)} \\int_u(t)^2 dt s.t. x(0) = 0, x... | the_stack_v2_python_sparse | traj_opt_transcription/block_move_trapezoidal.py | chickensouple/experiments | train | 0 |
a99d8062ab6660f0d4911b51c168e2c7422def94 | [
"super().__init__(model, state_preprocessor, rlt.ModelFeatureConfig())\nself.seq_len = seq_len\nself.num_action = num_action\nself.all_permut = gen_permutations(seq_len, num_action)",
"state_with_presence, _, _ = state\nbatch_size, state_dim = state_with_presence[0].size()\nstate_first_step = self.state_preproces... | <|body_start_0|>
super().__init__(model, state_preprocessor, rlt.ModelFeatureConfig())
self.seq_len = seq_len
self.num_action = num_action
self.all_permut = gen_permutations(seq_len, num_action)
<|end_body_0|>
<|body_start_1|>
state_with_presence, _, _ = state
batch_size... | Seq2RewardWithPreprocessor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seq2RewardWithPreprocessor:
def __init__(self, model: ModelBase, state_preprocessor: Preprocessor, seq_len: int, num_action: int):
"""Since TorchScript unable to trace control-flow, we have to generate the action enumerations as constants here so that trace can use them directly."""
... | stack_v2_sparse_classes_36k_train_004904 | 32,028 | permissive | [
{
"docstring": "Since TorchScript unable to trace control-flow, we have to generate the action enumerations as constants here so that trace can use them directly.",
"name": "__init__",
"signature": "def __init__(self, model: ModelBase, state_preprocessor: Preprocessor, seq_len: int, num_action: int)"
... | 2 | null | Implement the Python class `Seq2RewardWithPreprocessor` described below.
Class description:
Implement the Seq2RewardWithPreprocessor class.
Method signatures and docstrings:
- def __init__(self, model: ModelBase, state_preprocessor: Preprocessor, seq_len: int, num_action: int): Since TorchScript unable to trace contr... | Implement the Python class `Seq2RewardWithPreprocessor` described below.
Class description:
Implement the Seq2RewardWithPreprocessor class.
Method signatures and docstrings:
- def __init__(self, model: ModelBase, state_preprocessor: Preprocessor, seq_len: int, num_action: int): Since TorchScript unable to trace contr... | c5f1a8371a677b4f8fb0882b600bf331eba5259d | <|skeleton|>
class Seq2RewardWithPreprocessor:
def __init__(self, model: ModelBase, state_preprocessor: Preprocessor, seq_len: int, num_action: int):
"""Since TorchScript unable to trace control-flow, we have to generate the action enumerations as constants here so that trace can use them directly."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Seq2RewardWithPreprocessor:
def __init__(self, model: ModelBase, state_preprocessor: Preprocessor, seq_len: int, num_action: int):
"""Since TorchScript unable to trace control-flow, we have to generate the action enumerations as constants here so that trace can use them directly."""
super().__... | the_stack_v2_python_sparse | reagent/prediction/predictor_wrapper.py | facebookresearch/ReAgent | train | 1,480 | |
b66469a6636cfa67f8d3717ae2806c874b7b2c53 | [
"if not root:\n return '[]'\nqueue = collections.deque()\nqueue.append(root)\nres = []\nwhile queue:\n size = len(queue)\n for i in range(size):\n cur = queue.popleft()\n if cur:\n res.append(str(cur.val))\n else:\n res.append('null')\n if cur:\n ... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
size = len(queue)
for i in range(size):
cur = queue.popleft()
if cur:
res.append(... | 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|>
def deserialize(self,... | stack_v2_sparse_classes_36k_train_004905 | 3,278 | 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... | 3 | stack_v2_sparse_classes_30k_train_019963 | 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:... | f1bbd6b3197cd9ac4f0d35a37539c11b02272065 | <|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|>
def deserialize(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
size = len(queue)
for i ... | the_stack_v2_python_sparse | leetcode/高频面试/树/297. 二叉树的序列化与反序列化 hard 细节上存在问题/Codec.py | guohaoyuan/algorithms-for-work | train | 2 | |
032f4d04902d8f452e33e4d2427eaec540101dfc | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"new_d = '\"[]\"'\nif list_dictionaries is None:\n return str(new_d)\nelif type(list_dictionaries) is list:\n return json.dumps(list_dictionaries)"
] | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
new_d = '"[]"'
if list_dictionaries is None:
return str(new_d)
elif type(list_dictionaries) i... | Creates "IDs" for instances. | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Creates "IDs" for instances."""
def __init__(self, id=None):
"""Creates an instance of Base"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Converts dictionary into str returns string."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004906 | 1,304 | no_license | [
{
"docstring": "Creates an instance of Base",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Converts dictionary into str returns string.",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015732 | Implement the Python class `Base` described below.
Class description:
Creates "IDs" for instances.
Method signatures and docstrings:
- def __init__(self, id=None): Creates an instance of Base
- def to_json_string(list_dictionaries): Converts dictionary into str returns string. | Implement the Python class `Base` described below.
Class description:
Creates "IDs" for instances.
Method signatures and docstrings:
- def __init__(self, id=None): Creates an instance of Base
- def to_json_string(list_dictionaries): Converts dictionary into str returns string.
<|skeleton|>
class Base:
"""Creates... | 5fd1f592e5e555a0076256208473afbd4a920eda | <|skeleton|>
class Base:
"""Creates "IDs" for instances."""
def __init__(self, id=None):
"""Creates an instance of Base"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Converts dictionary into str returns string."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""Creates "IDs" for instances."""
def __init__(self, id=None):
"""Creates an instance of Base"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def to_json_string(list_dictionaries):
... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | gateway17/holbertonschool-higher_level_programming | train | 0 |
95091c6b7c4e772633dcd655caf80e274042fdfe | [
"super(HumiditySensorEmulatorTask, self).__init__(sensorName=ConfigConst.HUMIDITY_SENSOR_NAME, sensorType=SensorData.HUMIDITY_SENSOR_TYPE, minVal=SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY, maxVal=SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)\nself.configUtil = ConfigUtil()\nif self.configUtil.getBoolean(self, Confi... | <|body_start_0|>
super(HumiditySensorEmulatorTask, self).__init__(sensorName=ConfigConst.HUMIDITY_SENSOR_NAME, sensorType=SensorData.HUMIDITY_SENSOR_TYPE, minVal=SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY, maxVal=SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)
self.configUtil = ConfigUtil()
if self... | Shell representation of class for student implementation. | HumiditySensorEmulatorTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumiditySensorEmulatorTask:
"""Shell representation of class for student implementation."""
def __init__(self, dataSet=None):
"""Constructor: determine if emulator is used dataSet: DataSet"""
<|body_0|>
def generateTelemetry(self) -> SensorData:
"""Get humidity d... | stack_v2_sparse_classes_36k_train_004907 | 2,165 | permissive | [
{
"docstring": "Constructor: determine if emulator is used dataSet: DataSet",
"name": "__init__",
"signature": "def __init__(self, dataSet=None)"
},
{
"docstring": "Get humidity data from emulator return SensorData",
"name": "generateTelemetry",
"signature": "def generateTelemetry(self) ... | 2 | stack_v2_sparse_classes_30k_train_001654 | Implement the Python class `HumiditySensorEmulatorTask` described below.
Class description:
Shell representation of class for student implementation.
Method signatures and docstrings:
- def __init__(self, dataSet=None): Constructor: determine if emulator is used dataSet: DataSet
- def generateTelemetry(self) -> Senso... | Implement the Python class `HumiditySensorEmulatorTask` described below.
Class description:
Shell representation of class for student implementation.
Method signatures and docstrings:
- def __init__(self, dataSet=None): Constructor: determine if emulator is used dataSet: DataSet
- def generateTelemetry(self) -> Senso... | 26db6375a21ee9bdccba3d137e30d2e63ad6395c | <|skeleton|>
class HumiditySensorEmulatorTask:
"""Shell representation of class for student implementation."""
def __init__(self, dataSet=None):
"""Constructor: determine if emulator is used dataSet: DataSet"""
<|body_0|>
def generateTelemetry(self) -> SensorData:
"""Get humidity d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HumiditySensorEmulatorTask:
"""Shell representation of class for student implementation."""
def __init__(self, dataSet=None):
"""Constructor: determine if emulator is used dataSet: DataSet"""
super(HumiditySensorEmulatorTask, self).__init__(sensorName=ConfigConst.HUMIDITY_SENSOR_NAME, sen... | the_stack_v2_python_sparse | src/main/python/programmingtheiot/cda/emulated/HumiditySensorEmulatorTask.py | Zhengrui-Liu/FireAlarmingSysCDA | train | 0 |
153bef56d0717e41310e1905c7aaf33bb9835eb1 | [
"self.libm = libm\nself.gen_src = []\nself.clml_modules = None\nself.clml_builds = {}\nself.codegen = None\nself.nodes = None\nself.MakeFileHeader = Template('/*\\n * Licensed to the Apache Software Foundation (ASF) under one\\n * or more contributor license agreements. See the NOTICE file\\n ... | <|body_start_0|>
self.libm = libm
self.gen_src = []
self.clml_modules = None
self.clml_builds = {}
self.codegen = None
self.nodes = None
self.MakeFileHeader = Template('/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more con... | Generates CLML API source given a TVM compiled mod | CLMLGenSrc | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"Zlib",
"LLVM-exception",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLMLGenSrc:
"""Generates CLML API source given a TVM compiled mod"""
def __init__(self, libm):
"""Initialize Parameters ---------- libm : Module Compiled relay module"""
<|body_0|>
def get_clml_params(self):
"""Returns parameters from the TVM module"""
<|... | stack_v2_sparse_classes_36k_train_004908 | 49,674 | permissive | [
{
"docstring": "Initialize Parameters ---------- libm : Module Compiled relay module",
"name": "__init__",
"signature": "def __init__(self, libm)"
},
{
"docstring": "Returns parameters from the TVM module",
"name": "get_clml_params",
"signature": "def get_clml_params(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_012127 | Implement the Python class `CLMLGenSrc` described below.
Class description:
Generates CLML API source given a TVM compiled mod
Method signatures and docstrings:
- def __init__(self, libm): Initialize Parameters ---------- libm : Module Compiled relay module
- def get_clml_params(self): Returns parameters from the TVM... | Implement the Python class `CLMLGenSrc` described below.
Class description:
Generates CLML API source given a TVM compiled mod
Method signatures and docstrings:
- def __init__(self, libm): Initialize Parameters ---------- libm : Module Compiled relay module
- def get_clml_params(self): Returns parameters from the TVM... | d75083cd97ede706338ab413dbc964009456d01b | <|skeleton|>
class CLMLGenSrc:
"""Generates CLML API source given a TVM compiled mod"""
def __init__(self, libm):
"""Initialize Parameters ---------- libm : Module Compiled relay module"""
<|body_0|>
def get_clml_params(self):
"""Returns parameters from the TVM module"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CLMLGenSrc:
"""Generates CLML API source given a TVM compiled mod"""
def __init__(self, libm):
"""Initialize Parameters ---------- libm : Module Compiled relay module"""
self.libm = libm
self.gen_src = []
self.clml_modules = None
self.clml_builds = {}
self.... | the_stack_v2_python_sparse | python/tvm/relay/op/contrib/clml.py | apache/tvm | train | 4,575 |
3a253428e137197d4133562d6e7deb2fff3f5c2f | [
"super().__init__(hass, LOGGER, name=name, update_interval=update_interval, update_method=update_method, always_update=False)\nself._rebooting = False\nself._signal_handler_unsubs: list[Callable[..., None]] = []\nself.config_entry = entry\nself.signal_reboot_completed = SIGNAL_REBOOT_COMPLETED.format(self.config_en... | <|body_start_0|>
super().__init__(hass, LOGGER, name=name, update_interval=update_interval, update_method=update_method, always_update=False)
self._rebooting = False
self._signal_handler_unsubs: list[Callable[..., None]] = []
self.config_entry = entry
self.signal_reboot_completed... | Define an extended DataUpdateCoordinator. | RainMachineDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainMachineDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None:
"""Initialize."""
<|bod... | stack_v2_sparse_classes_36k_train_004909 | 5,234 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None"
},
{
"docstring": "Initialize the coordinator.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_008614 | Implement the Python class `RainMachineDataUpdateCoordinator` described below.
Class description:
Define an extended DataUpdateCoordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callab... | Implement the Python class `RainMachineDataUpdateCoordinator` described below.
Class description:
Define an extended DataUpdateCoordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callab... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RainMachineDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None:
"""Initialize."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RainMachineDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None:
"""Initialize."""
super().__init__(h... | the_stack_v2_python_sparse | homeassistant/components/rainmachine/util.py | home-assistant/core | train | 35,501 |
e341595248af14b62a36bda8fedd9dee4583d9ee | [
"nid = request.GET.get('id', None)\nupdate = models.Bussiness.objects.filter(id=nid).first()\nobj = forms.CreateBussiness(initial={'virIP': update.virIP, 'application': update.application, 'port': update.port, 'component': update.component, 'principal': update.principal, 'business_chooics': update.business_chooics,... | <|body_start_0|>
nid = request.GET.get('id', None)
update = models.Bussiness.objects.filter(id=nid).first()
obj = forms.CreateBussiness(initial={'virIP': update.virIP, 'application': update.application, 'port': update.port, 'component': update.component, 'principal': update.principal, 'business_... | 更新业务线 | RessourcessModifyView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RessourcessModifyView:
"""更新业务线"""
def get(self, request, *args, **kwargs):
"""获取历史相应的数据"""
<|body_0|>
def post(self, request):
"""更新相应的历史数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nid = request.GET.get('id', None)
update = model... | stack_v2_sparse_classes_36k_train_004910 | 5,922 | no_license | [
{
"docstring": "获取历史相应的数据",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "更新相应的历史数据",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019796 | Implement the Python class `RessourcessModifyView` described below.
Class description:
更新业务线
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取历史相应的数据
- def post(self, request): 更新相应的历史数据 | Implement the Python class `RessourcessModifyView` described below.
Class description:
更新业务线
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取历史相应的数据
- def post(self, request): 更新相应的历史数据
<|skeleton|>
class RessourcessModifyView:
"""更新业务线"""
def get(self, request, *args, **kwarg... | fc565af20312410214dec638e85fc35fc85eef2d | <|skeleton|>
class RessourcessModifyView:
"""更新业务线"""
def get(self, request, *args, **kwargs):
"""获取历史相应的数据"""
<|body_0|>
def post(self, request):
"""更新相应的历史数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RessourcessModifyView:
"""更新业务线"""
def get(self, request, *args, **kwargs):
"""获取历史相应的数据"""
nid = request.GET.get('id', None)
update = models.Bussiness.objects.filter(id=nid).first()
obj = forms.CreateBussiness(initial={'virIP': update.virIP, 'application': update.applicat... | the_stack_v2_python_sparse | resources/views.py | xiaoyaolaotou/Devops | train | 6 |
bb92ae563af1dd4dfa6ca67cf1716c9e0a6566f9 | [
"context = super(ProcessOrder, self).get_context_data()\norder = get_object_or_404(Order, id=self.kwargs.get('order'))\ncontext['ordered_by'] = order.user\nreturn context",
"form = super(ProcessOrder, self).get_form()\nform.fields['crate'].queryset = Crate.objects.filter(at_user=None).filter(at_distributer=None).... | <|body_start_0|>
context = super(ProcessOrder, self).get_context_data()
order = get_object_or_404(Order, id=self.kwargs.get('order'))
context['ordered_by'] = order.user
return context
<|end_body_0|>
<|body_start_1|>
form = super(ProcessOrder, self).get_form()
form.fields... | Fill out production details | ProcessOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessOrder:
"""Fill out production details"""
def get_context_data(self):
"""pass user preferences"""
<|body_0|>
def get_form(self):
"""get form to change fields"""
<|body_1|>
def get_initial(self):
"""set initial state"""
<|body_2|... | stack_v2_sparse_classes_36k_train_004911 | 7,814 | no_license | [
{
"docstring": "pass user preferences",
"name": "get_context_data",
"signature": "def get_context_data(self)"
},
{
"docstring": "get form to change fields",
"name": "get_form",
"signature": "def get_form(self)"
},
{
"docstring": "set initial state",
"name": "get_initial",
... | 4 | stack_v2_sparse_classes_30k_train_003592 | Implement the Python class `ProcessOrder` described below.
Class description:
Fill out production details
Method signatures and docstrings:
- def get_context_data(self): pass user preferences
- def get_form(self): get form to change fields
- def get_initial(self): set initial state
- def form_valid(self, form): if th... | Implement the Python class `ProcessOrder` described below.
Class description:
Fill out production details
Method signatures and docstrings:
- def get_context_data(self): pass user preferences
- def get_form(self): get form to change fields
- def get_initial(self): set initial state
- def form_valid(self, form): if th... | dba0dc18ca9b6d8464536ea2e96c29c51efc1a94 | <|skeleton|>
class ProcessOrder:
"""Fill out production details"""
def get_context_data(self):
"""pass user preferences"""
<|body_0|>
def get_form(self):
"""get form to change fields"""
<|body_1|>
def get_initial(self):
"""set initial state"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessOrder:
"""Fill out production details"""
def get_context_data(self):
"""pass user preferences"""
context = super(ProcessOrder, self).get_context_data()
order = get_object_or_404(Order, id=self.kwargs.get('order'))
context['ordered_by'] = order.user
return co... | the_stack_v2_python_sparse | management/views.py | sasekb/tozd | train | 0 |
cd1ea0f255fde9c97246765be5134ed6158698a2 | [
"self.name = name\nself.weight = weight\nself.children = children\nself.parent = None\nself.total_weight = 0",
"for child in self.children:\n found, val = child.balance()\n if found:\n return (found, val)\nchildren = sorted(self.children, key=lambda child: -child.total_weight)\nif len(children) > 1:\... | <|body_start_0|>
self.name = name
self.weight = weight
self.children = children
self.parent = None
self.total_weight = 0
<|end_body_0|>
<|body_start_1|>
for child in self.children:
found, val = child.balance()
if found:
return (fou... | Basic class representing a given 'program' in the tower Includes method to determine unbalanced program within the tower | Program | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Program:
"""Basic class representing a given 'program' in the tower Includes method to determine unbalanced program within the tower"""
def __init__(self, name, weight, children):
"""Basic initialization, including tracking the parent and total weight for the sub-tower under the give... | stack_v2_sparse_classes_36k_train_004912 | 3,396 | permissive | [
{
"docstring": "Basic initialization, including tracking the parent and total weight for the sub-tower under the given program",
"name": "__init__",
"signature": "def __init__(self, name, weight, children)"
},
{
"docstring": "Determine the unbalanced program and return the corrected value needed... | 2 | stack_v2_sparse_classes_30k_train_009453 | Implement the Python class `Program` described below.
Class description:
Basic class representing a given 'program' in the tower Includes method to determine unbalanced program within the tower
Method signatures and docstrings:
- def __init__(self, name, weight, children): Basic initialization, including tracking the... | Implement the Python class `Program` described below.
Class description:
Basic class representing a given 'program' in the tower Includes method to determine unbalanced program within the tower
Method signatures and docstrings:
- def __init__(self, name, weight, children): Basic initialization, including tracking the... | 3f5a0e03ca03a73cfffbe88945f6c50285a029db | <|skeleton|>
class Program:
"""Basic class representing a given 'program' in the tower Includes method to determine unbalanced program within the tower"""
def __init__(self, name, weight, children):
"""Basic initialization, including tracking the parent and total weight for the sub-tower under the give... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Program:
"""Basic class representing a given 'program' in the tower Includes method to determine unbalanced program within the tower"""
def __init__(self, name, weight, children):
"""Basic initialization, including tracking the parent and total weight for the sub-tower under the given program"""
... | the_stack_v2_python_sparse | day07.py | minddrive/adventofcode2017 | train | 0 |
c4bd9d3decb557c710646e5bff05fc3b3d7701ec | [
"numbers = range(0, 16)\nexpected_even = range(0, 16, 2)\nexpected_odd = range(1, 16, 2)\neven, odd = source.split_even_odd(numbers)\nself.assertEqual(even, expected_even, 'Even values differ')\nself.assertEqual(odd, expected_odd, 'Odd values differ')",
"inst = source.NumbersList()\nnumber = 6\nexpected_even = [n... | <|body_start_0|>
numbers = range(0, 16)
expected_even = range(0, 16, 2)
expected_odd = range(1, 16, 2)
even, odd = source.split_even_odd(numbers)
self.assertEqual(even, expected_even, 'Even values differ')
self.assertEqual(odd, expected_odd, 'Odd values differ')
<|end_bod... | Test exercise 0: mutable and immutable types common errors | TestMutableImmutable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMutableImmutable:
"""Test exercise 0: mutable and immutable types common errors"""
def test_split_even_odd(self):
"""Check multiple assignment of mutables"""
<|body_0|>
def test_append_number_even(self):
"""Check mutable class attributes"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_004913 | 2,522 | no_license | [
{
"docstring": "Check multiple assignment of mutables",
"name": "test_split_even_odd",
"signature": "def test_split_even_odd(self)"
},
{
"docstring": "Check mutable class attributes",
"name": "test_append_number_even",
"signature": "def test_append_number_even(self)"
},
{
"docstr... | 5 | stack_v2_sparse_classes_30k_val_000091 | Implement the Python class `TestMutableImmutable` described below.
Class description:
Test exercise 0: mutable and immutable types common errors
Method signatures and docstrings:
- def test_split_even_odd(self): Check multiple assignment of mutables
- def test_append_number_even(self): Check mutable class attributes
... | Implement the Python class `TestMutableImmutable` described below.
Class description:
Test exercise 0: mutable and immutable types common errors
Method signatures and docstrings:
- def test_split_even_odd(self): Check multiple assignment of mutables
- def test_append_number_even(self): Check mutable class attributes
... | 8f082201e24f0f2b991d9388500fdbf95d6f073d | <|skeleton|>
class TestMutableImmutable:
"""Test exercise 0: mutable and immutable types common errors"""
def test_split_even_odd(self):
"""Check multiple assignment of mutables"""
<|body_0|>
def test_append_number_even(self):
"""Check mutable class attributes"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMutableImmutable:
"""Test exercise 0: mutable and immutable types common errors"""
def test_split_even_odd(self):
"""Check multiple assignment of mutables"""
numbers = range(0, 16)
expected_even = range(0, 16, 2)
expected_odd = range(1, 16, 2)
even, odd = sourc... | the_stack_v2_python_sparse | intermediate/exercises/mod_01_mutables/tests.py | garciacastano09/pycourse | train | 0 |
5f8cbd0085f8006aaff0a569b132791de2f3397b | [
"if not root:\n return []\nq = deque()\nq.appendleft(root)\nresult = []\nwhile q:\n node = q.pop()\n if node:\n result.append(str(node.val))\n q.appendleft(node.left)\n q.appendleft(node.right)\n else:\n result.append('null')\nreturn result",
"if not data:\n return\ninde... | <|body_start_0|>
if not root:
return []
q = deque()
q.appendleft(root)
result = []
while q:
node = q.pop()
if node:
result.append(str(node.val))
q.appendleft(node.left)
q.appendleft(node.right)
... | Codec | [
"MIT"
] | 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_36k_train_004914 | 3,122 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_019876 | 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:... | 6a83cb798cc317d1e4357ac6b2b1fbf76fa034fb | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
q = deque()
q.appendleft(root)
result = []
while q:
node = q.pop()
if node:
res... | the_stack_v2_python_sparse | Month 03/Week 03/Day 02/d.py | KevinKnott/Coding-Review | train | 0 | |
c22b8a188c46185ce9d9ed85466fabeb59a45d2b | [
"if ax is None:\n fig, ax = plt.subplots()\nlines, markers = plt.triplot(self.tri, **kwargs)",
"vertices = self.node_map(self.tri.triangles)\nget_level = lambda node_id: self.data[label_by].loc[node_id]\nlevels = np.apply_along_axis(get_level, axis=1, arr=vertices)\nget_mode = lambda x: Counter(x).most_common(... | <|body_start_0|>
if ax is None:
fig, ax = plt.subplots()
lines, markers = plt.triplot(self.tri, **kwargs)
<|end_body_0|>
<|body_start_1|>
vertices = self.node_map(self.tri.triangles)
get_level = lambda node_id: self.data[label_by].loc[node_id]
levels = np.apply_along... | Methods for visualizing a Graph instance. | GraphVisualizationMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphVisualizationMethods:
"""Methods for visualizing a Graph instance."""
def plot_edges(self, ax=None, **kwargs):
"""Plot triangulation edges. Args: ax (matplotlib.axes.AxesSubplot) kwargs: keyword arguments for matplotlib.pyplot.triplot"""
<|body_0|>
def label_triangl... | stack_v2_sparse_classes_36k_train_004915 | 23,136 | permissive | [
{
"docstring": "Plot triangulation edges. Args: ax (matplotlib.axes.AxesSubplot) kwargs: keyword arguments for matplotlib.pyplot.triplot",
"name": "plot_edges",
"signature": "def plot_edges(self, ax=None, **kwargs)"
},
{
"docstring": "Label each triangle with most common node attribute value. Ar... | 4 | stack_v2_sparse_classes_30k_train_020302 | Implement the Python class `GraphVisualizationMethods` described below.
Class description:
Methods for visualizing a Graph instance.
Method signatures and docstrings:
- def plot_edges(self, ax=None, **kwargs): Plot triangulation edges. Args: ax (matplotlib.axes.AxesSubplot) kwargs: keyword arguments for matplotlib.py... | Implement the Python class `GraphVisualizationMethods` described below.
Class description:
Methods for visualizing a Graph instance.
Method signatures and docstrings:
- def plot_edges(self, ax=None, **kwargs): Plot triangulation edges. Args: ax (matplotlib.axes.AxesSubplot) kwargs: keyword arguments for matplotlib.py... | 4a622c3f5fed4456c3b9240f5a96428789fde9bd | <|skeleton|>
class GraphVisualizationMethods:
"""Methods for visualizing a Graph instance."""
def plot_edges(self, ax=None, **kwargs):
"""Plot triangulation edges. Args: ax (matplotlib.axes.AxesSubplot) kwargs: keyword arguments for matplotlib.pyplot.triplot"""
<|body_0|>
def label_triangl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphVisualizationMethods:
"""Methods for visualizing a Graph instance."""
def plot_edges(self, ax=None, **kwargs):
"""Plot triangulation edges. Args: ax (matplotlib.axes.AxesSubplot) kwargs: keyword arguments for matplotlib.pyplot.triplot"""
if ax is None:
fig, ax = plt.subpl... | the_stack_v2_python_sparse | flyqma/annotation/spatial/graphs.py | sbernasek/flyqma | train | 1 |
218d46b50c1eb56003322dcdde02d320e1322b2e | [
"directory = 'resources/js/components'\nif not os.path.exists(os.path.realpath(directory)):\n os.makedirs(os.path.realpath(directory))",
"if not os.path.exists(os.path.realpath('package.json')):\n return\nconfiguration_key = 'devDependencies' if dev else 'dependencies'\npackages = {}\nwith open(os.path.real... | <|body_start_0|>
directory = 'resources/js/components'
if not os.path.exists(os.path.realpath(directory)):
os.makedirs(os.path.realpath(directory))
<|end_body_0|>
<|body_start_1|>
if not os.path.exists(os.path.realpath('package.json')):
return
configuration_key =... | Preset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preset:
def ensure_component_directory_exists(self):
"""Ensure the component directories we need exist."""
<|body_0|>
def update_packages(self, dev=True):
"""Update the "package.json" file."""
<|body_1|>
def remove_node_modules(self):
"""Remove t... | stack_v2_sparse_classes_36k_train_004916 | 1,555 | permissive | [
{
"docstring": "Ensure the component directories we need exist.",
"name": "ensure_component_directory_exists",
"signature": "def ensure_component_directory_exists(self)"
},
{
"docstring": "Update the \"package.json\" file.",
"name": "update_packages",
"signature": "def update_packages(se... | 4 | stack_v2_sparse_classes_30k_train_008385 | Implement the Python class `Preset` described below.
Class description:
Implement the Preset class.
Method signatures and docstrings:
- def ensure_component_directory_exists(self): Ensure the component directories we need exist.
- def update_packages(self, dev=True): Update the "package.json" file.
- def remove_node_... | Implement the Python class `Preset` described below.
Class description:
Implement the Preset class.
Method signatures and docstrings:
- def ensure_component_directory_exists(self): Ensure the component directories we need exist.
- def update_packages(self, dev=True): Update the "package.json" file.
- def remove_node_... | 66a6b1480a5771bbd1056ba59cec4014beb63fa8 | <|skeleton|>
class Preset:
def ensure_component_directory_exists(self):
"""Ensure the component directories we need exist."""
<|body_0|>
def update_packages(self, dev=True):
"""Update the "package.json" file."""
<|body_1|>
def remove_node_modules(self):
"""Remove t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preset:
def ensure_component_directory_exists(self):
"""Ensure the component directories we need exist."""
directory = 'resources/js/components'
if not os.path.exists(os.path.realpath(directory)):
os.makedirs(os.path.realpath(directory))
def update_packages(self, dev=T... | the_stack_v2_python_sparse | src/masonite/commands/presets/Preset.py | angrycaptain19/masonite | train | 0 | |
8814cf677361cec768225806eed0994900c3a469 | [
"y = column_or_1d(y, warn=True)\nself.classes_ = np.unique(y[~pandas.isnull(y)])\nreturn self",
"check_is_fitted(self, 'classes_')\ny = column_or_1d(y, warn=True)\nnone_label = self.classes_[-1] + '_ZZ' if self.classes_.size > 0 else '_ZZ'\ny[pandas.isnull(y)] = none_label\nlabeled = np.searchsorted(self.classes_... | <|body_start_0|>
y = column_or_1d(y, warn=True)
self.classes_ = np.unique(y[~pandas.isnull(y)])
return self
<|end_body_0|>
<|body_start_1|>
check_is_fitted(self, 'classes_')
y = column_or_1d(y, warn=True)
none_label = self.classes_[-1] + '_ZZ' if self.classes_.size > 0 e... | Encode labels with value between 0 and n_classes-1. Add support for unknown labels See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme. | FlexLabelEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlexLabelEncoder:
"""Encode labels with value between 0 and n_classes-1. Add support for unknown labels See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme."""
def fit(self, y):
"""Fit label encoder Parameter... | stack_v2_sparse_classes_36k_train_004917 | 7,891 | no_license | [
{
"docstring": "Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self.",
"name": "fit",
"signature": "def fit(self, y)"
},
{
"docstring": "Transform labels to normalized encoding. Parameters ---------- y : a... | 3 | stack_v2_sparse_classes_30k_val_000315 | Implement the Python class `FlexLabelEncoder` described below.
Class description:
Encode labels with value between 0 and n_classes-1. Add support for unknown labels See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme.
Method signatures and do... | Implement the Python class `FlexLabelEncoder` described below.
Class description:
Encode labels with value between 0 and n_classes-1. Add support for unknown labels See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme.
Method signatures and do... | 932be1a3007473e6748771fa1629b677e252627d | <|skeleton|>
class FlexLabelEncoder:
"""Encode labels with value between 0 and n_classes-1. Add support for unknown labels See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme."""
def fit(self, y):
"""Fit label encoder Parameter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlexLabelEncoder:
"""Encode labels with value between 0 and n_classes-1. Add support for unknown labels See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme."""
def fit(self, y):
"""Fit label encoder Parameters ---------- ... | the_stack_v2_python_sparse | _archived_versions/20180107_invalidated_archives/20171015_full_df_exploration/preprocessing.py | dfaivre/python-ml-poc-2018 | train | 0 |
300e3584aa0d21d2a8726ffc51438670c6f72786 | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('.novel-info .title h2').text\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_cover = self.absolute_url(soup.select_one('.novel .novel-thumb img')['data-src'])\nlogger.info('Novel cov... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('.novel-info .title h2').text
logger.info('Novel title: %s', self.novel_title)
self.novel_cover = self.absolute_url(soup.select_one('.novel .novel-... | FlyingLinesCrawler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlyingLinesCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_004918 | 2,065 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | stack_v2_sparse_classes_30k_train_003460 | Implement the Python class `FlyingLinesCrawler` described below.
Class description:
Implement the FlyingLinesCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean... | Implement the Python class `FlyingLinesCrawler` described below.
Class description:
Implement the FlyingLinesCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class FlyingLinesCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlyingLinesCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('.novel-info .title h2').text
logger.info('Novel title: %s', self.n... | the_stack_v2_python_sparse | lncrawl/sources/flyinglines.py | NNTin/lightnovel-crawler | train | 2 | |
5b2de20438b8f1835ceb6d563893c1643416b2d6 | [
"test = '4 5\\n75 5\\n0 100\\n150 20\\n75 1'\nd = Company(test)\nself.assertEqual(d.n, 4)\nself.assertEqual(d.d, 5)\nself.assertEqual(d.numa, [75, 0, 150, 75])\nself.assertEqual(d.numb, [5, 100, 20, 1])\nself.assertEqual(Company(test).calculate(), '100')\ntest = '5 100\\n0 7\\n11 32\\n99 10\\n46 8\\n87 54'\nself.as... | <|body_start_0|>
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
self.assertEqual(d.n, 4)
self.assertEqual(d.d, 5)
self.assertEqual(d.numa, [75, 0, 150, 75])
self.assertEqual(d.numb, [5, 100, 20, 1])
self.assertEqual(Company(test).calculate(), '100')
... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Company class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
... | stack_v2_sparse_classes_36k_train_004919 | 3,763 | permissive | [
{
"docstring": "Company class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001187 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Company class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Company class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Company class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Company class testing"""
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
self.assertEqual(d.n, 4)
self.assertEqual(d.d, 5)
self.assertEqual(d.numa, [75, 0, 150, 75])
self.assertEqual(d.numb, [5, 100, 20... | the_stack_v2_python_sparse | codeforces/580B_company.py | snsokolov/contests | train | 1 | |
ee995a66fe990957cb04eaa1ea2aaa3fe40d28e7 | [
"super(ValueMonitor, self).__init__(parent)\nself.keyCellDict = {}\nself.data = None\nself.inited = False\nself.editable = editable\nself.initUi()",
"self.setRowCount(1)\nself.verticalHeader().setVisible(False)\nif not self.editable:\n self.setEditTriggers(self.NoEditTriggers)\nself.setMaximumHeight(self.sizeH... | <|body_start_0|>
super(ValueMonitor, self).__init__(parent)
self.keyCellDict = {}
self.data = None
self.inited = False
self.editable = editable
self.initUi()
<|end_body_0|>
<|body_start_1|>
self.setRowCount(1)
self.verticalHeader().setVisible(False)
... | 参数监控 | ValueMonitor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueMonitor:
"""参数监控"""
def __init__(self, editable=False, parent=None):
"""Constructor"""
<|body_0|>
def initUi(self):
"""初始化界面"""
<|body_1|>
def updateData(self, data):
"""更新数据"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004920 | 9,669 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, editable=False, parent=None)"
},
{
"docstring": "初始化界面",
"name": "initUi",
"signature": "def initUi(self)"
},
{
"docstring": "更新数据",
"name": "updateData",
"signature": "def updateData(self,... | 3 | null | Implement the Python class `ValueMonitor` described below.
Class description:
参数监控
Method signatures and docstrings:
- def __init__(self, editable=False, parent=None): Constructor
- def initUi(self): 初始化界面
- def updateData(self, data): 更新数据 | Implement the Python class `ValueMonitor` described below.
Class description:
参数监控
Method signatures and docstrings:
- def __init__(self, editable=False, parent=None): Constructor
- def initUi(self): 初始化界面
- def updateData(self, data): 更新数据
<|skeleton|>
class ValueMonitor:
"""参数监控"""
def __init__(self, edit... | 75f95a00e7eb569cb7cc530ea55d6646ba4595c1 | <|skeleton|>
class ValueMonitor:
"""参数监控"""
def __init__(self, editable=False, parent=None):
"""Constructor"""
<|body_0|>
def initUi(self):
"""初始化界面"""
<|body_1|>
def updateData(self, data):
"""更新数据"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueMonitor:
"""参数监控"""
def __init__(self, editable=False, parent=None):
"""Constructor"""
super(ValueMonitor, self).__init__(parent)
self.keyCellDict = {}
self.data = None
self.inited = False
self.editable = editable
self.initUi()
def initUi(... | the_stack_v2_python_sparse | vnpy/trader/app/optionMaster/uiOmStrategyManager.py | KilimanjaroFreeman/vnpy | train | 3 |
2838b1298d11942e9eae50214c7bd28a66e5177b | [
"my_grid = grid_setup(self.rp, ng=4)\nmy_data = patch.CellCenterData2d(my_grid)\nbc = bc_setup(self.rp)[0]\nmy_data.register_var('x-velocity', bc)\nmy_data.register_var('y-velocity', bc)\nmy_data.create()\nself.cc_data = my_data\nif self.rp.get_param('particles.do_particles') == 1:\n n_particles = self.rp.get_pa... | <|body_start_0|>
my_grid = grid_setup(self.rp, ng=4)
my_data = patch.CellCenterData2d(my_grid)
bc = bc_setup(self.rp)[0]
my_data.register_var('x-velocity', bc)
my_data.register_var('y-velocity', bc)
my_data.create()
self.cc_data = my_data
if self.rp.get_pa... | Simulation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""The timestep() function computes the advective timestep (CFL) constraint. T... | stack_v2_sparse_classes_36k_train_004921 | 7,113 | permissive | [
{
"docstring": "Initialize the grid and variables for advection and set the initial conditions for the chosen problem.",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "The timestep() function computes the advective timestep (CFL) constraint. The CFL constraint says ... | 4 | stack_v2_sparse_classes_30k_train_019824 | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for advection and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The timestep... | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for advection and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The timestep... | f91789a319caa98dfbc3f496e9953756e6ee3ca9 | <|skeleton|>
class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""The timestep() function computes the advective timestep (CFL) constraint. T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
my_grid = grid_setup(self.rp, ng=4)
my_data = patch.CellCenterData2d(my_grid)
bc = bc_setup(self.rp)[0]
my_data.register_var('x... | the_stack_v2_python_sparse | pyro/burgers/simulation.py | python-hydro/pyro2 | train | 202 | |
6b6bc3a002a6cebfdc09952b5b8492bf32fb0980 | [
"self.d_maas_free_trial__c = d_maas_free_trial__c\nself.end_date = end_date\nself.id = id\nself.name = name\nself.sku__c = sku__c\nself.start_date = start_date",
"if dictionary is None:\n return None\nd_maas_free_trial__c = dictionary.get('DMaaS_Free_Trial__c')\nend_date = dictionary.get('EndDate')\nid = dicti... | <|body_start_0|>
self.d_maas_free_trial__c = d_maas_free_trial__c
self.end_date = end_date
self.id = id
self.name = name
self.sku__c = sku__c
self.start_date = start_date
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
d_maa... | Implementation of the 'AccountEntitlement' model. Specifies the account entitlement for a Salesforce account. Attributes: d_maas_free_trial__c (bool): Specifies whether DMaaS free trail is active. end_date (string): Specifies the end date for the entitlement. id (bool): Specifies the entitlement ID. name (bool): Specif... | AccountEntitlement | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountEntitlement:
"""Implementation of the 'AccountEntitlement' model. Specifies the account entitlement for a Salesforce account. Attributes: d_maas_free_trial__c (bool): Specifies whether DMaaS free trail is active. end_date (string): Specifies the end date for the entitlement. id (bool): Spe... | stack_v2_sparse_classes_36k_train_004922 | 2,530 | permissive | [
{
"docstring": "Constructor for the AccountEntitlement class",
"name": "__init__",
"signature": "def __init__(self, d_maas_free_trial__c=None, end_date=None, id=None, name=None, sku__c=None, start_date=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary... | 2 | null | Implement the Python class `AccountEntitlement` described below.
Class description:
Implementation of the 'AccountEntitlement' model. Specifies the account entitlement for a Salesforce account. Attributes: d_maas_free_trial__c (bool): Specifies whether DMaaS free trail is active. end_date (string): Specifies the end d... | Implement the Python class `AccountEntitlement` described below.
Class description:
Implementation of the 'AccountEntitlement' model. Specifies the account entitlement for a Salesforce account. Attributes: d_maas_free_trial__c (bool): Specifies whether DMaaS free trail is active. end_date (string): Specifies the end d... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AccountEntitlement:
"""Implementation of the 'AccountEntitlement' model. Specifies the account entitlement for a Salesforce account. Attributes: d_maas_free_trial__c (bool): Specifies whether DMaaS free trail is active. end_date (string): Specifies the end date for the entitlement. id (bool): Spe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountEntitlement:
"""Implementation of the 'AccountEntitlement' model. Specifies the account entitlement for a Salesforce account. Attributes: d_maas_free_trial__c (bool): Specifies whether DMaaS free trail is active. end_date (string): Specifies the end date for the entitlement. id (bool): Specifies the en... | the_stack_v2_python_sparse | cohesity_management_sdk/models/account_entitlement.py | cohesity/management-sdk-python | train | 24 |
ee06e713d27fb5a06a055e5d2b5418d4f6890355 | [
"logs = get_logging_container()\nstdout, parsed_data, logs = self.parse_stdout_from_retrieved(logs)\nbase_exit_code = self.check_base_errors(logs)\nif base_exit_code:\n return self.exit(base_exit_code, logs)\nself.out('output_parameters', Dict(parsed_data))\nfor exit_code in self.get_error_map().values():\n i... | <|body_start_0|>
logs = get_logging_container()
stdout, parsed_data, logs = self.parse_stdout_from_retrieved(logs)
base_exit_code = self.check_base_errors(logs)
if base_exit_code:
return self.exit(base_exit_code, logs)
self.out('output_parameters', Dict(parsed_data))
... | ``Parser`` implementation for the ``OpenGridCalculation`` calculation job class. | OpenGridParser | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenGridParser:
"""``Parser`` implementation for the ``OpenGridCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes."""
<|body_0|>
def parse_kpoints(stdout: str, logs: Att... | stack_v2_sparse_classes_36k_train_004923 | 2,749 | permissive | [
{
"docstring": "Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes.",
"name": "parse",
"signature": "def parse(self, **kwargs)"
},
{
"docstring": "Parse the ``stdout`` for the mesh and explicit list of kpoints.",
"name": "parse_kpoints",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_019923 | Implement the Python class `OpenGridParser` described below.
Class description:
``Parser`` implementation for the ``OpenGridCalculation`` calculation job class.
Method signatures and docstrings:
- def parse(self, **kwargs): Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes.
- def pars... | Implement the Python class `OpenGridParser` described below.
Class description:
``Parser`` implementation for the ``OpenGridCalculation`` calculation job class.
Method signatures and docstrings:
- def parse(self, **kwargs): Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes.
- def pars... | 7263f92ccabcfc9f828b9da5473e1aefbc4b8eca | <|skeleton|>
class OpenGridParser:
"""``Parser`` implementation for the ``OpenGridCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes."""
<|body_0|>
def parse_kpoints(stdout: str, logs: Att... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenGridParser:
"""``Parser`` implementation for the ``OpenGridCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes."""
logs = get_logging_container()
stdout, parsed_data, logs = se... | the_stack_v2_python_sparse | src/aiida_quantumespresso/parsers/open_grid.py | aiidateam/aiida-quantumespresso | train | 56 |
e28b743f83ad33a9f58acc3d66970f9faa84e530 | [
"if not matrix:\n self.sumMatrix = []\n return\nrows = len(matrix) + 1\ncols = len(matrix[0]) + 1\nself.sumMatrix = [[0 for __ in range(cols)] for __ in range(rows)]\nfor r in range(1, rows):\n for c in range(1, cols):\n self.sumMatrix[r][c] = self.sumMatrix[r - 1][c] + matrix[r - 1][c - 1]\nfor r i... | <|body_start_0|>
if not matrix:
self.sumMatrix = []
return
rows = len(matrix) + 1
cols = len(matrix[0]) + 1
self.sumMatrix = [[0 for __ in range(cols)] for __ in range(rows)]
for r in range(1, rows):
for c in range(1, cols):
sel... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k_train_004924 | 1,334 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | e0f032f34f7fa8fa4f6e5af65c60b3fe581fdc23 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if not matrix:
self.sumMatrix = []
return
rows = len(matrix) + 1
cols = len(matrix[0]) + 1
self.sumMatrix = [[0 for __ in range(cols)]... | the_stack_v2_python_sparse | Range Sum Query 2D - Immutable.py | jke-zq/myleetcode.py | train | 4 | |
d545d7f91c3624a82a1f4d04bc964b15578272bd | [
"invest_page = Invest_SetUp[0]\ninvest_page.input_invest_amount(cases['amount'])\nres = invest_page.get_invest_button_text()\nassert cases['expected'] == res",
"invest_page = Invest_SetUp[0]\ninvest_page.input_invest_amount(cases['amount'])\ninvest_page.click_invest_button()\nres = invest_page.get_error_box_text(... | <|body_start_0|>
invest_page = Invest_SetUp[0]
invest_page.input_invest_amount(cases['amount'])
res = invest_page.get_invest_button_text()
assert cases['expected'] == res
<|end_body_0|>
<|body_start_1|>
invest_page = Invest_SetUp[0]
invest_page.input_invest_amount(cases[... | Test_Invest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Invest:
def test_invest_error_info_button(self, cases, Invest_SetUp):
"""投标失败,button错误提示 :param Invest_SetUp: :return:"""
<|body_0|>
def test_invest_error_windows_button(self, cases, Invest_SetUp):
"""投标失败,button错误提示 :param Invest_SetUp: :return:"""
<|bo... | stack_v2_sparse_classes_36k_train_004925 | 2,575 | no_license | [
{
"docstring": "投标失败,button错误提示 :param Invest_SetUp: :return:",
"name": "test_invest_error_info_button",
"signature": "def test_invest_error_info_button(self, cases, Invest_SetUp)"
},
{
"docstring": "投标失败,button错误提示 :param Invest_SetUp: :return:",
"name": "test_invest_error_windows_button",
... | 3 | stack_v2_sparse_classes_30k_train_000765 | Implement the Python class `Test_Invest` described below.
Class description:
Implement the Test_Invest class.
Method signatures and docstrings:
- def test_invest_error_info_button(self, cases, Invest_SetUp): 投标失败,button错误提示 :param Invest_SetUp: :return:
- def test_invest_error_windows_button(self, cases, Invest_SetUp... | Implement the Python class `Test_Invest` described below.
Class description:
Implement the Test_Invest class.
Method signatures and docstrings:
- def test_invest_error_info_button(self, cases, Invest_SetUp): 投标失败,button错误提示 :param Invest_SetUp: :return:
- def test_invest_error_windows_button(self, cases, Invest_SetUp... | 205e87bc659bb69c7480457c19bd5d166d26a085 | <|skeleton|>
class Test_Invest:
def test_invest_error_info_button(self, cases, Invest_SetUp):
"""投标失败,button错误提示 :param Invest_SetUp: :return:"""
<|body_0|>
def test_invest_error_windows_button(self, cases, Invest_SetUp):
"""投标失败,button错误提示 :param Invest_SetUp: :return:"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_Invest:
def test_invest_error_info_button(self, cases, Invest_SetUp):
"""投标失败,button错误提示 :param Invest_SetUp: :return:"""
invest_page = Invest_SetUp[0]
invest_page.input_invest_amount(cases['amount'])
res = invest_page.get_invest_button_text()
assert cases['expecte... | the_stack_v2_python_sparse | py31_web_qianchengdai/testcase/future_loan/test_invest_case.py | jianyi666/py31_web_qianchengdai | train | 0 | |
62bba570c93f1e8d970a31e471280a1c3c91e098 | [
"super(XnatEmptyPopup, self).__init__(self)\nself.spacer = qt.QLabel('\\n\\n\\n')\nself.windowTitle = title\nself.setWindowModality(modality)\nself.hide()\nself.masterLayout = qt.QFormLayout()\nself.setLayout(self.masterLayout)",
"self.raise_()\nqt.QWidget.show(self)\nXnatSlicerUtils.repositionToMainSlicerWindow(... | <|body_start_0|>
super(XnatEmptyPopup, self).__init__(self)
self.spacer = qt.QLabel('\n\n\n')
self.windowTitle = title
self.setWindowModality(modality)
self.hide()
self.masterLayout = qt.QFormLayout()
self.setLayout(self.masterLayout)
<|end_body_0|>
<|body_start_... | Popup class for XNAT-relevant interactions | XnatEmptyPopup | [
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XnatEmptyPopup:
"""Popup class for XNAT-relevant interactions"""
def __init__(self, title='Popup', modality=1):
"""Init function."""
<|body_0|>
def show(self, position=True):
"""Generic show function. Repositions the popup to be cenetered within the slicer app.""... | stack_v2_sparse_classes_36k_train_004926 | 16,351 | permissive | [
{
"docstring": "Init function.",
"name": "__init__",
"signature": "def __init__(self, title='Popup', modality=1)"
},
{
"docstring": "Generic show function. Repositions the popup to be cenetered within the slicer app.",
"name": "show",
"signature": "def show(self, position=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013848 | Implement the Python class `XnatEmptyPopup` described below.
Class description:
Popup class for XNAT-relevant interactions
Method signatures and docstrings:
- def __init__(self, title='Popup', modality=1): Init function.
- def show(self, position=True): Generic show function. Repositions the popup to be cenetered wit... | Implement the Python class `XnatEmptyPopup` described below.
Class description:
Popup class for XNAT-relevant interactions
Method signatures and docstrings:
- def __init__(self, title='Popup', modality=1): Init function.
- def show(self, position=True): Generic show function. Repositions the popup to be cenetered wit... | 06867037842e2a074ae5ed3b0bdf4bf016a231a5 | <|skeleton|>
class XnatEmptyPopup:
"""Popup class for XNAT-relevant interactions"""
def __init__(self, title='Popup', modality=1):
"""Init function."""
<|body_0|>
def show(self, position=True):
"""Generic show function. Repositions the popup to be cenetered within the slicer app.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XnatEmptyPopup:
"""Popup class for XNAT-relevant interactions"""
def __init__(self, title='Popup', modality=1):
"""Init function."""
super(XnatEmptyPopup, self).__init__(self)
self.spacer = qt.QLabel('\n\n\n')
self.windowTitle = title
self.setWindowModality(modalit... | the_stack_v2_python_sparse | XNATSlicer/XnatSlicerLib/ui/Popup.py | NrgXnat/XNATSlicer | train | 4 |
fc826f3942a48e40b3d6d601724478cb1cdc057e | [
"left, right = (nums[0], nums[nums[0]])\nwhile left != right:\n left = nums[left]\n right = nums[nums[right]]\nstart = 0\nwhile start != left:\n start = nums[start]\n left = nums[left]\nreturn start",
"pre = 0\nwhile nums[0] != pre:\n pre = nums[0]\n nums[0] = nums[pre]\n nums[pre] = pre\nret... | <|body_start_0|>
left, right = (nums[0], nums[nums[0]])
while left != right:
left = nums[left]
right = nums[nums[right]]
start = 0
while start != left:
start = nums[start]
left = nums[left]
return start
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""思路:快慢指针 1、通过下标获取下一个元素,存在重复的值,相当于链表有环 2、第一次循环找到相遇的点,这个点不一定是链表的入口 3、起点和相遇的点离链表交点的距离相等"""
<|body_0|>
def findDuplicate2(self, nums: List[int]) -> int:
"""如果可以改变nums的话 :param nums: :return:"""
<|body_1... | stack_v2_sparse_classes_36k_train_004927 | 3,490 | no_license | [
{
"docstring": "思路:快慢指针 1、通过下标获取下一个元素,存在重复的值,相当于链表有环 2、第一次循环找到相遇的点,这个点不一定是链表的入口 3、起点和相遇的点离链表交点的距离相等",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums: List[int]) -> int"
},
{
"docstring": "如果可以改变nums的话 :param nums: :return:",
"name": "findDuplicate2",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_000842 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: 思路:快慢指针 1、通过下标获取下一个元素,存在重复的值,相当于链表有环 2、第一次循环找到相遇的点,这个点不一定是链表的入口 3、起点和相遇的点离链表交点的距离相等
- def findDuplicate2(self, nums: List[int]) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: 思路:快慢指针 1、通过下标获取下一个元素,存在重复的值,相当于链表有环 2、第一次循环找到相遇的点,这个点不一定是链表的入口 3、起点和相遇的点离链表交点的距离相等
- def findDuplicate2(self, nums: List[int]) -... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""思路:快慢指针 1、通过下标获取下一个元素,存在重复的值,相当于链表有环 2、第一次循环找到相遇的点,这个点不一定是链表的入口 3、起点和相遇的点离链表交点的距离相等"""
<|body_0|>
def findDuplicate2(self, nums: List[int]) -> int:
"""如果可以改变nums的话 :param nums: :return:"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""思路:快慢指针 1、通过下标获取下一个元素,存在重复的值,相当于链表有环 2、第一次循环找到相遇的点,这个点不一定是链表的入口 3、起点和相遇的点离链表交点的距离相等"""
left, right = (nums[0], nums[nums[0]])
while left != right:
left = nums[left]
right = nums[nums[right]]
s... | the_stack_v2_python_sparse | LeetCode/双指针(two points)/287. Find the Duplicate Number.py | yiming1012/MyLeetCode | train | 2 | |
dca1aff0227ebd0bcfb5a09818e0be91b9b363fc | [
"challenge_mgr.init()\nself.user = test_utils.setup_user(username='user', password='changeme')\nchallenge_mgr.register_page_widget('learn', 'smartgrid')\nchallenge_mgr.register_page_widget('learn', 'scoreboard')\ncache_mgr.clear()\nself.client.login(username='user', password='changeme')",
"test_utils.set_competit... | <|body_start_0|>
challenge_mgr.init()
self.user = test_utils.setup_user(username='user', password='changeme')
challenge_mgr.register_page_widget('learn', 'smartgrid')
challenge_mgr.register_page_widget('learn', 'scoreboard')
cache_mgr.clear()
self.client.login(username='u... | Scoreboard Test. | ScoreboardTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScoreboardTest:
"""Scoreboard Test."""
def setUp(self):
"""setup"""
<|body_0|>
def testScoreboard(self):
"""Test that the scoreboard loads current round information."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
challenge_mgr.init()
se... | stack_v2_sparse_classes_36k_train_004928 | 2,564 | permissive | [
{
"docstring": "setup",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the scoreboard loads current round information.",
"name": "testScoreboard",
"signature": "def testScoreboard(self)"
}
] | 2 | null | Implement the Python class `ScoreboardTest` described below.
Class description:
Scoreboard Test.
Method signatures and docstrings:
- def setUp(self): setup
- def testScoreboard(self): Test that the scoreboard loads current round information. | Implement the Python class `ScoreboardTest` described below.
Class description:
Scoreboard Test.
Method signatures and docstrings:
- def setUp(self): setup
- def testScoreboard(self): Test that the scoreboard loads current round information.
<|skeleton|>
class ScoreboardTest:
"""Scoreboard Test."""
def setU... | 4b7dd685012ec64758affe0ecee3103596d16aa7 | <|skeleton|>
class ScoreboardTest:
"""Scoreboard Test."""
def setUp(self):
"""setup"""
<|body_0|>
def testScoreboard(self):
"""Test that the scoreboard loads current round information."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScoreboardTest:
"""Scoreboard Test."""
def setUp(self):
"""setup"""
challenge_mgr.init()
self.user = test_utils.setup_user(username='user', password='changeme')
challenge_mgr.register_page_widget('learn', 'smartgrid')
challenge_mgr.register_page_widget('learn', 'sc... | the_stack_v2_python_sparse | makahiki/apps/widgets/group_status_scoreboard/tests.py | justinslee/Wai-Not-Makahiki | train | 1 |
624da4dcc8c6a8ae5c6a0d01e5663e0216d964ca | [
"super(DropStripes, self).__init__()\nassert dim in [2, 3]\nself.dim = dim\nself.drop_width = drop_width\nself.stripes_num = stripes_num",
"assert input.ndimension() == 4\nif self.training is False:\n return input\nelse:\n batch_size = input.shape[0]\n total_width = input.shape[self.dim]\n for n in ra... | <|body_start_0|>
super(DropStripes, self).__init__()
assert dim in [2, 3]
self.dim = dim
self.drop_width = drop_width
self.stripes_num = stripes_num
<|end_body_0|>
<|body_start_1|>
assert input.ndimension() == 4
if self.training is False:
return input... | DropStripes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input):
"""input... | stack_v2_sparse_classes_36k_train_004929 | 25,139 | no_license | [
{
"docstring": "Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop",
"name": "__init__",
"signature": "def __init__(self, dim, drop_width, stripes_num)"
},
{
"docstring": "input: (batch_size, ch... | 3 | stack_v2_sparse_classes_30k_train_015737 | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | 7ab627aefa56525735684b6671918d7c7db1cc07 | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input):
"""input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
super(DropStripes, self).__init__()
assert dim in [2, 3]
... | the_stack_v2_python_sparse | easy_gold/pann_utils.py | wdy06/kaggle-birdsong-recognition | train | 1 | |
7c3a6835a01812076386f7ca337b95c83fbffbb8 | [
"result = super(AliasDetailView, self).has_permission()\nif not result:\n return result\nreturn self.request.user.can_access(self.get_object())",
"context = super(AliasDetailView, self).get_context_data(**kwargs)\ncontext['selection'] = 'identities'\nreturn context"
] | <|body_start_0|>
result = super(AliasDetailView, self).has_permission()
if not result:
return result
return self.request.user.can_access(self.get_object())
<|end_body_0|>
<|body_start_1|>
context = super(AliasDetailView, self).get_context_data(**kwargs)
context['sele... | DetailView for Alias. | AliasDetailView | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliasDetailView:
"""DetailView for Alias."""
def has_permission(self):
"""Check object-level access."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Add information to context."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = supe... | stack_v2_sparse_classes_36k_train_004930 | 4,058 | permissive | [
{
"docstring": "Check object-level access.",
"name": "has_permission",
"signature": "def has_permission(self)"
},
{
"docstring": "Add information to context.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | null | Implement the Python class `AliasDetailView` described below.
Class description:
DetailView for Alias.
Method signatures and docstrings:
- def has_permission(self): Check object-level access.
- def get_context_data(self, **kwargs): Add information to context. | Implement the Python class `AliasDetailView` described below.
Class description:
DetailView for Alias.
Method signatures and docstrings:
- def has_permission(self): Check object-level access.
- def get_context_data(self, **kwargs): Add information to context.
<|skeleton|>
class AliasDetailView:
"""DetailView for... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class AliasDetailView:
"""DetailView for Alias."""
def has_permission(self):
"""Check object-level access."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Add information to context."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AliasDetailView:
"""DetailView for Alias."""
def has_permission(self):
"""Check object-level access."""
result = super(AliasDetailView, self).has_permission()
if not result:
return result
return self.request.user.can_access(self.get_object())
def get_conte... | the_stack_v2_python_sparse | modoboa/admin/views/alias.py | modoboa/modoboa | train | 2,201 |
c74194858f673648650f1f6b6e96b1a6dca3981e | [
"try:\n service.JobManager().regit_job(nnid, const.JOB_TYPE_DF_PRE_PROCESS)\n return_data = {'status': '200', 'result': tb}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '400', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n ... | <|body_start_0|>
try:
service.JobManager().regit_job(nnid, const.JOB_TYPE_DF_PRE_PROCESS)
return_data = {'status': '200', 'result': tb}
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '400', 'result': str(e)}
... | 1. POST : 2. PUT : 3. GET : 4. DELETE : | DataFramePre | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFramePre:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid, tb, nnid):
"""create table column distinct data :param request: Not used :param baseid: schemaId :return: create schema result"""
<|body_0|>
def get(self, request, baseid, tb, nni... | stack_v2_sparse_classes_36k_train_004931 | 2,632 | no_license | [
{
"docstring": "create table column distinct data :param request: Not used :param baseid: schemaId :return: create schema result",
"name": "post",
"signature": "def post(self, request, baseid, tb, nnid)"
},
{
"docstring": "return all table :param request: Not used :param baseid: schemaId :return... | 4 | stack_v2_sparse_classes_30k_train_009790 | Implement the Python class `DataFramePre` described below.
Class description:
1. POST : 2. PUT : 3. GET : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, baseid, tb, nnid): create table column distinct data :param request: Not used :param baseid: schemaId :return: create schema result
- def ge... | Implement the Python class `DataFramePre` described below.
Class description:
1. POST : 2. PUT : 3. GET : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, baseid, tb, nnid): create table column distinct data :param request: Not used :param baseid: schemaId :return: create schema result
- def ge... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class DataFramePre:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid, tb, nnid):
"""create table column distinct data :param request: Not used :param baseid: schemaId :return: create schema result"""
<|body_0|>
def get(self, request, baseid, tb, nni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataFramePre:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid, tb, nnid):
"""create table column distinct data :param request: Not used :param baseid: schemaId :return: create schema result"""
try:
service.JobManager().regit_job(nnid, const.JOB_TYP... | the_stack_v2_python_sparse | tfmsarest/views/dataframe_preprocess.py | TensorMSA/tensormsa_old | train | 6 |
66bdb5fcdfce90314e43760d276bcf93ba639532 | [
"if not username:\n raise ValueError('Users must have an username address')\nuser = self.model(email=email, username=username, first_name=first_name, last_name=last_name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, username, password=password)\nuser.is... | <|body_start_0|>
if not username:
raise ValueError('Users must have an username address')
user = self.model(email=email, username=username, first_name=first_name, last_name=last_name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|... | AccountManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountManager:
def create_user(self, email, username, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password):
"""Creates and s... | stack_v2_sparse_classes_36k_train_004932 | 7,081 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, username, first_name=None, last_name=None, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of... | 2 | stack_v2_sparse_classes_30k_train_020039 | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, username, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, date of birth and password.
- d... | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, username, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, date of birth and password.
- d... | 21f16fde395a1c5ab64ba9bfc02373454389d073 | <|skeleton|>
class AccountManager:
def create_user(self, email, username, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password):
"""Creates and s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountManager:
def create_user(self, email, username, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not username:
raise ValueError('Users must have an username address')
user = self.mode... | the_stack_v2_python_sparse | service-python/authserver/accounts/models.py | firmanJS/picasso-backend | train | 1 | |
35eaf42c7d7cee40a5d6cb5100fdc8e337979bd4 | [
"super().__init__(config=config, **kw)\nself.default_languages.update(self.languages)\nany_language = '|'.join(self.default_languages.keys())\nself.re_magic_language = re.compile(f'^\\\\s*({any_language})\\\\s+')",
"m = self.re_magic_language.match(source)\nif m:\n return self.default_languages[m.group(1)]\nel... | <|body_start_0|>
super().__init__(config=config, **kw)
self.default_languages.update(self.languages)
any_language = '|'.join(self.default_languages.keys())
self.re_magic_language = re.compile(f'^\\s*({any_language})\\s+')
<|end_body_0|>
<|body_start_1|>
m = self.re_magic_languag... | Detects and tags code cells that use a different languages than Python. | HighlightMagicsPreprocessor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighlightMagicsPreprocessor:
"""Detects and tags code cells that use a different languages than Python."""
def __init__(self, config=None, **kw):
"""Public constructor"""
<|body_0|>
def which_magic_language(self, source):
"""When a cell uses another language thro... | stack_v2_sparse_classes_36k_train_004933 | 3,216 | permissive | [
{
"docstring": "Public constructor",
"name": "__init__",
"signature": "def __init__(self, config=None, **kw)"
},
{
"docstring": "When a cell uses another language through a magic extension, the other language is returned. If no language magic is detected, this function returns None. Parameters -... | 3 | stack_v2_sparse_classes_30k_train_011154 | Implement the Python class `HighlightMagicsPreprocessor` described below.
Class description:
Detects and tags code cells that use a different languages than Python.
Method signatures and docstrings:
- def __init__(self, config=None, **kw): Public constructor
- def which_magic_language(self, source): When a cell uses ... | Implement the Python class `HighlightMagicsPreprocessor` described below.
Class description:
Detects and tags code cells that use a different languages than Python.
Method signatures and docstrings:
- def __init__(self, config=None, **kw): Public constructor
- def which_magic_language(self, source): When a cell uses ... | 51c6e0a7d40918366e2a68c5ea471fd2c65722cb | <|skeleton|>
class HighlightMagicsPreprocessor:
"""Detects and tags code cells that use a different languages than Python."""
def __init__(self, config=None, **kw):
"""Public constructor"""
<|body_0|>
def which_magic_language(self, source):
"""When a cell uses another language thro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HighlightMagicsPreprocessor:
"""Detects and tags code cells that use a different languages than Python."""
def __init__(self, config=None, **kw):
"""Public constructor"""
super().__init__(config=config, **kw)
self.default_languages.update(self.languages)
any_language = '|'... | the_stack_v2_python_sparse | nbconvert/preprocessors/highlightmagics.py | jupyter/nbconvert | train | 1,645 |
ca8265ad5bd648fde6304471e3c9867be0aca172 | [
"super(Suppressor, self).__init__()\nif limb not in ['left', 'right']:\n raise ValueError(\"'limb' must be 'left' or 'right'!\")\nself._stop = False\nself._pub = rospy.Publisher('robot/limb/' + limb + name, Empty, queue_size=10)",
"while not rospy.is_shutdown() and (not self._stop):\n self._pub.publish()\n ... | <|body_start_0|>
super(Suppressor, self).__init__()
if limb not in ['left', 'right']:
raise ValueError("'limb' must be 'left' or 'right'!")
self._stop = False
self._pub = rospy.Publisher('robot/limb/' + limb + name, Empty, queue_size=10)
<|end_body_0|>
<|body_start_1|>
... | Suppressor | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Suppressor:
def __init__(self, limb, name):
"""Suppressing collision avoidance or collision detection on one of baxter's limbs using a separate thread. :param limb: The limb to suppress functionality on. :param name: The string identifying the functionality. :return: A Suppressor Thread ... | stack_v2_sparse_classes_36k_train_004934 | 3,320 | permissive | [
{
"docstring": "Suppressing collision avoidance or collision detection on one of baxter's limbs using a separate thread. :param limb: The limb to suppress functionality on. :param name: The string identifying the functionality. :return: A Suppressor Thread instance.",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_018136 | Implement the Python class `Suppressor` described below.
Class description:
Implement the Suppressor class.
Method signatures and docstrings:
- def __init__(self, limb, name): Suppressing collision avoidance or collision detection on one of baxter's limbs using a separate thread. :param limb: The limb to suppress fun... | Implement the Python class `Suppressor` described below.
Class description:
Implement the Suppressor class.
Method signatures and docstrings:
- def __init__(self, limb, name): Suppressing collision avoidance or collision detection on one of baxter's limbs using a separate thread. :param limb: The limb to suppress fun... | a0f458ebc6eb4671bf9346571848daf5ce433505 | <|skeleton|>
class Suppressor:
def __init__(self, limb, name):
"""Suppressing collision avoidance or collision detection on one of baxter's limbs using a separate thread. :param limb: The limb to suppress functionality on. :param name: The string identifying the functionality. :return: A Suppressor Thread ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Suppressor:
def __init__(self, limb, name):
"""Suppressing collision avoidance or collision detection on one of baxter's limbs using a separate thread. :param limb: The limb to suppress functionality on. :param name: The string identifying the functionality. :return: A Suppressor Thread instance."""
... | the_stack_v2_python_sparse | src/baxter_data_acquisition/suppression.py | birlrobotics/baxter_data_acquisition | train | 0 | |
cc92c9037866377923284d7f25a73750fdce8fd2 | [
"self.family = family\nself.k = k\nself.dist_thres = dist_thres\nself.dist_fn = dist_fn\nP1 = self.family.P1(dist_thres)\nif P1 == 1.0:\n self.num_tables = 1\nelse:\n self.num_tables = math.log(1.0 - reporting_prob, 1.0 - math.pow(P1, k))\n self.num_tables = int(math.ceil(self.num_tables))\nself.hashtables... | <|body_start_0|>
self.family = family
self.k = k
self.dist_thres = dist_thres
self.dist_fn = dist_fn
P1 = self.family.P1(dist_thres)
if P1 == 1.0:
self.num_tables = 1
else:
self.num_tables = math.log(1.0 - reporting_prob, 1.0 - math.pow(P1,... | Support for approximate near neighbor lookups. This implements the R-near neighbor reporting problem described in Andoni and Indyk 2008. | NearNeighborLookup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NearNeighborLookup:
"""Support for approximate near neighbor lookups. This implements the R-near neighbor reporting problem described in Andoni and Indyk 2008."""
def __init__(self, family, k, dist_thres, dist_fn, reporting_prob):
"""This selects a number of hash tables (defined as L... | stack_v2_sparse_classes_36k_train_004935 | 12,499 | permissive | [
{
"docstring": "This selects a number of hash tables (defined as L in the above reference) according to the strategy it outlines: we want any neighbor (within dist_thres) of a query to be reported with probability at least reporting_prob; thus, the number of tables should be [log_{1 - (P1)^k} (1 - reporting_pro... | 3 | stack_v2_sparse_classes_30k_train_007078 | Implement the Python class `NearNeighborLookup` described below.
Class description:
Support for approximate near neighbor lookups. This implements the R-near neighbor reporting problem described in Andoni and Indyk 2008.
Method signatures and docstrings:
- def __init__(self, family, k, dist_thres, dist_fn, reporting_... | Implement the Python class `NearNeighborLookup` described below.
Class description:
Support for approximate near neighbor lookups. This implements the R-near neighbor reporting problem described in Andoni and Indyk 2008.
Method signatures and docstrings:
- def __init__(self, family, k, dist_thres, dist_fn, reporting_... | 9c4696c28e32fd102fbae30c55a9470cb2ad8d3d | <|skeleton|>
class NearNeighborLookup:
"""Support for approximate near neighbor lookups. This implements the R-near neighbor reporting problem described in Andoni and Indyk 2008."""
def __init__(self, family, k, dist_thres, dist_fn, reporting_prob):
"""This selects a number of hash tables (defined as L... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NearNeighborLookup:
"""Support for approximate near neighbor lookups. This implements the R-near neighbor reporting problem described in Andoni and Indyk 2008."""
def __init__(self, family, k, dist_thres, dist_fn, reporting_prob):
"""This selects a number of hash tables (defined as L in the above... | the_stack_v2_python_sparse | catch/utils/lsh.py | broadinstitute/catch | train | 69 |
2b4ae57432622ad8a899a86fda1db654d300ee4f | [
"if search_text(u'接受'):\n click_button_by_text(u'接受')\n self.operate_guidepage()\nfunc = lambda: get_activity_name() == 'com.baidu.BaiduMap.map.mainmap.MainMapActivity'\nif not wait_for_fun(func, True, 15):\n set_cannot_continue()\n return\nregister_update_watcher('com.android.BaiduMap', VIEW_BUTTON, ID... | <|body_start_0|>
if search_text(u'接受'):
click_button_by_text(u'接受')
self.operate_guidepage()
func = lambda: get_activity_name() == 'com.baidu.BaiduMap.map.mainmap.MainMapActivity'
if not wait_for_fun(func, True, 15):
set_cannot_continue()
return
... | test_suit_settings_case1 is a class for baidumap case. @see: L{TestCaseBase <TestCaseBase>} | test_suit_baidumap_case1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_suit_baidumap_case1:
"""test_suit_settings_case1 is a class for baidumap case. @see: L{TestCaseBase <TestCaseBase>}"""
def test_case_main(self, case_results):
"""main entry. @type case_results: tuple @param case_results: record some case result information"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_004936 | 2,759 | no_license | [
{
"docstring": "main entry. @type case_results: tuple @param case_results: record some case result information",
"name": "test_case_main",
"signature": "def test_case_main(self, case_results)"
},
{
"docstring": "operation guidepage.",
"name": "operate_guidepage",
"signature": "def operat... | 2 | null | Implement the Python class `test_suit_baidumap_case1` described below.
Class description:
test_suit_settings_case1 is a class for baidumap case. @see: L{TestCaseBase <TestCaseBase>}
Method signatures and docstrings:
- def test_case_main(self, case_results): main entry. @type case_results: tuple @param case_results: r... | Implement the Python class `test_suit_baidumap_case1` described below.
Class description:
test_suit_settings_case1 is a class for baidumap case. @see: L{TestCaseBase <TestCaseBase>}
Method signatures and docstrings:
- def test_case_main(self, case_results): main entry. @type case_results: tuple @param case_results: r... | a04b717ae437511abae1e7e9e399373c161a7b65 | <|skeleton|>
class test_suit_baidumap_case1:
"""test_suit_settings_case1 is a class for baidumap case. @see: L{TestCaseBase <TestCaseBase>}"""
def test_case_main(self, case_results):
"""main entry. @type case_results: tuple @param case_results: record some case result information"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_suit_baidumap_case1:
"""test_suit_settings_case1 is a class for baidumap case. @see: L{TestCaseBase <TestCaseBase>}"""
def test_case_main(self, case_results):
"""main entry. @type case_results: tuple @param case_results: record some case result information"""
if search_text(u'接受'):
... | the_stack_v2_python_sparse | test_env/test_suit_baidumap/test_suit_baidumap_case1.py | wwlwwlqaz/Qualcomm | train | 1 |
931123ce17366095f6b9abc9b5fb25a477e16422 | [
"from collections import Counter\nans = 0\ni = 0\nn = len(s)\nfor i in range(n):\n for j in range(i + 1, n):\n substr = s[i:j + 1]\n c = Counter(substr)\n if len(c) <= 2:\n ans = max(ans, len(substr))\nprint(ans)\nreturn ans",
"from collections import deque, Counter\nqueue = deq... | <|body_start_0|>
from collections import Counter
ans = 0
i = 0
n = len(s)
for i in range(n):
for j in range(i + 1, n):
substr = s[i:j + 1]
c = Counter(substr)
if len(c) <= 2:
ans = max(ans, len(substr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def characterReplacement(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def characterReplacement_deque(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from collecti... | stack_v2_sparse_classes_36k_train_004937 | 2,149 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "characterReplacement",
"signature": "def characterReplacement(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "characterReplacement_deque",
"signature": "def characterReplacement_deque(self, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def characterReplacement(self, s, k): :type s: str :type k: int :rtype: int
- def characterReplacement_deque(self, s, k): :type s: str :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def characterReplacement(self, s, k): :type s: str :type k: int :rtype: int
- def characterReplacement_deque(self, s, k): :type s: str :type k: int :rtype: int
<|skeleton|>
clas... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def characterReplacement(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def characterReplacement_deque(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def characterReplacement(self, s, k):
""":type s: str :type k: int :rtype: int"""
from collections import Counter
ans = 0
i = 0
n = len(s)
for i in range(n):
for j in range(i + 1, n):
substr = s[i:j + 1]
c = ... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00424.Longest Repeating Character Replacement.py | roger6blog/LeetCode | train | 0 | |
c24a333d4228d3898e8d0ab20b12c8120265dd08 | [
"assert len(args) == 1\nx = args[0]\nreturn 1 - x",
"assert len(args) == 1\nx = args[0]\nreturn np.sqrt(1 - np.square(x))",
"assert len(args) == 1\nx = args[0]\nreturn 1 - np.square(x)",
"if name == 'standard':\n return cls(cls.standard).get\nelif name == 'circle':\n return cls(cls.circle).get\nelif nam... | <|body_start_0|>
assert len(args) == 1
x = args[0]
return 1 - x
<|end_body_0|>
<|body_start_1|>
assert len(args) == 1
x = args[0]
return np.sqrt(1 - np.square(x))
<|end_body_1|>
<|body_start_2|>
assert len(args) == 1
x = args[0]
return 1 - np.squ... | Fuzzy negator. | Negator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Negator:
"""Fuzzy negator."""
def standard(*args):
"""Standard negator. Arguments: x Input fuzzy value."""
<|body_0|>
def circle(*args):
"""Circle negator. Arguments: x Input fuzzy value."""
<|body_1|>
def parabolic(*args):
"""Parabolic negat... | stack_v2_sparse_classes_36k_train_004938 | 7,372 | no_license | [
{
"docstring": "Standard negator. Arguments: x Input fuzzy value.",
"name": "standard",
"signature": "def standard(*args)"
},
{
"docstring": "Circle negator. Arguments: x Input fuzzy value.",
"name": "circle",
"signature": "def circle(*args)"
},
{
"docstring": "Parabolic negator.... | 4 | null | Implement the Python class `Negator` described below.
Class description:
Fuzzy negator.
Method signatures and docstrings:
- def standard(*args): Standard negator. Arguments: x Input fuzzy value.
- def circle(*args): Circle negator. Arguments: x Input fuzzy value.
- def parabolic(*args): Parabolic negator. Arguments: ... | Implement the Python class `Negator` described below.
Class description:
Fuzzy negator.
Method signatures and docstrings:
- def standard(*args): Standard negator. Arguments: x Input fuzzy value.
- def circle(*args): Circle negator. Arguments: x Input fuzzy value.
- def parabolic(*args): Parabolic negator. Arguments: ... | 1c2c3abe50bd9125b105ffd13eef513839f3f9d8 | <|skeleton|>
class Negator:
"""Fuzzy negator."""
def standard(*args):
"""Standard negator. Arguments: x Input fuzzy value."""
<|body_0|>
def circle(*args):
"""Circle negator. Arguments: x Input fuzzy value."""
<|body_1|>
def parabolic(*args):
"""Parabolic negat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Negator:
"""Fuzzy negator."""
def standard(*args):
"""Standard negator. Arguments: x Input fuzzy value."""
assert len(args) == 1
x = args[0]
return 1 - x
def circle(*args):
"""Circle negator. Arguments: x Input fuzzy value."""
assert len(args) == 1
... | the_stack_v2_python_sparse | monitor/fuzzy.py | martinbenes1996/bc | train | 0 |
1c5a2cc22093dbf4b7724e08cd50bf01c3274957 | [
"super().__init__(logger, {})\nself.bot = bot\nself.mod_name = mod_name\nif module.logger_level:\n self.setLevel(module.logger_level)\n\" custom handlers dont work\\n if module.config.get('logger_handler'):\\n df = DictConfigurator(bot.logging_config)\\n handler_config = bot.logging_... | <|body_start_0|>
super().__init__(logger, {})
self.bot = bot
self.mod_name = mod_name
if module.logger_level:
self.setLevel(module.logger_level)
" custom handlers dont work\n if module.config.get('logger_handler'):\n df = DictConfigurator(bot.logging... | Custom Logger Adapter to add some context data and more control on DotFlow extensions logging behavior | BBotLoggerAdapter | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BBotLoggerAdapter:
"""Custom Logger Adapter to add some context data and more control on DotFlow extensions logging behavior"""
def __init__(self, logger, module: object, bot, mod_name=''):
""":param logger: :param module: :param bot: :param mod_name:"""
<|body_0|>
def p... | stack_v2_sparse_classes_36k_train_004939 | 19,616 | permissive | [
{
"docstring": ":param logger: :param module: :param bot: :param mod_name:",
"name": "__init__",
"signature": "def __init__(self, logger, module: object, bot, mod_name='')"
},
{
"docstring": ":param msg: :param kwargs: :return:",
"name": "process",
"signature": "def process(self, msg, kw... | 2 | null | Implement the Python class `BBotLoggerAdapter` described below.
Class description:
Custom Logger Adapter to add some context data and more control on DotFlow extensions logging behavior
Method signatures and docstrings:
- def __init__(self, logger, module: object, bot, mod_name=''): :param logger: :param module: :par... | Implement the Python class `BBotLoggerAdapter` described below.
Class description:
Custom Logger Adapter to add some context data and more control on DotFlow extensions logging behavior
Method signatures and docstrings:
- def __init__(self, logger, module: object, bot, mod_name=''): :param logger: :param module: :par... | b94ef5e75411ac4a214f5ac54d04ce00d9108ec0 | <|skeleton|>
class BBotLoggerAdapter:
"""Custom Logger Adapter to add some context data and more control on DotFlow extensions logging behavior"""
def __init__(self, logger, module: object, bot, mod_name=''):
""":param logger: :param module: :param bot: :param mod_name:"""
<|body_0|>
def p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BBotLoggerAdapter:
"""Custom Logger Adapter to add some context data and more control on DotFlow extensions logging behavior"""
def __init__(self, logger, module: object, bot, mod_name=''):
""":param logger: :param module: :param bot: :param mod_name:"""
super().__init__(logger, {})
... | the_stack_v2_python_sparse | bbot/core.py | SeedVault/rhizome | train | 8 |
63013c9c8a3e4d6f1f789cef4f838f4c0005421c | [
"node = head\nwhile node:\n if node.next is None:\n break\n node = node.next\nreturn node",
"result = 0\nnode = head\nwhile node:\n result += 1\n if node.next is None:\n break\n node = node.next\nreturn result",
"if head is None:\n return None\ncount = 1\nnode = head\nwhile count... | <|body_start_0|>
node = head
while node:
if node.next is None:
break
node = node.next
return node
<|end_body_0|>
<|body_start_1|>
result = 0
node = head
while node:
result += 1
if node.next is None:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def tail(self, head):
""">>> s = Solution() >>> head = LinkedList.fromList([1, 2, 3]) >>> result = s.tail(head) >>> result.val 3 >>> head = LinkedList.fromList([]) >>> result = s.tail(head) >>> result >>> head = LinkedList.fromList([1]) >>> result = s.tail(head) >>> result.val ... | stack_v2_sparse_classes_36k_train_004940 | 2,651 | no_license | [
{
"docstring": ">>> s = Solution() >>> head = LinkedList.fromList([1, 2, 3]) >>> result = s.tail(head) >>> result.val 3 >>> head = LinkedList.fromList([]) >>> result = s.tail(head) >>> result >>> head = LinkedList.fromList([1]) >>> result = s.tail(head) >>> result.val 1",
"name": "tail",
"signature": "d... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tail(self, head): >>> s = Solution() >>> head = LinkedList.fromList([1, 2, 3]) >>> result = s.tail(head) >>> result.val 3 >>> head = LinkedList.fromList([]) >>> result = s.ta... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tail(self, head): >>> s = Solution() >>> head = LinkedList.fromList([1, 2, 3]) >>> result = s.tail(head) >>> result.val 3 >>> head = LinkedList.fromList([]) >>> result = s.ta... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def tail(self, head):
""">>> s = Solution() >>> head = LinkedList.fromList([1, 2, 3]) >>> result = s.tail(head) >>> result.val 3 >>> head = LinkedList.fromList([]) >>> result = s.tail(head) >>> result >>> head = LinkedList.fromList([1]) >>> result = s.tail(head) >>> result.val ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def tail(self, head):
""">>> s = Solution() >>> head = LinkedList.fromList([1, 2, 3]) >>> result = s.tail(head) >>> result.val 3 >>> head = LinkedList.fromList([]) >>> result = s.tail(head) >>> result >>> head = LinkedList.fromList([1]) >>> result = s.tail(head) >>> result.val 1"""
n... | the_stack_v2_python_sparse | rotate_list.py | gsy/leetcode | train | 1 | |
2b9f7df4a2ca0427785ebde8f4eddc1b209da21c | [
"if os.name not in ('posix', 'nt'):\n raise RuntimeError(f\"Runtime system '{os.name}' not supported.\")\nself.stop_event = stop_event\nself.max_rate = max_rate\nif os.name == 'posix':\n import fcntl\n import termios\n self.fd = sys.stdin.fileno()\n self.oldterm = termios.tcgetattr(self.fd)\n newa... | <|body_start_0|>
if os.name not in ('posix', 'nt'):
raise RuntimeError(f"Runtime system '{os.name}' not supported.")
self.stop_event = stop_event
self.max_rate = max_rate
if os.name == 'posix':
import fcntl
import termios
self.fd = sys.stdi... | Catch a single character from standard input before it echoes to the screen. | Getch | [
"MIT",
"BSL-1.0",
"MPL-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Getch:
"""Catch a single character from standard input before it echoes to the screen."""
def __init__(self, stop_event: Optional[threading.Event]=None, max_rate: Optional[float]=None) -> None:
""":param stop_event: Event used to abort wanting for incoming character. Optional: Disabl... | stack_v2_sparse_classes_36k_train_004941 | 9,350 | permissive | [
{
"docstring": ":param stop_event: Event used to abort wanting for incoming character. Optional: Disabled by default. :param max_rate: Maximum fetch rate of `sys.stdin` stream. Using any value larger than 1ms avoid CPU throttling by releasing the GIL periodically for other threads. Optional: Disabled by default... | 3 | stack_v2_sparse_classes_30k_test_000415 | Implement the Python class `Getch` described below.
Class description:
Catch a single character from standard input before it echoes to the screen.
Method signatures and docstrings:
- def __init__(self, stop_event: Optional[threading.Event]=None, max_rate: Optional[float]=None) -> None: :param stop_event: Event used ... | Implement the Python class `Getch` described below.
Class description:
Catch a single character from standard input before it echoes to the screen.
Method signatures and docstrings:
- def __init__(self, stop_event: Optional[threading.Event]=None, max_rate: Optional[float]=None) -> None: :param stop_event: Event used ... | a3b244f0bcb21abe605544d1f5c4a31419946efd | <|skeleton|>
class Getch:
"""Catch a single character from standard input before it echoes to the screen."""
def __init__(self, stop_event: Optional[threading.Event]=None, max_rate: Optional[float]=None) -> None:
""":param stop_event: Event used to abort wanting for incoming character. Optional: Disabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Getch:
"""Catch a single character from standard input before it echoes to the screen."""
def __init__(self, stop_event: Optional[threading.Event]=None, max_rate: Optional[float]=None) -> None:
""":param stop_event: Event used to abort wanting for incoming character. Optional: Disabled by default... | the_stack_v2_python_sparse | python/gym_jiminy/common/gym_jiminy/common/envs/internal/play.py | duburcqa/jiminy | train | 108 |
a6e261d56170bc9119b8c9b18c1c2551c8c2a99f | [
"xbsy_url = '/'\nxbsy_urlName = '寻宝网首页'\nwith self.client.get(xbsy_url, headers=header, proxies=proxies, name=xbsy_urlName + xbsy_url, verify=False, allow_redirects=False, catch_response=True) as response:\n if 'navigation' in response.text:\n soup = BeautifulSoup(response.text, 'html.parser')\n sy... | <|body_start_0|>
xbsy_url = '/'
xbsy_urlName = '寻宝网首页'
with self.client.get(xbsy_url, headers=header, proxies=proxies, name=xbsy_urlName + xbsy_url, verify=False, allow_redirects=False, catch_response=True) as response:
if 'navigation' in response.text:
soup = Beautif... | XunBaoShouYe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XunBaoShouYe:
def xunBao_index(self, header, proxies):
"""# 寻宝网首页"""
<|body_0|>
def xunBaoIndex_list(self, header, proxies):
"""# 寻宝网首页list"""
<|body_1|>
def xunBaoIndex_detail(self, header, proxies, detail):
"""# 详情"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k_train_004942 | 3,630 | no_license | [
{
"docstring": "# 寻宝网首页",
"name": "xunBao_index",
"signature": "def xunBao_index(self, header, proxies)"
},
{
"docstring": "# 寻宝网首页list",
"name": "xunBaoIndex_list",
"signature": "def xunBaoIndex_list(self, header, proxies)"
},
{
"docstring": "# 详情",
"name": "xunBaoIndex_deta... | 3 | stack_v2_sparse_classes_30k_val_000691 | Implement the Python class `XunBaoShouYe` described below.
Class description:
Implement the XunBaoShouYe class.
Method signatures and docstrings:
- def xunBao_index(self, header, proxies): # 寻宝网首页
- def xunBaoIndex_list(self, header, proxies): # 寻宝网首页list
- def xunBaoIndex_detail(self, header, proxies, detail): # 详情 | Implement the Python class `XunBaoShouYe` described below.
Class description:
Implement the XunBaoShouYe class.
Method signatures and docstrings:
- def xunBao_index(self, header, proxies): # 寻宝网首页
- def xunBaoIndex_list(self, header, proxies): # 寻宝网首页list
- def xunBaoIndex_detail(self, header, proxies, detail): # 详情
... | 069a895f2b98d3dc817be9eca74009f6bd668fbd | <|skeleton|>
class XunBaoShouYe:
def xunBao_index(self, header, proxies):
"""# 寻宝网首页"""
<|body_0|>
def xunBaoIndex_list(self, header, proxies):
"""# 寻宝网首页list"""
<|body_1|>
def xunBaoIndex_detail(self, header, proxies, detail):
"""# 详情"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XunBaoShouYe:
def xunBao_index(self, header, proxies):
"""# 寻宝网首页"""
xbsy_url = '/'
xbsy_urlName = '寻宝网首页'
with self.client.get(xbsy_url, headers=header, proxies=proxies, name=xbsy_urlName + xbsy_url, verify=False, allow_redirects=False, catch_response=True) as response:
... | the_stack_v2_python_sparse | TongChuangYuanMa/xunbao/xunbaoshouye.py | lqrby/zhongfuan | train | 0 | |
bfdbc8eba6aaed9b09cddb141349a5b992d944aa | [
"super().__init__(coordinator)\nself.entity_description = SensorEntityDescription(key=account, name=f'steam_{account}', icon='mdi:steam')\nself._attr_unique_id = f'sensor.steam_{account}'",
"if self.entity_description.key in self.coordinator.data:\n player = self.coordinator.data[self.entity_description.key]\n... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = SensorEntityDescription(key=account, name=f'steam_{account}', icon='mdi:steam')
self._attr_unique_id = f'sensor.steam_{account}'
<|end_body_0|>
<|body_start_1|>
if self.entity_description.key in self.coordinator.da... | A class for the Steam account. | SteamSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SteamSensor:
"""A class for the Steam account."""
def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the state of the sensor."""
<|body_... | stack_v2_sparse_classes_36k_train_004943 | 3,561 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signature": "def native_value(self) -> StateType"
... | 4 | null | Implement the Python class `SteamSensor` described below.
Class description:
A class for the Steam account.
Method signatures and docstrings:
- def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None: Initialize the sensor.
- def native_value(self) -> StateType: Return the state of the senso... | Implement the Python class `SteamSensor` described below.
Class description:
A class for the Steam account.
Method signatures and docstrings:
- def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None: Initialize the sensor.
- def native_value(self) -> StateType: Return the state of the senso... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SteamSensor:
"""A class for the Steam account."""
def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the state of the sensor."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SteamSensor:
"""A class for the Steam account."""
def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = SensorEntityDescription(key=account, name=f'steam_{account}', i... | the_stack_v2_python_sparse | homeassistant/components/steam_online/sensor.py | home-assistant/core | train | 35,501 |
3f937745ec648c3b949aec6a2428cb24753492f3 | [
"if not nums:\n return None\n\n@cache\ndef bestScoreDiff(lo, hi):\n if lo > hi:\n return 0\n return max(nums[lo] - bestScoreDiff(lo + 1, hi), nums[hi] - bestScoreDiff(lo, hi - 1))\nreturn bestScoreDiff(0, len(nums) - 1) >= 0",
"if not nums:\n return None\nmemo = list(nums)\nfor span in range(1,... | <|body_start_0|>
if not nums:
return None
@cache
def bestScoreDiff(lo, hi):
if lo > hi:
return 0
return max(nums[lo] - bestScoreDiff(lo + 1, hi), nums[hi] - bestScoreDiff(lo, hi - 1))
return bestScoreDiff(0, len(nums) - 1) >= 0
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
"""Return the best score advantage you can get from: - Playing one valid move - Plug the negation of the best score advantage of the opponent (since it is a negative sum game) Complexity is O(N**2) for this is the number of s... | stack_v2_sparse_classes_36k_train_004944 | 2,363 | no_license | [
{
"docstring": "Return the best score advantage you can get from: - Playing one valid move - Plug the negation of the best score advantage of the opponent (since it is a negative sum game) Complexity is O(N**2) for this is the number of sub-solutions (i < j)",
"name": "PredictTheWinner",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_006820 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def PredictTheWinner(self, nums: List[int]) -> bool: Return the best score advantage you can get from: - Playing one valid move - Plug the negation of the best score advantage of... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def PredictTheWinner(self, nums: List[int]) -> bool: Return the best score advantage you can get from: - Playing one valid move - Plug the negation of the best score advantage of... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
"""Return the best score advantage you can get from: - Playing one valid move - Plug the negation of the best score advantage of the opponent (since it is a negative sum game) Complexity is O(N**2) for this is the number of s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
"""Return the best score advantage you can get from: - Playing one valid move - Plug the negation of the best score advantage of the opponent (since it is a negative sum game) Complexity is O(N**2) for this is the number of sub-solutions (... | the_stack_v2_python_sparse | dp/PredictTheWinner.py | QuentinDuval/PythonExperiments | train | 3 | |
88b6b065e81269ed88733245e0c345e6b387d765 | [
"try:\n self.session_duration = int(getenv('SESSION_DURATION', 0))\nexcept ValueError:\n self.session_duration = 0",
"session_id = super().create_session(user_id)\nif session_id is None:\n return None\nSessionExpAuth.user_id_by_session_id[session_id] = {'user_id': user_id, 'created_at': datetime.now()}\n... | <|body_start_0|>
try:
self.session_duration = int(getenv('SESSION_DURATION', 0))
except ValueError:
self.session_duration = 0
<|end_body_0|>
<|body_start_1|>
session_id = super().create_session(user_id)
if session_id is None:
return None
Sessi... | Extend behavior of SessionAuth class for session expiry. | SessionExpAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionExpAuth:
"""Extend behavior of SessionAuth class for session expiry."""
def __init__(self):
"""Initialize instance of SessionExpAuth."""
<|body_0|>
def create_session(self, user_id=None):
"""Create session associated with specified user id."""
<|bo... | stack_v2_sparse_classes_36k_train_004945 | 1,760 | no_license | [
{
"docstring": "Initialize instance of SessionExpAuth.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create session associated with specified user id.",
"name": "create_session",
"signature": "def create_session(self, user_id=None)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_train_012970 | Implement the Python class `SessionExpAuth` described below.
Class description:
Extend behavior of SessionAuth class for session expiry.
Method signatures and docstrings:
- def __init__(self): Initialize instance of SessionExpAuth.
- def create_session(self, user_id=None): Create session associated with specified use... | Implement the Python class `SessionExpAuth` described below.
Class description:
Extend behavior of SessionAuth class for session expiry.
Method signatures and docstrings:
- def __init__(self): Initialize instance of SessionExpAuth.
- def create_session(self, user_id=None): Create session associated with specified use... | 609a1679d2c31400979d96523565db8c2d12d794 | <|skeleton|>
class SessionExpAuth:
"""Extend behavior of SessionAuth class for session expiry."""
def __init__(self):
"""Initialize instance of SessionExpAuth."""
<|body_0|>
def create_session(self, user_id=None):
"""Create session associated with specified user id."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionExpAuth:
"""Extend behavior of SessionAuth class for session expiry."""
def __init__(self):
"""Initialize instance of SessionExpAuth."""
try:
self.session_duration = int(getenv('SESSION_DURATION', 0))
except ValueError:
self.session_duration = 0
... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_exp_auth.py | agzsoftsi/holbertonschool-web_back_end | train | 2 |
07a1bfa504e4541ab4ea1a5e7c540382ebbec7d7 | [
"super().__init__()\nself.label_emb = torch.nn.Embedding(n_classes, n_classes)\n\ndef block(in_feat, out_feat, normalize=True):\n layers = [torch.nn.Linear(in_feat, out_feat)]\n if normalize:\n layers.append(torch.nn.BatchNorm1d(out_feat, 0.8))\n layers.append(torch.nn.LeakyReLU(0.2, inplace=True))\... | <|body_start_0|>
super().__init__()
self.label_emb = torch.nn.Embedding(n_classes, n_classes)
def block(in_feat, out_feat, normalize=True):
layers = [torch.nn.Linear(in_feat, out_feat)]
if normalize:
layers.append(torch.nn.BatchNorm1d(out_feat, 0.8))
... | A very simple generator model to generate images of specific classes | Generator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""A very simple generator model to generate images of specific classes"""
def __init__(self, n_classes, img_shape, latent_dim):
"""Parameters ---------- n_classes : int the total number of classes img_shape : tuple the shape of the input images (including channel-dimensio... | stack_v2_sparse_classes_36k_train_004946 | 3,667 | permissive | [
{
"docstring": "Parameters ---------- n_classes : int the total number of classes img_shape : tuple the shape of the input images (including channel-dimension, excluding batch-dimension) latent_dim : int the size of the latent dimension",
"name": "__init__",
"signature": "def __init__(self, n_classes, i... | 2 | null | Implement the Python class `Generator` described below.
Class description:
A very simple generator model to generate images of specific classes
Method signatures and docstrings:
- def __init__(self, n_classes, img_shape, latent_dim): Parameters ---------- n_classes : int the total number of classes img_shape : tuple ... | Implement the Python class `Generator` described below.
Class description:
A very simple generator model to generate images of specific classes
Method signatures and docstrings:
- def __init__(self, n_classes, img_shape, latent_dim): Parameters ---------- n_classes : int the total number of classes img_shape : tuple ... | 1078f5030b8aac2bf022daf5fa14d66f74c3c893 | <|skeleton|>
class Generator:
"""A very simple generator model to generate images of specific classes"""
def __init__(self, n_classes, img_shape, latent_dim):
"""Parameters ---------- n_classes : int the total number of classes img_shape : tuple the shape of the input images (including channel-dimensio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""A very simple generator model to generate images of specific classes"""
def __init__(self, n_classes, img_shape, latent_dim):
"""Parameters ---------- n_classes : int the total number of classes img_shape : tuple the shape of the input images (including channel-dimension, excluding ... | the_stack_v2_python_sparse | dlutils/models/gans/conditional/models.py | justusschock/dl-utils | train | 15 |
588117f0ae883e6ce352ac4174cd7916ff5f14b3 | [
"widget = CompleterLineEdit(parent, self.delimiters, self.entries, self.entries_updater)\nwidget.setText(self.text)\nwidget.textEdited.connect(self.update_object)\nreturn widget",
"if not self._no_update and self.activated:\n try:\n value = self.get_widget().text()\n except AttributeError:\n v... | <|body_start_0|>
widget = CompleterLineEdit(parent, self.delimiters, self.entries, self.entries_updater)
widget.setText(self.text)
widget.textEdited.connect(self.update_object)
return widget
<|end_body_0|>
<|body_start_1|>
if not self._no_update and self.activated:
t... | Simple style text editor, which displays a text field. | QtLineCompleter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QtLineCompleter:
"""Simple style text editor, which displays a text field."""
def create_widget(self, parent):
"""Finishes initializing the editor by creating the underlying toolkit widget."""
<|body_0|>
def update_object(self):
"""Handles the user entering input... | stack_v2_sparse_classes_36k_train_004947 | 4,964 | no_license | [
{
"docstring": "Finishes initializing the editor by creating the underlying toolkit widget.",
"name": "create_widget",
"signature": "def create_widget(self, parent)"
},
{
"docstring": "Handles the user entering input data in the edit control.",
"name": "update_object",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_021388 | Implement the Python class `QtLineCompleter` described below.
Class description:
Simple style text editor, which displays a text field.
Method signatures and docstrings:
- def create_widget(self, parent): Finishes initializing the editor by creating the underlying toolkit widget.
- def update_object(self): Handles th... | Implement the Python class `QtLineCompleter` described below.
Class description:
Simple style text editor, which displays a text field.
Method signatures and docstrings:
- def create_widget(self, parent): Finishes initializing the editor by creating the underlying toolkit widget.
- def update_object(self): Handles th... | 6d54091d2c1c436a4dc07727a66be5a536ea8414 | <|skeleton|>
class QtLineCompleter:
"""Simple style text editor, which displays a text field."""
def create_widget(self, parent):
"""Finishes initializing the editor by creating the underlying toolkit widget."""
<|body_0|>
def update_object(self):
"""Handles the user entering input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QtLineCompleter:
"""Simple style text editor, which displays a text field."""
def create_widget(self, parent):
"""Finishes initializing the editor by creating the underlying toolkit widget."""
widget = CompleterLineEdit(parent, self.delimiters, self.entries, self.entries_updater)
... | the_stack_v2_python_sparse | hqc_meas/utils/widgets/qt_line_completer.py | MatthieuDartiailh/HQCMeas | train | 11 |
f090e4aa50ba6abaebde98419d0bdcb8e1e460e8 | [
"res = []\nif root:\n res.extend(self._inorderTraversal(root.left))\n res.append(root.val)\n res.extend(self._inorderTraversal(root.right))\nreturn res",
"res = []\ncurrent_node = pre_node = root\nwhile current_node:\n if not current_node.left:\n res.append(current_node.val)\n current_no... | <|body_start_0|>
res = []
if root:
res.extend(self._inorderTraversal(root.left))
res.append(root.val)
res.extend(self._inorderTraversal(root.right))
return res
<|end_body_0|>
<|body_start_1|>
res = []
current_node = pre_node = root
whi... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def __inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def ___inorderTraversal(self, root):
""":type root: T... | stack_v2_sparse_classes_36k_train_004948 | 3,683 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "_inorderTraversal",
"signature": "def _inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "__inorderTraversal",
"signature": "def __inorderTraversal(self, root)"
},
{
... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def __inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def ___inorderTraversal(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def __inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def ___inorderTraversal(s... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def __inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def ___inorderTraversal(self, root):
""":type root: T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
res = []
if root:
res.extend(self._inorderTraversal(root.left))
res.append(root.val)
res.extend(self._inorderTraversal(root.right))
return res
def ... | the_stack_v2_python_sparse | 94.binary-tree-inorder-traversal.py | windard/leeeeee | train | 0 | |
9749640fcda24434b223602f0cfbe2dcc4ab07f7 | [
"assert isinstance(wrapper, ForwardWrapperBase)\nassert isinstance(self.container_type, Container)\nassert self.default_value is None, 'default value not implemented for containers'\ncontainer_tmp_var = wrapper.declarations.declare_variable(self.container_type.full_name, self.name + '_value')\nwrapper.parse_params.... | <|body_start_0|>
assert isinstance(wrapper, ForwardWrapperBase)
assert isinstance(self.container_type, Container)
assert self.default_value is None, 'default value not implemented for containers'
container_tmp_var = wrapper.declarations.declare_variable(self.container_type.full_name, sel... | Container handlers | ContainerParameter | [
"LGPL-2.1-only",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainerParameter:
"""Container handlers"""
def convert_python_to_c(self, wrapper):
"""parses python args to get C++ value"""
<|body_0|>
def convert_c_to_python(self, wrapper):
"""Write some code before calling the Python method."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_004949 | 34,197 | permissive | [
{
"docstring": "parses python args to get C++ value",
"name": "convert_python_to_c",
"signature": "def convert_python_to_c(self, wrapper)"
},
{
"docstring": "Write some code before calling the Python method.",
"name": "convert_c_to_python",
"signature": "def convert_c_to_python(self, wra... | 2 | null | Implement the Python class `ContainerParameter` described below.
Class description:
Container handlers
Method signatures and docstrings:
- def convert_python_to_c(self, wrapper): parses python args to get C++ value
- def convert_c_to_python(self, wrapper): Write some code before calling the Python method. | Implement the Python class `ContainerParameter` described below.
Class description:
Container handlers
Method signatures and docstrings:
- def convert_python_to_c(self, wrapper): parses python args to get C++ value
- def convert_c_to_python(self, wrapper): Write some code before calling the Python method.
<|skeleton... | cbedcf671ba19fded26e4776c0e068f81f068dfd | <|skeleton|>
class ContainerParameter:
"""Container handlers"""
def convert_python_to_c(self, wrapper):
"""parses python args to get C++ value"""
<|body_0|>
def convert_c_to_python(self, wrapper):
"""Write some code before calling the Python method."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContainerParameter:
"""Container handlers"""
def convert_python_to_c(self, wrapper):
"""parses python args to get C++ value"""
assert isinstance(wrapper, ForwardWrapperBase)
assert isinstance(self.container_type, Container)
assert self.default_value is None, 'default value... | the_stack_v2_python_sparse | ns3/pybindgen-0.17.0.post57+nga6376f2/pybindgen/container.py | cyliustack/clusim | train | 7 |
50594984c84de39d3c69350b562d05eb95bb26da | [
"super().__init__()\nself.embedder = embedder\nself.output_layer = output_layer\nself.drop = nn.Dropout(dropout)\nself.pad_index = pad_index\nself.tie_weights = tie_weights\nif tie_weights:\n module = self.embedder\n for attr in tie_weight_attr.split('.'):\n module = getattr(module, attr)\n self.out... | <|body_start_0|>
super().__init__()
self.embedder = embedder
self.output_layer = output_layer
self.drop = nn.Dropout(dropout)
self.pad_index = pad_index
self.tie_weights = tie_weights
if tie_weights:
module = self.embedder
for attr in tie_w... | Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multiplied by the sequence length. | LanguageModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageModel:
"""Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multip... | stack_v2_sparse_classes_36k_train_004950 | 3,321 | permissive | [
{
"docstring": "Initialize the LanguageModel model. Parameters ---------- embedder: Embedder The embedder layer output_layer : Decoder Output layer to use dropout : float, optional Amount of droput between the encoder and decoder, defaults to 0. pad_index: int, optional Index used for padding, defaults to 0 tie... | 2 | stack_v2_sparse_classes_30k_train_010796 | Implement the Python class `LanguageModel` described below.
Class description:
Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the n... | Implement the Python class `LanguageModel` described below.
Class description:
Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the n... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class LanguageModel:
"""Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageModel:
"""Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multiplied by the s... | the_stack_v2_python_sparse | flambe/nlp/language_modeling/model.py | cle-ros/flambe | train | 1 |
15c2beb6cbb6ef4035d949c117c98ad38c1a6f89 | [
"if help is None:\n help = _('show a list of available pastebins and exit')\nsuper().__init__(*args, nargs=nargs, help=help, **kwargs)\nself.__pastebin_names = pastebin_names",
"print(_('Supported pastebins:'))\nprint()\nprint(_('Full name').upper().ljust(20), _('Abbreviated name').upper())\nfor abbreviated_na... | <|body_start_0|>
if help is None:
help = _('show a list of available pastebins and exit')
super().__init__(*args, nargs=nargs, help=help, **kwargs)
self.__pastebin_names = pastebin_names
<|end_body_0|>
<|body_start_1|>
print(_('Supported pastebins:'))
print()
... | An argparse action for printing a list of available pastebins. | PastebinsAction | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PastebinsAction:
"""An argparse action for printing a list of available pastebins."""
def __init__(self, *args, pastebin_names, nargs=0, help=None, **kwargs):
"""Initialize the action. full_name_dict should be a dictionary with abbreviated pastebin names as keys and non-abbreviated p... | stack_v2_sparse_classes_36k_train_004951 | 5,412 | permissive | [
{
"docstring": "Initialize the action. full_name_dict should be a dictionary with abbreviated pastebin names as keys and non-abbreviated pastebin names as values.",
"name": "__init__",
"signature": "def __init__(self, *args, pastebin_names, nargs=0, help=None, **kwargs)"
},
{
"docstring": "Print... | 2 | stack_v2_sparse_classes_30k_train_009708 | Implement the Python class `PastebinsAction` described below.
Class description:
An argparse action for printing a list of available pastebins.
Method signatures and docstrings:
- def __init__(self, *args, pastebin_names, nargs=0, help=None, **kwargs): Initialize the action. full_name_dict should be a dictionary with... | Implement the Python class `PastebinsAction` described below.
Class description:
An argparse action for printing a list of available pastebins.
Method signatures and docstrings:
- def __init__(self, *args, pastebin_names, nargs=0, help=None, **kwargs): Initialize the action. full_name_dict should be a dictionary with... | 575f1adfb0ae8cb16534daac8a6f36e2c2babe14 | <|skeleton|>
class PastebinsAction:
"""An argparse action for printing a list of available pastebins."""
def __init__(self, *args, pastebin_names, nargs=0, help=None, **kwargs):
"""Initialize the action. full_name_dict should be a dictionary with abbreviated pastebin names as keys and non-abbreviated p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PastebinsAction:
"""An argparse action for printing a list of available pastebins."""
def __init__(self, *args, pastebin_names, nargs=0, help=None, **kwargs):
"""Initialize the action. full_name_dict should be a dictionary with abbreviated pastebin names as keys and non-abbreviated pastebin names... | the_stack_v2_python_sparse | qastetray/cli/__main__.py | Akuli/qastetray | train | 0 |
46c4c387ed30b9230ecaa7419dab2029b1fcd947 | [
"super().__init__(driver, config, directory, prefix)\nself.pbar = tqdm(bar_format='{n_fmt}/{total_fmt}')\nself.next_key = Keys.ARROW_LEFT\n'\\n The key for next page.\\n '\nself.current_percent_element = None\n'\\n The element indicates current position.\\n '",
"self.driver.set_window_... | <|body_start_0|>
super().__init__(driver, config, directory, prefix)
self.pbar = tqdm(bar_format='{n_fmt}/{total_fmt}')
self.next_key = Keys.ARROW_LEFT
'\n The key for next page.\n '
self.current_percent_element = None
'\n The element indicates curren... | Manages 'd-library.jp' scraping. | Manager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manager:
"""Manages 'd-library.jp' scraping."""
def __init__(self, driver, config=None, directory='./', prefix=''):
"""Creates 'd-library.jp' manager. @param driver selenium instance"""
<|body_0|>
def start(self, url=None):
"""Starts scraping. @return an error ma... | stack_v2_sparse_classes_36k_train_004952 | 1,666 | no_license | [
{
"docstring": "Creates 'd-library.jp' manager. @param driver selenium instance",
"name": "__init__",
"signature": "def __init__(self, driver, config=None, directory='./', prefix='')"
},
{
"docstring": "Starts scraping. @return an error massage or True when succeed.",
"name": "start",
"s... | 3 | stack_v2_sparse_classes_30k_train_008418 | Implement the Python class `Manager` described below.
Class description:
Manages 'd-library.jp' scraping.
Method signatures and docstrings:
- def __init__(self, driver, config=None, directory='./', prefix=''): Creates 'd-library.jp' manager. @param driver selenium instance
- def start(self, url=None): Starts scraping... | Implement the Python class `Manager` described below.
Class description:
Manages 'd-library.jp' scraping.
Method signatures and docstrings:
- def __init__(self, driver, config=None, directory='./', prefix=''): Creates 'd-library.jp' manager. @param driver selenium instance
- def start(self, url=None): Starts scraping... | a43887e55a5484a813d944dce22e19ea3bec6c8c | <|skeleton|>
class Manager:
"""Manages 'd-library.jp' scraping."""
def __init__(self, driver, config=None, directory='./', prefix=''):
"""Creates 'd-library.jp' manager. @param driver selenium instance"""
<|body_0|>
def start(self, url=None):
"""Starts scraping. @return an error ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Manager:
"""Manages 'd-library.jp' scraping."""
def __init__(self, driver, config=None, directory='./', prefix=''):
"""Creates 'd-library.jp' manager. @param driver selenium instance"""
super().__init__(driver, config, directory, prefix)
self.pbar = tqdm(bar_format='{n_fmt}/{total... | the_stack_v2_python_sparse | dlibraryjp/manager.py | umjammer/K-AutoBook | train | 6 |
4c231424109f9ebd43336ce8213490328a2f8caa | [
"self.done = False\nself.success = False\nself.x_init = init_state[0]\nself.x_lim = 0.0\nself.xd_max = 0.0001\nself.delta_x_min = 0.1\nself.sign = 1 if positive else -1\nself.u_max = self.sign * np.array([1.5])\nself._t0 = None\nself._t_max = 10.0\nself._t_min = 2.0",
"x, _, _, xd, _ = obs\nif self._t0 is None:\n... | <|body_start_0|>
self.done = False
self.success = False
self.x_init = init_state[0]
self.x_lim = 0.0
self.xd_max = 0.0001
self.delta_x_min = 0.1
self.sign = 1 if positive else -1
self.u_max = self.sign * np.array([1.5])
self._t0 = None
self... | Controller for going to one of the joint limits (part of the calibration routine) | QCartPoleGoToLimCtrl | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCartPoleGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
<|... | stack_v2_sparse_classes_36k_train_004953 | 32,197 | permissive | [
{
"docstring": "Constructor :param init_state: initial state of the system :param positive: direction switch",
"name": "__init__",
"signature": "def __init__(self, init_state: np.ndarray, positive: bool=True)"
},
{
"docstring": "Go to joint limits by applying u_max and save limit value in th_lim... | 2 | null | Implement the Python class `QCartPoleGoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, init_state: np.ndarray, positive: bool=True): Constructor :param init_state: initial state of t... | Implement the Python class `QCartPoleGoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, init_state: np.ndarray, positive: bool=True): Constructor :param init_state: initial state of t... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class QCartPoleGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QCartPoleGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
self.done = Fal... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/special/environment_specific.py | 1abner1/SimuRLacra | train | 0 |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super(Funnel, self).__init__()\nself.conv_funnel = nn.Conv2d(in_channels, in_channels, 3, 1, 1, groups=in_channels)\nself.bn_funnel = nn.BatchNorm2d(in_channels)",
"tau = self.conv_funnel(input)\ntau = self.bn_funnel(tau)\noutput = torch.max(input, tau)\nreturn output"
] | <|body_start_0|>
super(Funnel, self).__init__()
self.conv_funnel = nn.Conv2d(in_channels, in_channels, 3, 1, 1, groups=in_channels)
self.bn_funnel = nn.BatchNorm2d(in_channels)
<|end_body_0|>
<|body_start_1|>
tau = self.conv_funnel(input)
tau = self.bn_funnel(tau)
output... | Funnel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Funnel:
def __init__(self, in_channels):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Funnel, self).__init__()
self.conv_funnel = nn.Conv2d(in_c... | stack_v2_sparse_classes_36k_train_004954 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, in_channels)"
},
{
"docstring": "Forward pass of the function",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000409 | Implement the Python class `Funnel` described below.
Class description:
Implement the Funnel class.
Method signatures and docstrings:
- def __init__(self, in_channels): Init method.
- def forward(self, input): Forward pass of the function | Implement the Python class `Funnel` described below.
Class description:
Implement the Funnel class.
Method signatures and docstrings:
- def __init__(self, in_channels): Init method.
- def forward(self, input): Forward pass of the function
<|skeleton|>
class Funnel:
def __init__(self, in_channels):
"""In... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Funnel:
def __init__(self, in_channels):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Funnel:
def __init__(self, in_channels):
"""Init method."""
super(Funnel, self).__init__()
self.conv_funnel = nn.Conv2d(in_channels, in_channels, 3, 1, 1, groups=in_channels)
self.bn_funnel = nn.BatchNorm2d(in_channels)
def forward(self, input):
"""Forward pass of ... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
f2f735ec797b9eff6bba7576f8bfb038544b4156 | [
"if self._code_response(self.body):\n codes = re.split('\\r?\\n', self.body)\n for code in codes:\n if code in OK_CODES:\n continue\n elif code in ERROR_CODES:\n exception = ERROR_CODE_TO_EXCEPTION_CLS.get(code)\n if code in ['411', '412', '413']:\n ... | <|body_start_0|>
if self._code_response(self.body):
codes = re.split('\r?\n', self.body)
for code in codes:
if code in OK_CODES:
continue
elif code in ERROR_CODES:
exception = ERROR_CODE_TO_EXCEPTION_CLS.get(code)
... | WorldWideDNSResponse | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorldWideDNSResponse:
def parse_body(self):
"""Parse response body. :return: Parsed body. :rtype: ``str``"""
<|body_0|>
def _code_response(self, body):
"""Checks if the response body contains code status. :rtype: ``bool``"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_004955 | 6,342 | permissive | [
{
"docstring": "Parse response body. :return: Parsed body. :rtype: ``str``",
"name": "parse_body",
"signature": "def parse_body(self)"
},
{
"docstring": "Checks if the response body contains code status. :rtype: ``bool``",
"name": "_code_response",
"signature": "def _code_response(self, ... | 2 | stack_v2_sparse_classes_30k_train_010147 | Implement the Python class `WorldWideDNSResponse` described below.
Class description:
Implement the WorldWideDNSResponse class.
Method signatures and docstrings:
- def parse_body(self): Parse response body. :return: Parsed body. :rtype: ``str``
- def _code_response(self, body): Checks if the response body contains co... | Implement the Python class `WorldWideDNSResponse` described below.
Class description:
Implement the WorldWideDNSResponse class.
Method signatures and docstrings:
- def parse_body(self): Parse response body. :return: Parsed body. :rtype: ``str``
- def _code_response(self, body): Checks if the response body contains co... | abba8c1719a8bda6db8efde2d46fd1b423ae4304 | <|skeleton|>
class WorldWideDNSResponse:
def parse_body(self):
"""Parse response body. :return: Parsed body. :rtype: ``str``"""
<|body_0|>
def _code_response(self, body):
"""Checks if the response body contains code status. :rtype: ``bool``"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorldWideDNSResponse:
def parse_body(self):
"""Parse response body. :return: Parsed body. :rtype: ``str``"""
if self._code_response(self.body):
codes = re.split('\r?\n', self.body)
for code in codes:
if code in OK_CODES:
continue
... | the_stack_v2_python_sparse | libcloud/common/worldwidedns.py | apache/libcloud | train | 1,644 | |
ec835ee8511d58a5524d82e5b149e1fc5b27d6bc | [
"user = get_object_or_404(UserProfileModel, account__username=username)\nself.check_object_permissions(request, user)\nqueryset = user.addresses.all()\npaginator = LimitOffsetPagination()\npaginator.default_limit = 10\npaginator.max_limit = 100\npaginated_queryset = paginator.paginate_queryset(queryset, request)\ns... | <|body_start_0|>
user = get_object_or_404(UserProfileModel, account__username=username)
self.check_object_permissions(request, user)
queryset = user.addresses.all()
paginator = LimitOffsetPagination()
paginator.default_limit = 10
paginator.max_limit = 100
paginate... | View for the user addresses. Lists, Creates, Updates and Deletes an Address. | UserAddressView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAddressView:
"""View for the user addresses. Lists, Creates, Updates and Deletes an Address."""
def list(self, request, username=None):
"""Lists all addresses the user has. Arguments: request: the request data sent by the user, it is used to check the user's permissions and in Pa... | stack_v2_sparse_classes_36k_train_004956 | 13,634 | permissive | [
{
"docstring": "Lists all addresses the user has. Arguments: request: the request data sent by the user, it is used to check the user's permissions and in Pagination username: the username of the user profile whose addresses will be returned Returns: HTTP 403 Response if the user is not authorized to see that u... | 6 | stack_v2_sparse_classes_30k_train_016175 | Implement the Python class `UserAddressView` described below.
Class description:
View for the user addresses. Lists, Creates, Updates and Deletes an Address.
Method signatures and docstrings:
- def list(self, request, username=None): Lists all addresses the user has. Arguments: request: the request data sent by the u... | Implement the Python class `UserAddressView` described below.
Class description:
View for the user addresses. Lists, Creates, Updates and Deletes an Address.
Method signatures and docstrings:
- def list(self, request, username=None): Lists all addresses the user has. Arguments: request: the request data sent by the u... | 7c361a31c5225c6ad649fcf92e323bdb10cc4c16 | <|skeleton|>
class UserAddressView:
"""View for the user addresses. Lists, Creates, Updates and Deletes an Address."""
def list(self, request, username=None):
"""Lists all addresses the user has. Arguments: request: the request data sent by the user, it is used to check the user's permissions and in Pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAddressView:
"""View for the user addresses. Lists, Creates, Updates and Deletes an Address."""
def list(self, request, username=None):
"""Lists all addresses the user has. Arguments: request: the request data sent by the user, it is used to check the user's permissions and in Pagination user... | the_stack_v2_python_sparse | users/views.py | ahmed-alllam/Koshkie-Server | train | 0 |
4d20d98aa324aed7861c4a62860a2ec18fbec141 | [
"super(ElaboratedEntireSpaceSupervisedMultiTaskModel, self).__init__()\nself.impress_to_click_pooling = nn.AdaptiveAvgPool1d(1)\nself.click_to_daction_pooling = nn.AdaptiveAvgPool1d(1)\nself.daction_to_buy_pooling = nn.AdaptiveAvgPool1d(1)\nself.oaction_to_buy_pooling = nn.AdaptiveAvgPool1d(1)\nself.impress_to_clic... | <|body_start_0|>
super(ElaboratedEntireSpaceSupervisedMultiTaskModel, self).__init__()
self.impress_to_click_pooling = nn.AdaptiveAvgPool1d(1)
self.click_to_daction_pooling = nn.AdaptiveAvgPool1d(1)
self.daction_to_buy_pooling = nn.AdaptiveAvgPool1d(1)
self.oaction_to_buy_pooling... | Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by adding two more base model to predict the direct CVR (Deterministic Acti... | ElaboratedEntireSpaceSupervisedMultiTaskModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElaboratedEntireSpaceSupervisedMultiTaskModel:
"""Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by... | stack_v2_sparse_classes_36k_train_004957 | 7,284 | permissive | [
{
"docstring": "Initialize ElaboratedEntireSpaceSupervisedMultiTaskModel Args: num_fields (int): Number of inputs' fields layer_sizes (List[int]): Layer sizes of dense network dropout_p (List[float], optional): Probability of Dropout in dense network. Defaults to None. activation (Callable[[T], T], optional): A... | 2 | stack_v2_sparse_classes_30k_train_006578 | Implement the Python class `ElaboratedEntireSpaceSupervisedMultiTaskModel` described below.
Class description:
Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions ... | Implement the Python class `ElaboratedEntireSpaceSupervisedMultiTaskModel` described below.
Class description:
Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions ... | 07a6a38c7eb44225f2b22f332081f697c3b92894 | <|skeleton|>
class ElaboratedEntireSpaceSupervisedMultiTaskModel:
"""Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElaboratedEntireSpaceSupervisedMultiTaskModel:
"""Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by adding two m... | the_stack_v2_python_sparse | torecsys/models/ctr/elaborated_entire_space_supervised_multi_task.py | zwcdp/torecsys | train | 0 |
791703677db4c430ebf7f448ff773c7f55b5083a | [
"plt.figure()\naxes = plt.gca()\ndata_lab = self.meta['OBS-FREQ'][0:2] + ' ' + self.meta['OBS-FREQ'][2:5]\naxes.plot(self.data.index, self.data, label=data_lab)\naxes.set_yscale('log')\naxes.set_ylim(0.0001, 1)\naxes.set_title('Nobeyama Radioheliograph')\naxes.set_xlabel('Start time: ' + self.data.index[0].strftime... | <|body_start_0|>
plt.figure()
axes = plt.gca()
data_lab = self.meta['OBS-FREQ'][0:2] + ' ' + self.meta['OBS-FREQ'][2:5]
axes.plot(self.data.index, self.data, label=data_lab)
axes.set_yscale('log')
axes.set_ylim(0.0001, 1)
axes.set_title('Nobeyama Radioheliograph')... | Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. It observes the full solar disk at 17 GHz ... | NoRHLightCurve | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoRHLightCurve:
"""Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. ... | stack_v2_sparse_classes_36k_train_004958 | 4,421 | permissive | [
{
"docstring": "Plots the NoRH lightcurve .. plot:: from sunpy import lightcurve as lc from sunpy.data.sample import NORH_TIMESERIES norh = lc.NoRHLightCurve.create(NORH_TIMESERIES) norh.peek() Parameters ---------- **kwargs : dict Any additional plot arguments that should be used when plotting.",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_003752 | Implement the Python class `NoRHLightCurve` described below.
Class description:
Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west... | Implement the Python class `NoRHLightCurve` described below.
Class description:
Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west... | 52fb75ece4677e554d5a6a5b43fa116a66d1fcdc | <|skeleton|>
class NoRHLightCurve:
"""Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoRHLightCurve:
"""Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. It observes t... | the_stack_v2_python_sparse | sunpy/lightcurve/sources/norh.py | cosmologist10/sunpy | train | 1 |
20afbec06cf905ff0e6ab0441cd12e4375e38612 | [
"if not strs:\n return ''\nprefix = strs[0]\nn = len(strs)\ni = 1\nwhile i < n:\n tmp = ''\n for a, b in zip(prefix, strs[i]):\n if a == b:\n tmp += a\n else:\n break\n if tmp:\n prefix = tmp\n i += 1\n else:\n return ''\nreturn prefix",
"if ... | <|body_start_0|>
if not strs:
return ''
prefix = strs[0]
n = len(strs)
i = 1
while i < n:
tmp = ''
for a, b in zip(prefix, strs[i]):
if a == b:
tmp += a
else:
break
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
"""横向扫描"""
<|body_0|>
def longestCommonPrefix2(self, strs: List[str]) -> str:
"""纵向扫描"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not strs:
return ''
prefix ... | stack_v2_sparse_classes_36k_train_004959 | 1,650 | no_license | [
{
"docstring": "横向扫描",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs: List[str]) -> str"
},
{
"docstring": "纵向扫描",
"name": "longestCommonPrefix2",
"signature": "def longestCommonPrefix2(self, strs: List[str]) -> str"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs: List[str]) -> str: 横向扫描
- def longestCommonPrefix2(self, strs: List[str]) -> str: 纵向扫描 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs: List[str]) -> str: 横向扫描
- def longestCommonPrefix2(self, strs: List[str]) -> str: 纵向扫描
<|skeleton|>
class Solution:
def longestCommonPre... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
"""横向扫描"""
<|body_0|>
def longestCommonPrefix2(self, strs: List[str]) -> str:
"""纵向扫描"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
"""横向扫描"""
if not strs:
return ''
prefix = strs[0]
n = len(strs)
i = 1
while i < n:
tmp = ''
for a, b in zip(prefix, strs[i]):
if a == b:
... | the_stack_v2_python_sparse | 14.最长公共前缀/solution.py | QtTao/daily_leetcode | train | 0 | |
60ee3a6cb30d880b33e355ad67a61f4feacf4492 | [
"super(Tagger, self).__init__()\nself.NEG_INF = -1000000.0\nself.rationale_binary = args.rationale_binary\nencoders = {'RNN': RnnEncoder, 'CNN': CnnEncoder, 'TRM': TrmEncoder}\nself.encoder = encoders[args.model_type](args)\nif self.rationale_binary:\n self.predictor = nn.Linear(args.hidden_dim, 2)\nelse:\n s... | <|body_start_0|>
super(Tagger, self).__init__()
self.NEG_INF = -1000000.0
self.rationale_binary = args.rationale_binary
encoders = {'RNN': RnnEncoder, 'CNN': CnnEncoder, 'TRM': TrmEncoder}
self.encoder = encoders[args.model_type](args)
if self.rationale_binary:
... | Tagger module, input sequence and output binary mask. | Tagger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tagger:
"""Tagger module, input sequence and output binary mask."""
def __init__(self, args):
"""Inputs: args.hidden_dim -- dimension of hidden states. args.model_type -- type of model, RNN/CNN/TRM. args.layer_num -- number of layers. args.cell_type -- type of cell GRU or LSTM (RNN o... | stack_v2_sparse_classes_36k_train_004960 | 5,435 | no_license | [
{
"docstring": "Inputs: args.hidden_dim -- dimension of hidden states. args.model_type -- type of model, RNN/CNN/TRM. args.layer_num -- number of layers. args.cell_type -- type of cell GRU or LSTM (RNN only). args.kernel_size -- kernel size of the conv1d (CNN only). args.head_num -- number of heads for multi he... | 3 | stack_v2_sparse_classes_30k_train_008294 | Implement the Python class `Tagger` described below.
Class description:
Tagger module, input sequence and output binary mask.
Method signatures and docstrings:
- def __init__(self, args): Inputs: args.hidden_dim -- dimension of hidden states. args.model_type -- type of model, RNN/CNN/TRM. args.layer_num -- number of ... | Implement the Python class `Tagger` described below.
Class description:
Tagger module, input sequence and output binary mask.
Method signatures and docstrings:
- def __init__(self, args): Inputs: args.hidden_dim -- dimension of hidden states. args.model_type -- type of model, RNN/CNN/TRM. args.layer_num -- number of ... | e79606e24ecc6fd713b481afb527c34eec7d5d66 | <|skeleton|>
class Tagger:
"""Tagger module, input sequence and output binary mask."""
def __init__(self, args):
"""Inputs: args.hidden_dim -- dimension of hidden states. args.model_type -- type of model, RNN/CNN/TRM. args.layer_num -- number of layers. args.cell_type -- type of cell GRU or LSTM (RNN o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tagger:
"""Tagger module, input sequence and output binary mask."""
def __init__(self, args):
"""Inputs: args.hidden_dim -- dimension of hidden states. args.model_type -- type of model, RNN/CNN/TRM. args.layer_num -- number of layers. args.cell_type -- type of cell GRU or LSTM (RNN only). args.ke... | the_stack_v2_python_sparse | rationalize/models/tagger.py | anshiquanshu66/factcheck-acl2021 | train | 0 |
8a82340e52e1e486e613389d71969df2d28f9ea7 | [
"super().__init__(kwargs)\nself.desc = copy.deepcopy(kwargs)\nself.fm = NormalizedWeightedFMLayer(input_dim4lookup=kwargs['input_dim4lookup'], alpha_init_mean=kwargs['alpha_init_mean'], alpha_init_radius=0.0001, alpha_activation=kwargs['alpha_activation'], selected_pairs=kwargs['selected_pairs'])\nself.l1_cover_par... | <|body_start_0|>
super().__init__(kwargs)
self.desc = copy.deepcopy(kwargs)
self.fm = NormalizedWeightedFMLayer(input_dim4lookup=kwargs['input_dim4lookup'], alpha_init_mean=kwargs['alpha_init_mean'], alpha_init_radius=0.0001, alpha_activation=kwargs['alpha_activation'], selected_pairs=kwargs['se... | Automatic Feature Interaction Selection (FIS) For DeepFM. :param input_dim: feature space of dataset :type input_dim: int :param input_dim4lookup: feature number in `feature_id`, usually equals to number of non-zero features :type input_dim4lookup: int :param embed_dim: length of each feature's latent vector(embedding ... | AutoGateModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoGateModel:
"""Automatic Feature Interaction Selection (FIS) For DeepFM. :param input_dim: feature space of dataset :type input_dim: int :param input_dim4lookup: feature number in `feature_id`, usually equals to number of non-zero features :type input_dim4lookup: int :param embed_dim: length o... | stack_v2_sparse_classes_36k_train_004961 | 3,679 | permissive | [
{
"docstring": "Construct the AutoGateModel class. :param net_desc: config of the structure :type net_desc: class object :return: return AutoGateModel class :rtype: class object",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Retrieve feature interaction scor... | 2 | stack_v2_sparse_classes_30k_train_005344 | Implement the Python class `AutoGateModel` described below.
Class description:
Automatic Feature Interaction Selection (FIS) For DeepFM. :param input_dim: feature space of dataset :type input_dim: int :param input_dim4lookup: feature number in `feature_id`, usually equals to number of non-zero features :type input_dim... | Implement the Python class `AutoGateModel` described below.
Class description:
Automatic Feature Interaction Selection (FIS) For DeepFM. :param input_dim: feature space of dataset :type input_dim: int :param input_dim4lookup: feature number in `feature_id`, usually equals to number of non-zero features :type input_dim... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class AutoGateModel:
"""Automatic Feature Interaction Selection (FIS) For DeepFM. :param input_dim: feature space of dataset :type input_dim: int :param input_dim4lookup: feature number in `feature_id`, usually equals to number of non-zero features :type input_dim4lookup: int :param embed_dim: length o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoGateModel:
"""Automatic Feature Interaction Selection (FIS) For DeepFM. :param input_dim: feature space of dataset :type input_dim: int :param input_dim4lookup: feature number in `feature_id`, usually equals to number of non-zero features :type input_dim4lookup: int :param embed_dim: length of each featur... | the_stack_v2_python_sparse | zeus/networks/pytorch/customs/autogate.py | huawei-noah/xingtian | train | 308 |
66dbc133cd0ee3fc02a76bdb1d9b02e5f4ec78c1 | [
"hold1 = -float('inf')\nhold2 = -float('inf')\nrelease1 = 0\nrelease2 = 0\nfor i in prices:\n release2 = max(release2, hold2 + i)\n hold2 = max(hold2, release1 - i)\n release1 = max(release1, hold1 + i)\n hold1 = max(hold1, -i)\nreturn release2",
"buy1 = -sys.maxsize\nsell1 = 0\nbuy2 = -sys.maxsize\ns... | <|body_start_0|>
hold1 = -float('inf')
hold2 = -float('inf')
release1 = 0
release2 = 0
for i in prices:
release2 = max(release2, hold2 + i)
hold2 = max(hold2, release1 - i)
release1 = max(release1, hold1 + i)
hold1 = max(hold1, -i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit0(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hold1 = -float('inf')
hold2 = -f... | stack_v2_sparse_classes_36k_train_004962 | 962 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit0",
"signature": "def maxProfit0(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit0(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit0(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit0(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
hold1 = -float('inf')
hold2 = -float('inf')
release1 = 0
release2 = 0
for i in prices:
release2 = max(release2, hold2 + i)
hold2 = max(hold2, release1 - i)
... | the_stack_v2_python_sparse | PythonCode/src/0123_Best_Time_to_Buy_and_Sell_Stock_III.py | oneyuan/CodeforFun | train | 0 | |
9eeefcb361a656a4846f3c3f5ce24fb47606c40a | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | StyleFactorServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleFactorServicer:
def GetSize(self, request, context):
"""语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数"""
<|body_0|>
def GetMomentum(self, request, ... | stack_v2_sparse_classes_36k_train_004963 | 4,758 | no_license | [
{
"docstring": "语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数",
"name": "GetSize",
"signature": "def GetSize(self, request, context)"
},
{
"docstring": "语法: get_momentum(ts_... | 4 | stack_v2_sparse_classes_30k_train_011714 | Implement the Python class `StyleFactorServicer` described below.
Class description:
Implement the StyleFactorServicer class.
Method signatures and docstrings:
- def GetSize(self, request, context): 语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'... | Implement the Python class `StyleFactorServicer` described below.
Class description:
Implement the StyleFactorServicer class.
Method signatures and docstrings:
- def GetSize(self, request, context): 语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'... | 663697ce5b3e591e1eddb8d308a1522214916fe5 | <|skeleton|>
class StyleFactorServicer:
def GetSize(self, request, context):
"""语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数"""
<|body_0|>
def GetMomentum(self, request, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StyleFactorServicer:
def GetSize(self, request, context):
"""语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
conte... | the_stack_v2_python_sparse | rpc/protoc/style_factor_pb2_grpc.py | webclinic017/soft_fin | train | 0 | |
3be691938872e8f43e26e703d3b71f317cfb008f | [
"try:\n instance = LessonRequest.objects.get(id=pk)\nexcept ObjectDoesNotExist:\n return Response({'detail': 'There is not lesson request with provided id'}, status=status.HTTP_400_BAD_REQUEST)\ndata = request.data.copy()\ndata['user_id'] = request.user.id\nif request.user.is_parent():\n ser = sers.LessonR... | <|body_start_0|>
try:
instance = LessonRequest.objects.get(id=pk)
except ObjectDoesNotExist:
return Response({'detail': 'There is not lesson request with provided id'}, status=status.HTTP_400_BAD_REQUEST)
data = request.data.copy()
data['user_id'] = request.user.i... | View for usage of parents and students. | LessonRequestItemView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LessonRequestItemView:
"""View for usage of parents and students."""
def put(self, request, pk):
"""Update an existing lesson request"""
<|body_0|>
def delete(self, request, pk):
"""Delete an existing lesson request"""
<|body_1|>
def get(self, reques... | stack_v2_sparse_classes_36k_train_004964 | 45,239 | no_license | [
{
"docstring": "Update an existing lesson request",
"name": "put",
"signature": "def put(self, request, pk)"
},
{
"docstring": "Delete an existing lesson request",
"name": "delete",
"signature": "def delete(self, request, pk)"
},
{
"docstring": "Get data from existing lesson requ... | 3 | null | Implement the Python class `LessonRequestItemView` described below.
Class description:
View for usage of parents and students.
Method signatures and docstrings:
- def put(self, request, pk): Update an existing lesson request
- def delete(self, request, pk): Delete an existing lesson request
- def get(self, request, p... | Implement the Python class `LessonRequestItemView` described below.
Class description:
View for usage of parents and students.
Method signatures and docstrings:
- def put(self, request, pk): Update an existing lesson request
- def delete(self, request, pk): Delete an existing lesson request
- def get(self, request, p... | e2e24cf41e1ea214ab608b61aa500feec95d68b6 | <|skeleton|>
class LessonRequestItemView:
"""View for usage of parents and students."""
def put(self, request, pk):
"""Update an existing lesson request"""
<|body_0|>
def delete(self, request, pk):
"""Delete an existing lesson request"""
<|body_1|>
def get(self, reques... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LessonRequestItemView:
"""View for usage of parents and students."""
def put(self, request, pk):
"""Update an existing lesson request"""
try:
instance = LessonRequest.objects.get(id=pk)
except ObjectDoesNotExist:
return Response({'detail': 'There is not les... | the_stack_v2_python_sparse | lesson/views.py | iamvane/nabi_api_django | train | 0 |
6f1f491c48537f3e0c6f0589e00c03c3f1fca57f | [
"self.x = 0\nself.y = 0\nself.offset = offset\nself.ratio = ratio\nself.vertical = vertical\nself.movement = movement\nself.moved_offset = 0\nself.stage_x = 0\nself.image = pygame.image.load(path).convert()\nself.image.set_colorkey(game_data.COLOR_KEY)",
"self.moved_offset += self.movement\nself.stage_x = round((... | <|body_start_0|>
self.x = 0
self.y = 0
self.offset = offset
self.ratio = ratio
self.vertical = vertical
self.movement = movement
self.moved_offset = 0
self.stage_x = 0
self.image = pygame.image.load(path).convert()
self.image.set_colorkey(g... | This class is, as for now, only really useful for side scrolling backgrounds. Other classes may inherit from this one and override the draw function to allow proper continuous vertical scrolling. | LayerObj | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerObj:
"""This class is, as for now, only really useful for side scrolling backgrounds. Other classes may inherit from this one and override the draw function to allow proper continuous vertical scrolling."""
def __init__(self, path: str, ratio: float, offset: [int, int], vertical: int, m... | stack_v2_sparse_classes_36k_train_004965 | 3,068 | no_license | [
{
"docstring": "LayerObj contains the data necessary to define the behaviour of a background layer to be handled properly by a background class. This allows for simple backgrounds and more complex parallax backgrounds. :param ratio: Ratio from the original scroll at which the layer will scroll, set to a value b... | 2 | stack_v2_sparse_classes_30k_train_015236 | Implement the Python class `LayerObj` described below.
Class description:
This class is, as for now, only really useful for side scrolling backgrounds. Other classes may inherit from this one and override the draw function to allow proper continuous vertical scrolling.
Method signatures and docstrings:
- def __init__... | Implement the Python class `LayerObj` described below.
Class description:
This class is, as for now, only really useful for side scrolling backgrounds. Other classes may inherit from this one and override the draw function to allow proper continuous vertical scrolling.
Method signatures and docstrings:
- def __init__... | 82c9a788a6c15e78e9882b28dfa824cb271c2562 | <|skeleton|>
class LayerObj:
"""This class is, as for now, only really useful for side scrolling backgrounds. Other classes may inherit from this one and override the draw function to allow proper continuous vertical scrolling."""
def __init__(self, path: str, ratio: float, offset: [int, int], vertical: int, m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayerObj:
"""This class is, as for now, only really useful for side scrolling backgrounds. Other classes may inherit from this one and override the draw function to allow proper continuous vertical scrolling."""
def __init__(self, path: str, ratio: float, offset: [int, int], vertical: int, movement: floa... | the_stack_v2_python_sparse | dymond_game/maps/layer_obj.py | YukiTheThicc/Black_Dymonds | train | 0 |
f16a4c9924ac8328b019dd8caf797ae878c956a1 | [
"ans: List[str] = []\nlevel: Set[str] = {s}\nwhile True:\n for sub_str in level:\n if self.is_valid(sub_str):\n ans.append(sub_str)\n if len(ans) > 0:\n return ans\n next_level: Set[str] = set()\n for sub_str in level:\n for i in range(len(sub_str)):\n if sub_s... | <|body_start_0|>
ans: List[str] = []
level: Set[str] = {s}
while True:
for sub_str in level:
if self.is_valid(sub_str):
ans.append(sub_str)
if len(ans) > 0:
return ans
next_level: Set[str] = set()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def remove_invalid_parentheses(self, s: str) -> List[str]:
"""BFS。"""
<|body_0|>
def is_valid(self, s: str) -> bool:
"""判断字符串括号是否有效。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans: List[str] = []
level: Set[str] = {s}
... | stack_v2_sparse_classes_36k_train_004966 | 3,194 | no_license | [
{
"docstring": "BFS。",
"name": "remove_invalid_parentheses",
"signature": "def remove_invalid_parentheses(self, s: str) -> List[str]"
},
{
"docstring": "判断字符串括号是否有效。",
"name": "is_valid",
"signature": "def is_valid(self, s: str) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_val_000399 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def remove_invalid_parentheses(self, s: str) -> List[str]: BFS。
- def is_valid(self, s: str) -> bool: 判断字符串括号是否有效。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def remove_invalid_parentheses(self, s: str) -> List[str]: BFS。
- def is_valid(self, s: str) -> bool: 判断字符串括号是否有效。
<|skeleton|>
class Solution:
def remove_invalid_parenthes... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def remove_invalid_parentheses(self, s: str) -> List[str]:
"""BFS。"""
<|body_0|>
def is_valid(self, s: str) -> bool:
"""判断字符串括号是否有效。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def remove_invalid_parentheses(self, s: str) -> List[str]:
"""BFS。"""
ans: List[str] = []
level: Set[str] = {s}
while True:
for sub_str in level:
if self.is_valid(sub_str):
ans.append(sub_str)
if len(ans) > 0... | the_stack_v2_python_sparse | 0301_remove-invalid-parentheses.py | Nigirimeshi/leetcode | train | 0 | |
303c38ae2d7850dda7ef66631a9450cdcdb80ae7 | [
"if root is None:\n return ''\nserialisation_list = dfs_preorder(root)\nreturn ','.join([str(x) for x in serialisation_list])",
"if len(data) == 0:\n return None\nraw_numbers = []\nfor s in data.split(','):\n if s == 'None':\n raw_numbers.append(None)\n else:\n raw_numbers.append(int(s))... | <|body_start_0|>
if root is None:
return ''
serialisation_list = dfs_preorder(root)
return ','.join([str(x) for x in serialisation_list])
<|end_body_0|>
<|body_start_1|>
if len(data) == 0:
return None
raw_numbers = []
for s in data.split(','):
... | 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_36k_train_004967 | 2,679 | 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_test_000596 | 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:... | 6546e93c77a033e2d291f276fe803787b8f4d8cd | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return ''
serialisation_list = dfs_preorder(root)
return ','.join([str(x) for x in serialisation_list])
def deserialize(self, data):
... | the_stack_v2_python_sparse | tree_and_graphs/serialise_deserialise_binary_tree.py | DarioBernardo/hackerrank_exercises | train | 0 | |
fbacad3332aaaf68a9b0dea69d97bdfcf76d0e97 | [
"self.points = []\nfor _ in range(numberOfPoints):\n self.points.append(parabolaPoint(a, b, c))\nself.allXY = []\nself.allLBL = []\nfor item in self.points:\n tmpXY = np.array([item.x, item.y])\n tmpLBL = np.array([item.label])\n self.allXY.append(tmpXY)\n self.allLBL.append(tmpLBL)\nself.allXY = np.... | <|body_start_0|>
self.points = []
for _ in range(numberOfPoints):
self.points.append(parabolaPoint(a, b, c))
self.allXY = []
self.allLBL = []
for item in self.points:
tmpXY = np.array([item.x, item.y])
tmpLBL = np.array([item.label])
... | ParabolaListOfpoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParabolaListOfpoint:
def __init__(self, numberOfPoints, a=1, b=0, c=0):
"""Get number Of Points Get a , b and c parameter in y=axx+bx+c (Parabola function) Return list of point class"""
<|body_0|>
def drawTrainingPoints(self):
"""Draw the training inputs and the trai... | stack_v2_sparse_classes_36k_train_004968 | 5,195 | no_license | [
{
"docstring": "Get number Of Points Get a , b and c parameter in y=axx+bx+c (Parabola function) Return list of point class",
"name": "__init__",
"signature": "def __init__(self, numberOfPoints, a=1, b=0, c=0)"
},
{
"docstring": "Draw the training inputs and the training label",
"name": "dra... | 3 | null | Implement the Python class `ParabolaListOfpoint` described below.
Class description:
Implement the ParabolaListOfpoint class.
Method signatures and docstrings:
- def __init__(self, numberOfPoints, a=1, b=0, c=0): Get number Of Points Get a , b and c parameter in y=axx+bx+c (Parabola function) Return list of point cla... | Implement the Python class `ParabolaListOfpoint` described below.
Class description:
Implement the ParabolaListOfpoint class.
Method signatures and docstrings:
- def __init__(self, numberOfPoints, a=1, b=0, c=0): Get number Of Points Get a , b and c parameter in y=axx+bx+c (Parabola function) Return list of point cla... | 76c27c9cb59f5e1d38ce28433c49a7d469fc692b | <|skeleton|>
class ParabolaListOfpoint:
def __init__(self, numberOfPoints, a=1, b=0, c=0):
"""Get number Of Points Get a , b and c parameter in y=axx+bx+c (Parabola function) Return list of point class"""
<|body_0|>
def drawTrainingPoints(self):
"""Draw the training inputs and the trai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParabolaListOfpoint:
def __init__(self, numberOfPoints, a=1, b=0, c=0):
"""Get number Of Points Get a , b and c parameter in y=axx+bx+c (Parabola function) Return list of point class"""
self.points = []
for _ in range(numberOfPoints):
self.points.append(parabolaPoint(a, b, ... | the_stack_v2_python_sparse | lab11/NN-final-parabola4_listPoint.py | GadiHerman/machine_learning_book | train | 2 | |
458cd2ff0cb40666f21b772c305c1b250688d978 | [
"m, n = (len(s1), len(s2))\ndps = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\nfor i in range(1, m + 1):\n dps[i][0] = dps[i - 1][0] + ord(s1[i - 1])\nfor j in range(1, n + 1):\n dps[0][j] = dps[0][j - 1] + ord(s2[j - 1])\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n if s1[i - 1] ==... | <|body_start_0|>
m, n = (len(s1), len(s2))
dps = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(1, m + 1):
dps[i][0] = dps[i - 1][0] + ord(s1[i - 1])
for j in range(1, n + 1):
dps[0][j] = dps[0][j - 1] + ord(s2[j - 1])
for i in range(1, m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int"""
<|body_0|>
def minimumDeleteSumOptimal(self, s1, s2):
""":type s1: str :type s2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m, n = (len(... | stack_v2_sparse_classes_36k_train_004969 | 1,327 | no_license | [
{
"docstring": ":type s1: str :type s2: str :rtype: int",
"name": "minimumDeleteSum",
"signature": "def minimumDeleteSum(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: int",
"name": "minimumDeleteSumOptimal",
"signature": "def minimumDeleteSumOptimal(self, s1, s2)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeleteSum(self, s1, s2): :type s1: str :type s2: str :rtype: int
- def minimumDeleteSumOptimal(self, s1, s2): :type s1: str :type s2: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeleteSum(self, s1, s2): :type s1: str :type s2: str :rtype: int
- def minimumDeleteSumOptimal(self, s1, s2): :type s1: str :type s2: str :rtype: int
<|skeleton|>
cla... | a330e92191642e2965939a06b050ca84d4ed11a6 | <|skeleton|>
class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int"""
<|body_0|>
def minimumDeleteSumOptimal(self, s1, s2):
""":type s1: str :type s2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int"""
m, n = (len(s1), len(s2))
dps = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(1, m + 1):
dps[i][0] = dps[i - 1][0] + ord(s1[i - 1])
for j in range(... | the_stack_v2_python_sparse | src/dps/minimum-ascii-delete-sum-for-two-strings-712.py | monpro/algorithm | train | 102 | |
a0ca8a4f4d1f0ecbd62fdaa3635f7b7135b48449 | [
"email_claim = Config.get_OIDC_email_claim()\nself._assert_required_token_parameters([email_claim])\nreturn self.token[email_claim]",
"from ..security import assert_authorized_email\nassert_authorized_email(emails, self.token)\nreturn"
] | <|body_start_0|>
email_claim = Config.get_OIDC_email_claim()
self._assert_required_token_parameters([email_claim])
return self.token[email_claim]
<|end_body_0|>
<|body_start_1|>
from ..security import assert_authorized_email
assert_authorized_email(emails, self.token)
re... | Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods. | TokenEmailMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenEmailMixin:
"""Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods."""
def token_email(self):
"""Property for the user's JWT email claim"""
<|body_0|>
def _assert_authorized_email(self, emails):
"""... | stack_v2_sparse_classes_36k_train_004970 | 4,756 | permissive | [
{
"docstring": "Property for the user's JWT email claim",
"name": "token_email",
"signature": "def token_email(self)"
},
{
"docstring": "Verify user JWT token email matches specified emails",
"name": "_assert_authorized_email",
"signature": "def _assert_authorized_email(self, emails)"
... | 2 | stack_v2_sparse_classes_30k_train_010550 | Implement the Python class `TokenEmailMixin` described below.
Class description:
Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods.
Method signatures and docstrings:
- def token_email(self): Property for the user's JWT email claim
- def _assert_authorized_... | Implement the Python class `TokenEmailMixin` described below.
Class description:
Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods.
Method signatures and docstrings:
- def token_email(self): Property for the user's JWT email claim
- def _assert_authorized_... | fa96624a09c7ac1595fcd6fbabd31e551382b757 | <|skeleton|>
class TokenEmailMixin:
"""Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods."""
def token_email(self):
"""Property for the user's JWT email claim"""
<|body_0|>
def _assert_authorized_email(self, emails):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenEmailMixin:
"""Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods."""
def token_email(self):
"""Property for the user's JWT email claim"""
email_claim = Config.get_OIDC_email_claim()
self._assert_required_token_para... | the_stack_v2_python_sparse | dss/util/auth/authorize.py | charlesreid1acom/data-store | train | 0 |
4adce9c92d97b54309dca1911899980e9df91dbe | [
"function = LegacyFunctionSpecification()\nfunction.addParameter('input', dtype='int32', direction=function.IN, description='Typical input parameter, the argument is passed by value to the function.')\nfunction.addParameter('output', dtype='float64', direction=function.OUT, description='Typical output parameter, th... | <|body_start_0|>
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='int32', direction=function.IN, description='Typical input parameter, the argument is passed by value to the function.')
function.addParameter('output', dtype='float64', direction=function.OUT, descrip... | ExampleInterface | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleInterface:
def example_function():
"""Example template for the other functions defined in this specification. All functions should follow this example.."""
<|body_0|>
def get_example_parameter():
"""Retrieve the current value of the parameter. Note, values can... | stack_v2_sparse_classes_36k_train_004971 | 3,439 | permissive | [
{
"docstring": "Example template for the other functions defined in this specification. All functions should follow this example..",
"name": "example_function",
"signature": "def example_function()"
},
{
"docstring": "Retrieve the current value of the parameter. Note, values can be any of the su... | 4 | stack_v2_sparse_classes_30k_train_014932 | Implement the Python class `ExampleInterface` described below.
Class description:
Implement the ExampleInterface class.
Method signatures and docstrings:
- def example_function(): Example template for the other functions defined in this specification. All functions should follow this example..
- def get_example_param... | Implement the Python class `ExampleInterface` described below.
Class description:
Implement the ExampleInterface class.
Method signatures and docstrings:
- def example_function(): Example template for the other functions defined in this specification. All functions should follow this example..
- def get_example_param... | b57c1e2fda1457d5025307be105c2aa59b19b574 | <|skeleton|>
class ExampleInterface:
def example_function():
"""Example template for the other functions defined in this specification. All functions should follow this example.."""
<|body_0|>
def get_example_parameter():
"""Retrieve the current value of the parameter. Note, values can... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExampleInterface:
def example_function():
"""Example template for the other functions defined in this specification. All functions should follow this example.."""
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='int32', direction=function.IN, description='... | the_stack_v2_python_sparse | src/amuse/community/interface/example.py | amusecode/amuse | train | 158 | |
178e0e4a930555a1a3d25c4c92a44012b52ccc01 | [
"if not matrix:\n return False\nleft = 0\nright = len(matrix) * len(matrix[0]) - 1\nwhile left <= right:\n mid = left + (right - left) // 2\n mid_val = self.get_value(matrix, mid)\n if mid_val < target:\n left = mid + 1\n elif mid_val > target:\n right = mid - 1\n else:\n retu... | <|body_start_0|>
if not matrix:
return False
left = 0
right = len(matrix) * len(matrix[0]) - 1
while left <= right:
mid = left + (right - left) // 2
mid_val = self.get_value(matrix, mid)
if mid_val < target:
left = mid + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""Args: matrix: list[list[int]] target: int Return: bool"""
<|body_0|>
def get_value(self, matrix, index):
"""Args: matrix: list[list[int]] index: int Return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_004972 | 931 | no_license | [
{
"docstring": "Args: matrix: list[list[int]] target: int Return: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": "Args: matrix: list[list[int]] index: int Return: int",
"name": "get_value",
"signature": "def get_value(self, matrix, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): Args: matrix: list[list[int]] target: int Return: bool
- def get_value(self, matrix, index): Args: matrix: list[list[int]] index: int Retu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): Args: matrix: list[list[int]] target: int Return: bool
- def get_value(self, matrix, index): Args: matrix: list[list[int]] index: int Retu... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""Args: matrix: list[list[int]] target: int Return: bool"""
<|body_0|>
def get_value(self, matrix, index):
"""Args: matrix: list[list[int]] index: int Return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
"""Args: matrix: list[list[int]] target: int Return: bool"""
if not matrix:
return False
left = 0
right = len(matrix) * len(matrix[0]) - 1
while left <= right:
mid = left + (right - left) // 2
... | the_stack_v2_python_sparse | code/74. 搜索二维矩阵.py | AiZhanghan/Leetcode | train | 0 | |
dbecf53767136df230106ee1663517de3edf08fb | [
"super(SpriteNaming, self).__init__()\nself.total_default = 0\nself.list_default = []\nself.default_names = ['Sprite', 'Objeto']",
"print('{} default sprite names found:'.format(self.total_default))\nfor name in self.list_default:\n print(name)",
"for sprite in self.iter_sprites(scratch):\n for default in... | <|body_start_0|>
super(SpriteNaming, self).__init__()
self.total_default = 0
self.list_default = []
self.default_names = ['Sprite', 'Objeto']
<|end_body_0|>
<|body_start_1|>
print('{} default sprite names found:'.format(self.total_default))
for name in self.list_default:... | Plugin that keeps track of how often sprites' default names are used. E.g., Sprite1, Sprite2, ... | SpriteNaming | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpriteNaming:
"""Plugin that keeps track of how often sprites' default names are used. E.g., Sprite1, Sprite2, ..."""
def __init__(self):
"""Initialize an instance of the SpriteNaming plugin."""
<|body_0|>
def finalize(self):
"""Output the default sprite names fo... | stack_v2_sparse_classes_36k_train_004973 | 1,151 | permissive | [
{
"docstring": "Initialize an instance of the SpriteNaming plugin.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Output the default sprite names found in the project.",
"name": "finalize",
"signature": "def finalize(self)"
},
{
"docstring": "Run and r... | 3 | stack_v2_sparse_classes_30k_train_021035 | Implement the Python class `SpriteNaming` described below.
Class description:
Plugin that keeps track of how often sprites' default names are used. E.g., Sprite1, Sprite2, ...
Method signatures and docstrings:
- def __init__(self): Initialize an instance of the SpriteNaming plugin.
- def finalize(self): Output the de... | Implement the Python class `SpriteNaming` described below.
Class description:
Plugin that keeps track of how often sprites' default names are used. E.g., Sprite1, Sprite2, ...
Method signatures and docstrings:
- def __init__(self): Initialize an instance of the SpriteNaming plugin.
- def finalize(self): Output the de... | 04082921a1c5404e32659e15769f2a8b1ca9e777 | <|skeleton|>
class SpriteNaming:
"""Plugin that keeps track of how often sprites' default names are used. E.g., Sprite1, Sprite2, ..."""
def __init__(self):
"""Initialize an instance of the SpriteNaming plugin."""
<|body_0|>
def finalize(self):
"""Output the default sprite names fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpriteNaming:
"""Plugin that keeps track of how often sprites' default names are used. E.g., Sprite1, Sprite2, ..."""
def __init__(self):
"""Initialize an instance of the SpriteNaming plugin."""
super(SpriteNaming, self).__init__()
self.total_default = 0
self.list_default ... | the_stack_v2_python_sparse | hairball-tcc/hairball/plugins/convention.py | gbrasile/hairball | train | 0 |
3e1727b0970b5ac05619b68d723e329e18be2e8e | [
"super().__init__(image=Chef.image, x=games.screen.width / 2, y=y, dx=speed)\nself.odds_change = odds_change\nself.time_til_drop = 0",
"if self.left < 0 or self.right > games.screen.width:\n self.dx = -self.dx\nelif random.randrange(self.odds_change) == 0:\n self.dx = -self.dx\nself.check_drop()",
"if sel... | <|body_start_0|>
super().__init__(image=Chef.image, x=games.screen.width / 2, y=y, dx=speed)
self.odds_change = odds_change
self.time_til_drop = 0
<|end_body_0|>
<|body_start_1|>
if self.left < 0 or self.right > games.screen.width:
self.dx = -self.dx
elif random.rand... | Chef whom throw pizza move left - right | Chef | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chef:
"""Chef whom throw pizza move left - right"""
def __init__(self, y=55, speed=speed, odds_change=200):
"""init object Chef"""
<|body_0|>
def update(self):
"""Defined got change course"""
<|body_1|>
def check_drop(self):
"""Reduce interva... | stack_v2_sparse_classes_36k_train_004974 | 10,701 | no_license | [
{
"docstring": "init object Chef",
"name": "__init__",
"signature": "def __init__(self, y=55, speed=speed, odds_change=200)"
},
{
"docstring": "Defined got change course",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Reduce interval expectation on one or d... | 3 | null | Implement the Python class `Chef` described below.
Class description:
Chef whom throw pizza move left - right
Method signatures and docstrings:
- def __init__(self, y=55, speed=speed, odds_change=200): init object Chef
- def update(self): Defined got change course
- def check_drop(self): Reduce interval expectation o... | Implement the Python class `Chef` described below.
Class description:
Chef whom throw pizza move left - right
Method signatures and docstrings:
- def __init__(self, y=55, speed=speed, odds_change=200): init object Chef
- def update(self): Defined got change course
- def check_drop(self): Reduce interval expectation o... | 501aed406bc88e0baebd402e18851f1f2f8ac9da | <|skeleton|>
class Chef:
"""Chef whom throw pizza move left - right"""
def __init__(self, y=55, speed=speed, odds_change=200):
"""init object Chef"""
<|body_0|>
def update(self):
"""Defined got change course"""
<|body_1|>
def check_drop(self):
"""Reduce interva... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Chef:
"""Chef whom throw pizza move left - right"""
def __init__(self, y=55, speed=speed, odds_change=200):
"""init object Chef"""
super().__init__(image=Chef.image, x=games.screen.width / 2, y=y, dx=speed)
self.odds_change = odds_change
self.time_til_drop = 0
def upd... | the_stack_v2_python_sparse | _Chapter_11_PYGAME_LIVEWIRES/Homework_1.py | MrVeshij/Michael-Dawson | train | 1 |
390b55ad55a201edb5db7cb6bbd8448294d25856 | [
"super(NeuralProcess, self).__init__()\nself._num_latents = num_latents\nself._latent_encoder_sizes = latent_encoder_sizes\nself._deterministic_encoder_sizes = deterministic_encoder_sizes\nself._decoder_sizes = decoder_sizes\nself._use_deterministic_path = use_deterministic_path\nself._attention = attention_wrapper... | <|body_start_0|>
super(NeuralProcess, self).__init__()
self._num_latents = num_latents
self._latent_encoder_sizes = latent_encoder_sizes
self._deterministic_encoder_sizes = deterministic_encoder_sizes
self._decoder_sizes = decoder_sizes
self._use_deterministic_path = use_... | Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018). | NeuralProcess | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model... | stack_v2_sparse_classes_36k_train_004975 | 32,302 | permissive | [
{
"docstring": "Initializes the Neural Process model. Args: latent_encoder_sizes: (list of ints) Hidden layer sizes for latent encoder. num_latents: (int) Dimensionality of global latent variable. decoder_sizes: (list of ints) Hidden layer sizes for decoder use_deterministic_path: (bool) Uses deterministic enco... | 5 | stack_v2_sparse_classes_30k_test_000890 | Implement the Python class `NeuralProcess` described below.
Class description:
Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018).
Method signatures and docstrings:
- def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, atte... | Implement the Python class `NeuralProcess` described below.
Class description:
Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018).
Method signatures and docstrings:
- def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, atte... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model. Args: laten... | the_stack_v2_python_sparse | t2t_bert/utils/tensor2tensor/layers/gaussian_process.py | yyht/BERT | train | 37 |
70d086a9685b64bfb791032fd2a3781aa2dc6e63 | [
"if not self.tasks:\n raise ValueError('Tasks must not be empty!!')\nmodule_attrs = {'train': self.mode == base.ExecutionMode.TRAIN, 'mode': self.mode, 'dtype': self.dtype}\nassert self.vision_model_fn is not None\nself.vision_model = self.vision_model_fn(**base.filter_attrs(self.vision_model_fn, module_attrs))\... | <|body_start_0|>
if not self.tasks:
raise ValueError('Tasks must not be empty!!')
module_attrs = {'train': self.mode == base.ExecutionMode.TRAIN, 'mode': self.mode, 'dtype': self.dtype}
assert self.vision_model_fn is not None
self.vision_model = self.vision_model_fn(**base.fi... | Multi-task model function. Attributes: tasks: A sequence of tasks to instantiate. Each task contains its own head. train_vision_model: A bool specifying whether to train the vision model. vision_model_fn: A function returning a nn.Module specifying which vision encoder to use. dtype: A jax data type. | MultitaskModel | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultitaskModel:
"""Multi-task model function. Attributes: tasks: A sequence of tasks to instantiate. Each task contains its own head. train_vision_model: A bool specifying whether to train the vision model. vision_model_fn: A function returning a nn.Module specifying which vision encoder to use. ... | stack_v2_sparse_classes_36k_train_004976 | 3,214 | permissive | [
{
"docstring": "Initializes a Module lazily (similar to a lazy ``__init__``).",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Call function for the multi-task model. Args: image: An array of shape [batch_size, height, width, channels]. text: A numeric array of the input text... | 2 | null | Implement the Python class `MultitaskModel` described below.
Class description:
Multi-task model function. Attributes: tasks: A sequence of tasks to instantiate. Each task contains its own head. train_vision_model: A bool specifying whether to train the vision model. vision_model_fn: A function returning a nn.Module s... | Implement the Python class `MultitaskModel` described below.
Class description:
Multi-task model function. Attributes: tasks: A sequence of tasks to instantiate. Each task contains its own head. train_vision_model: A bool specifying whether to train the vision model. vision_model_fn: A function returning a nn.Module s... | 1b4e7db5f90bcb4f80803383a81d8613ebfdfeec | <|skeleton|>
class MultitaskModel:
"""Multi-task model function. Attributes: tasks: A sequence of tasks to instantiate. Each task contains its own head. train_vision_model: A bool specifying whether to train the vision model. vision_model_fn: A function returning a nn.Module specifying which vision encoder to use. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultitaskModel:
"""Multi-task model function. Attributes: tasks: A sequence of tasks to instantiate. Each task contains its own head. train_vision_model: A bool specifying whether to train the vision model. vision_model_fn: A function returning a nn.Module specifying which vision encoder to use. dtype: A jax ... | the_stack_v2_python_sparse | fvlm/modeling/multitask_model.py | antonpolishko/google-research | train | 0 |
9f27a7cc9f4055c4f64db957510045fcf7a7deee | [
"self.nums = nums\nind = 1\nwhile ind < len(nums):\n self.nums[ind] += self.nums[ind - 1]\n ind += 1",
"if not i:\n return self.nums[j]\nelse:\n return self.nums[j] - self.nums[i - 1]"
] | <|body_start_0|>
self.nums = nums
ind = 1
while ind < len(nums):
self.nums[ind] += self.nums[ind - 1]
ind += 1
<|end_body_0|>
<|body_start_1|>
if not i:
return self.nums[j]
else:
return self.nums[j] - self.nums[i - 1]
<|end_body_1|... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_004977 | 799 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, ... | 2 | stack_v2_sparse_classes_30k_train_010257 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | 129c5c77077fbe7fd0fbd93efd75a77e3aaeae8e | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
self.nums = nums
ind = 1
while ind < len(nums):
self.nums[ind] += self.nums[ind - 1]
ind += 1
def sumRange(self, i, j):
"""sum of elements n... | the_stack_v2_python_sparse | 303_Range_Sum_Query-Immutable.py | MultiLi/leetcode | train | 1 | |
0d7435c9c3f78fea8212d02288beb662458c31ff | [
"location = get_object_or_404(Location, pk=location_id)\nserializer = LocationSerializer(location)\nreturn Response(serializer.data)",
"location = get_object_or_404(Location, pk=location_id)\nserializer = LocationSerializer(location, data=request.data)\nif serializer.is_valid():\n serializer.save()\n return... | <|body_start_0|>
location = get_object_or_404(Location, pk=location_id)
serializer = LocationSerializer(location)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
location = get_object_or_404(Location, pk=location_id)
serializer = LocationSerializer(location, dat... | LocationDetail | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationDetail:
def get(self, request, location_id, format=None):
"""Get location detail"""
<|body_0|>
def put(self, request, location_id, format=None):
"""Edit location --- serializer: administrator.serializers.LocationSerializer"""
<|body_1|>
def delet... | stack_v2_sparse_classes_36k_train_004978 | 30,608 | permissive | [
{
"docstring": "Get location detail",
"name": "get",
"signature": "def get(self, request, location_id, format=None)"
},
{
"docstring": "Edit location --- serializer: administrator.serializers.LocationSerializer",
"name": "put",
"signature": "def put(self, request, location_id, format=Non... | 3 | stack_v2_sparse_classes_30k_train_013773 | Implement the Python class `LocationDetail` described below.
Class description:
Implement the LocationDetail class.
Method signatures and docstrings:
- def get(self, request, location_id, format=None): Get location detail
- def put(self, request, location_id, format=None): Edit location --- serializer: administrator.... | Implement the Python class `LocationDetail` described below.
Class description:
Implement the LocationDetail class.
Method signatures and docstrings:
- def get(self, request, location_id, format=None): Get location detail
- def put(self, request, location_id, format=None): Edit location --- serializer: administrator.... | 73728463badb3bfd4413aa0f7aeb44a9606fdfea | <|skeleton|>
class LocationDetail:
def get(self, request, location_id, format=None):
"""Get location detail"""
<|body_0|>
def put(self, request, location_id, format=None):
"""Edit location --- serializer: administrator.serializers.LocationSerializer"""
<|body_1|>
def delet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocationDetail:
def get(self, request, location_id, format=None):
"""Get location detail"""
location = get_object_or_404(Location, pk=location_id)
serializer = LocationSerializer(location)
return Response(serializer.data)
def put(self, request, location_id, format=None):
... | the_stack_v2_python_sparse | administrator/views.py | belatrix/BackendAllStars | train | 5 | |
cc3eff043ae16ef5a92ff9868daf3228e6e78849 | [
"rev1, rev2, use_common_ancestor = cls._parse(revision_range, stdin_mode)\nif use_common_ancestor:\n return cls._with_common_ancestor(rev1, rev2, cwd)\nreturn cls(rev1, rev2)",
"if revision_range == PRE_COMMIT_FROM_TO_REFS:\n if stdin_mode:\n raise ValueError(f'With --stdin-filename, revision {revisi... | <|body_start_0|>
rev1, rev2, use_common_ancestor = cls._parse(revision_range, stdin_mode)
if use_common_ancestor:
return cls._with_common_ancestor(rev1, rev2, cwd)
return cls(rev1, rev2)
<|end_body_0|>
<|body_start_1|>
if revision_range == PRE_COMMIT_FROM_TO_REFS:
... | Represent a range of commits in a Git repository for comparing differences ``rev1`` is the "old" revision, and ``rev2``, the "new" revision which should be compared against ``rev1``. When parsing a revision range expression with triple dots (e.g. ``master...HEAD``), the branch point, or common ancestor of the revisions... | RevisionRange | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevisionRange:
"""Represent a range of commits in a Git repository for comparing differences ``rev1`` is the "old" revision, and ``rev2``, the "new" revision which should be compared against ``rev1``. When parsing a revision range expression with triple dots (e.g. ``master...HEAD``), the branch p... | stack_v2_sparse_classes_36k_train_004979 | 24,537 | permissive | [
{
"docstring": "Convert a range expression to a ``RevisionRange`` object If the expression contains triple dots (e.g. ``master...HEAD``), finds the common ancestor of the two revisions and uses that as the first revision. :param revision_range: The revision range as a string to parse :param cwd: The working dir... | 3 | stack_v2_sparse_classes_30k_train_005487 | Implement the Python class `RevisionRange` described below.
Class description:
Represent a range of commits in a Git repository for comparing differences ``rev1`` is the "old" revision, and ``rev2``, the "new" revision which should be compared against ``rev1``. When parsing a revision range expression with triple dots... | Implement the Python class `RevisionRange` described below.
Class description:
Represent a range of commits in a Git repository for comparing differences ``rev1`` is the "old" revision, and ``rev2``, the "new" revision which should be compared against ``rev1``. When parsing a revision range expression with triple dots... | e96018f086383a2dcfaab6825945fbee08daca2a | <|skeleton|>
class RevisionRange:
"""Represent a range of commits in a Git repository for comparing differences ``rev1`` is the "old" revision, and ``rev2``, the "new" revision which should be compared against ``rev1``. When parsing a revision range expression with triple dots (e.g. ``master...HEAD``), the branch p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RevisionRange:
"""Represent a range of commits in a Git repository for comparing differences ``rev1`` is the "old" revision, and ``rev2``, the "new" revision which should be compared against ``rev1``. When parsing a revision range expression with triple dots (e.g. ``master...HEAD``), the branch point, or comm... | the_stack_v2_python_sparse | src/darker/git.py | akaihola/darker | train | 547 |
b0002832f82f3563a62e4aa5b8f65c44a8d274f2 | [
"self.alpha = 5 / len(states_df.index)\nlner = MB_MMPC_Lner(states_df, alpha, verbose, vtx_to_states, learn_later=True)\nlner.find_PC()\nself.vtx_to_nbors = lner.vtx_to_nbors\nHC_RandRestartLner.__init__(self, states_df, score_type, max_num_mtries, num_starts, ess, verbose, vtx_to_states)",
"m_approved = True\nif... | <|body_start_0|>
self.alpha = 5 / len(states_df.index)
lner = MB_MMPC_Lner(states_df, alpha, verbose, vtx_to_states, learn_later=True)
lner.find_PC()
self.vtx_to_nbors = lner.vtx_to_nbors
HC_RandRestartLner.__init__(self, states_df, score_type, max_num_mtries, num_starts, ess, ve... | The class HC_MMHC_rr_Lner (Hill Climbing Min-Max Hill Climbing Random Restart Learner) is a child of HC_RandomRestartLner. It adds to the latter a search at the beginning of the learning process of the PC ( parents children, aka neighbors) set of each node. This knowledge is then used in the move_allowed() function to ... | HC_MMHC_rr_Lner | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HC_MMHC_rr_Lner:
"""The class HC_MMHC_rr_Lner (Hill Climbing Min-Max Hill Climbing Random Restart Learner) is a child of HC_RandomRestartLner. It adds to the latter a search at the beginning of the learning process of the PC ( parents children, aka neighbors) set of each node. This knowledge is t... | stack_v2_sparse_classes_36k_train_004980 | 3,607 | permissive | [
{
"docstring": "Constructor Parameters ---------- alpha : float states_df : pandas.DataFrame score_type : str max_num_mtries : int num_starts : int ess : float Equivalent Sample Size, a parameter in BDEU scorer. Fudge factor that is supposed to grow as the amount of prior knowledge grows. verbose : bool vtx_to_... | 2 | null | Implement the Python class `HC_MMHC_rr_Lner` described below.
Class description:
The class HC_MMHC_rr_Lner (Hill Climbing Min-Max Hill Climbing Random Restart Learner) is a child of HC_RandomRestartLner. It adds to the latter a search at the beginning of the learning process of the PC ( parents children, aka neighbors... | Implement the Python class `HC_MMHC_rr_Lner` described below.
Class description:
The class HC_MMHC_rr_Lner (Hill Climbing Min-Max Hill Climbing Random Restart Learner) is a child of HC_RandomRestartLner. It adds to the latter a search at the beginning of the learning process of the PC ( parents children, aka neighbors... | 5b4a3055ea14c2ee9c80c339f759fe2b9c8c51e2 | <|skeleton|>
class HC_MMHC_rr_Lner:
"""The class HC_MMHC_rr_Lner (Hill Climbing Min-Max Hill Climbing Random Restart Learner) is a child of HC_RandomRestartLner. It adds to the latter a search at the beginning of the learning process of the PC ( parents children, aka neighbors) set of each node. This knowledge is t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HC_MMHC_rr_Lner:
"""The class HC_MMHC_rr_Lner (Hill Climbing Min-Max Hill Climbing Random Restart Learner) is a child of HC_RandomRestartLner. It adds to the latter a search at the beginning of the learning process of the PC ( parents children, aka neighbors) set of each node. This knowledge is then used in t... | the_stack_v2_python_sparse | learning/HC_MMHC_rr_Lner.py | artiste-qb-net/quantum-fog | train | 95 |
31a22d99baefc68a13279864e5804b3d3cb7b8ee | [
"session = Session()\ntry:\n item = find_organization_department(department_id, organization_code, session)\n if item is None:\n raise falcon.HTTPNotFound()\n resp.media = {'data': custom_asdict(item)}\nfinally:\n session.close()",
"session = Session()\ntry:\n item = find_organization_depart... | <|body_start_0|>
session = Session()
try:
item = find_organization_department(department_id, organization_code, session)
if item is None:
raise falcon.HTTPNotFound()
resp.media = {'data': custom_asdict(item)}
finally:
session.close(... | GET and DELETE an organization department. | Item | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Item:
"""GET and DELETE an organization department."""
def on_get(self, req, resp, organization_code, department_id):
"""GETs a single department of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code... | stack_v2_sparse_classes_36k_train_004981 | 5,562 | no_license | [
{
"docstring": "GETs a single department of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The code of the organization. :param department_id: The id of department to retrieve.",
"name": "on_get",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_016757 | Implement the Python class `Item` described below.
Class description:
GET and DELETE an organization department.
Method signatures and docstrings:
- def on_get(self, req, resp, organization_code, department_id): GETs a single department of an organization. :param req: See Falcon Request documentation. :param resp: Se... | Implement the Python class `Item` described below.
Class description:
GET and DELETE an organization department.
Method signatures and docstrings:
- def on_get(self, req, resp, organization_code, department_id): GETs a single department of an organization. :param req: See Falcon Request documentation. :param resp: Se... | 62723133595829230e5b589431a32cda3b092460 | <|skeleton|>
class Item:
"""GET and DELETE an organization department."""
def on_get(self, req, resp, organization_code, department_id):
"""GETs a single department of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Item:
"""GET and DELETE an organization department."""
def on_get(self, req, resp, organization_code, department_id):
"""GETs a single department of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The code of... | the_stack_v2_python_sparse | knoweak/api/resources/organization_department.py | psvaiter/knoweak-api | train | 0 |
28057cfa220cec3d46462f4d582dbe035c6d3bdf | [
"if not tree:\n return 0\nelse:\n left_height = self.max_depth_(tree.left)\n right_height = self.max_depth_(tree.right)\n return max(left_height, right_height) + 1",
"stack = []\nif tree is not None:\n stack.append((1, tree))\ndepth = 0\nwhile stack:\n curr_depth, tree = stack.pop()\n if tree... | <|body_start_0|>
if not tree:
return 0
else:
left_height = self.max_depth_(tree.left)
right_height = self.max_depth_(tree.right)
return max(left_height, right_height) + 1
<|end_body_0|>
<|body_start_1|>
stack = []
if tree is not None:
... | MaxTreeDepth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxTreeDepth:
def max_depth_(self, tree: TreeNode) -> int:
"""Approach: Recursion :param tree: :return:"""
<|body_0|>
def max_depth(self, tree: TreeNode) -> int:
"""Approach: Iterative :param self: :param tree: :return:"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_004982 | 1,034 | no_license | [
{
"docstring": "Approach: Recursion :param tree: :return:",
"name": "max_depth_",
"signature": "def max_depth_(self, tree: TreeNode) -> int"
},
{
"docstring": "Approach: Iterative :param self: :param tree: :return:",
"name": "max_depth",
"signature": "def max_depth(self, tree: TreeNode) ... | 2 | null | Implement the Python class `MaxTreeDepth` described below.
Class description:
Implement the MaxTreeDepth class.
Method signatures and docstrings:
- def max_depth_(self, tree: TreeNode) -> int: Approach: Recursion :param tree: :return:
- def max_depth(self, tree: TreeNode) -> int: Approach: Iterative :param self: :par... | Implement the Python class `MaxTreeDepth` described below.
Class description:
Implement the MaxTreeDepth class.
Method signatures and docstrings:
- def max_depth_(self, tree: TreeNode) -> int: Approach: Recursion :param tree: :return:
- def max_depth(self, tree: TreeNode) -> int: Approach: Iterative :param self: :par... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class MaxTreeDepth:
def max_depth_(self, tree: TreeNode) -> int:
"""Approach: Recursion :param tree: :return:"""
<|body_0|>
def max_depth(self, tree: TreeNode) -> int:
"""Approach: Iterative :param self: :param tree: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxTreeDepth:
def max_depth_(self, tree: TreeNode) -> int:
"""Approach: Recursion :param tree: :return:"""
if not tree:
return 0
else:
left_height = self.max_depth_(tree.left)
right_height = self.max_depth_(tree.right)
return max(left_hei... | the_stack_v2_python_sparse | data_structures/tree_node/depth_of_a tree.py | Shiv2157k/leet_code | train | 1 | |
04ae1e6821d1937e43fe1fe110658070ecf36309 | [
"A.sort()\nfor i in range(len(A)):\n if not K:\n break\n if A[i] < 0:\n A[i] = -A[i]\n K -= 1\nif K % 2 == 0:\n return sum(A)\nelse:\n return sum(A) - 2 * min(A)",
"for i in range(K):\n idx = A.index(min(A))\n A[idx] = -A[idx]\nreturn sum(A)"
] | <|body_start_0|>
A.sort()
for i in range(len(A)):
if not K:
break
if A[i] < 0:
A[i] = -A[i]
K -= 1
if K % 2 == 0:
return sum(A)
else:
return sum(A) - 2 * min(A)
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestSumAfterKNegations(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def largestSumAfterKNegations2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004983 | 1,756 | no_license | [
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "largestSumAfterKNegations",
"signature": "def largestSumAfterKNegations(self, A, K)"
},
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "largestSumAfterKNegations2",
"signature": "def largestSumA... | 2 | stack_v2_sparse_classes_30k_train_002341 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestSumAfterKNegations(self, A, K): :type A: List[int] :type K: int :rtype: int
- def largestSumAfterKNegations2(self, A, K): :type A: List[int] :type K: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestSumAfterKNegations(self, A, K): :type A: List[int] :type K: int :rtype: int
- def largestSumAfterKNegations2(self, A, K): :type A: List[int] :type K: int :rtype: int
... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def largestSumAfterKNegations(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def largestSumAfterKNegations2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestSumAfterKNegations(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
A.sort()
for i in range(len(A)):
if not K:
break
if A[i] < 0:
A[i] = -A[i]
K -= 1
if K % 2 == 0:
... | the_stack_v2_python_sparse | python/1005.maximize-sum-of-array-after-k-negations.py | tainenko/Leetcode2019 | train | 5 | |
84bac932a8b43d3ab81a6b7f4a940cc04a30dbf9 | [
"base.Action.__init__(self, self.__loadDicom)\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx\nself.__frame = frame\nself.enabled = fsldcm.enabled()",
"def onLoad(overlays):\n if len(overlays) == 0:\n return\n self.__overlayList.extend(overlays)\n self.__displayCtx.selectedOverla... | <|body_start_0|>
base.Action.__init__(self, self.__loadDicom)
self.__overlayList = overlayList
self.__displayCtx = displayCtx
self.__frame = frame
self.enabled = fsldcm.enabled()
<|end_body_0|>
<|body_start_1|>
def onLoad(overlays):
if len(overlays) == 0:
... | The ``LoadDicomAction`` is an :class:`.Action` which allows the user to load images from a DICOM directory. When invoked, the ``LoadDicomAction`` does the following: 1. Prompts the user to select a DICOM directory 2. Identifies the data series that are present in the directory 3. Prompts the user to select which series... | LoadDicomAction | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadDicomAction:
"""The ``LoadDicomAction`` is an :class:`.Action` which allows the user to load images from a DICOM directory. When invoked, the ``LoadDicomAction`` does the following: 1. Prompts the user to select a DICOM directory 2. Identifies the data series that are present in the directory... | stack_v2_sparse_classes_36k_train_004984 | 13,722 | permissive | [
{
"docstring": "Create a ``LoadDicomAction``. :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": "Called when... | 2 | null | Implement the Python class `LoadDicomAction` described below.
Class description:
The ``LoadDicomAction`` is an :class:`.Action` which allows the user to load images from a DICOM directory. When invoked, the ``LoadDicomAction`` does the following: 1. Prompts the user to select a DICOM directory 2. Identifies the data s... | Implement the Python class `LoadDicomAction` described below.
Class description:
The ``LoadDicomAction`` is an :class:`.Action` which allows the user to load images from a DICOM directory. When invoked, the ``LoadDicomAction`` does the following: 1. Prompts the user to select a DICOM directory 2. Identifies the data s... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class LoadDicomAction:
"""The ``LoadDicomAction`` is an :class:`.Action` which allows the user to load images from a DICOM directory. When invoked, the ``LoadDicomAction`` does the following: 1. Prompts the user to select a DICOM directory 2. Identifies the data series that are present in the directory... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadDicomAction:
"""The ``LoadDicomAction`` is an :class:`.Action` which allows the user to load images from a DICOM directory. When invoked, the ``LoadDicomAction`` does the following: 1. Prompts the user to select a DICOM directory 2. Identifies the data series that are present in the directory 3. Prompts t... | the_stack_v2_python_sparse | fsleyes/actions/loaddicom.py | sanjayankur31/fsleyes | train | 1 |
4f2dfcb0669d0d5f97bfa861e7bc2bf2859b064e | [
"urls = ['https://gz.lianjia.com/zufang/pg{}/'.format(i) for i in range(1, 4)]\nfor url in urls:\n yield scrapy.Request(url=url, callback=self.parse, headers=self.headers)",
"for house in response.xpath('//div[@class=\"content__list--item\"]'):\n item = LianjiaItem()\n title = house.xpath('.//p[@class=\"... | <|body_start_0|>
urls = ['https://gz.lianjia.com/zufang/pg{}/'.format(i) for i in range(1, 4)]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse, headers=self.headers)
<|end_body_0|>
<|body_start_1|>
for house in response.xpath('//div[@class="content__list--item"]')... | 链家租房数据爬虫 | LianjiaSpiderSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LianjiaSpiderSpider:
"""链家租房数据爬虫"""
def start_requests(self):
"""生成爬取链接,最大页数为100页"""
<|body_0|>
def parse(self, response):
"""解析租房列表页面 :param:response :return:"""
<|body_1|>
def detail_parse(self, response):
"""解析租房的详情,接收parse的item, 增加更多的item... | stack_v2_sparse_classes_36k_train_004985 | 6,297 | no_license | [
{
"docstring": "生成爬取链接,最大页数为100页",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "解析租房列表页面 :param:response :return:",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "解析租房的详情,接收parse的item, 增加更多的item,更新独栋公寓的item :pa... | 3 | stack_v2_sparse_classes_30k_train_010387 | Implement the Python class `LianjiaSpiderSpider` described below.
Class description:
链家租房数据爬虫
Method signatures and docstrings:
- def start_requests(self): 生成爬取链接,最大页数为100页
- def parse(self, response): 解析租房列表页面 :param:response :return:
- def detail_parse(self, response): 解析租房的详情,接收parse的item, 增加更多的item,更新独栋公寓的item :p... | Implement the Python class `LianjiaSpiderSpider` described below.
Class description:
链家租房数据爬虫
Method signatures and docstrings:
- def start_requests(self): 生成爬取链接,最大页数为100页
- def parse(self, response): 解析租房列表页面 :param:response :return:
- def detail_parse(self, response): 解析租房的详情,接收parse的item, 增加更多的item,更新独栋公寓的item :p... | a38f10bff22f049c6065f744be919a1fe7910268 | <|skeleton|>
class LianjiaSpiderSpider:
"""链家租房数据爬虫"""
def start_requests(self):
"""生成爬取链接,最大页数为100页"""
<|body_0|>
def parse(self, response):
"""解析租房列表页面 :param:response :return:"""
<|body_1|>
def detail_parse(self, response):
"""解析租房的详情,接收parse的item, 增加更多的item... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LianjiaSpiderSpider:
"""链家租房数据爬虫"""
def start_requests(self):
"""生成爬取链接,最大页数为100页"""
urls = ['https://gz.lianjia.com/zufang/pg{}/'.format(i) for i in range(1, 4)]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse, headers=self.headers)
def parse(s... | the_stack_v2_python_sparse | lianjia/lianjia/spiders/lianjia_spider.py | xiaotiepi/Web_Spider | train | 0 |
f4fbd258fed56e1a5299cbaa58ff581a312778ed | [
"self.num_categoricals = get_num_z_categoricals(model_size, override=num_categoricals)\nself.num_classes_per_categorical = get_num_z_classes(model_size, override=num_classes_per_categorical)\nsuper().__init__(name=f'z{self.num_categoricals}x{self.num_classes_per_categorical}')\nself.z_generating_layer = tf.keras.la... | <|body_start_0|>
self.num_categoricals = get_num_z_categoricals(model_size, override=num_categoricals)
self.num_classes_per_categorical = get_num_z_classes(model_size, override=num_classes_per_categorical)
super().__init__(name=f'z{self.num_categoricals}x{self.num_classes_per_categorical}')
... | A representation (z-state) generating layer. The value for z is the result of sampling from a categorical distribution with shape B x `num_classes`. So a computed z-state consists of `num_categoricals` one-hot vectors, each of size `num_classes_per_categorical`. | RepresentationLayer | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepresentationLayer:
"""A representation (z-state) generating layer. The value for z is the result of sampling from a categorical distribution with shape B x `num_classes`. So a computed z-state consists of `num_categoricals` one-hot vectors, each of size `num_classes_per_categorical`."""
de... | stack_v2_sparse_classes_36k_train_004986 | 5,719 | permissive | [
{
"docstring": "Initializes a RepresentationLayer instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Use None for manually setting the different parameters. num_categoricals: Overrides the number of categoricals used in the z-states. In [1], 32 is used for any model size. num_clas... | 2 | stack_v2_sparse_classes_30k_train_009674 | Implement the Python class `RepresentationLayer` described below.
Class description:
A representation (z-state) generating layer. The value for z is the result of sampling from a categorical distribution with shape B x `num_classes`. So a computed z-state consists of `num_categoricals` one-hot vectors, each of size `n... | Implement the Python class `RepresentationLayer` described below.
Class description:
A representation (z-state) generating layer. The value for z is the result of sampling from a categorical distribution with shape B x `num_classes`. So a computed z-state consists of `num_categoricals` one-hot vectors, each of size `n... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class RepresentationLayer:
"""A representation (z-state) generating layer. The value for z is the result of sampling from a categorical distribution with shape B x `num_classes`. So a computed z-state consists of `num_categoricals` one-hot vectors, each of size `num_classes_per_categorical`."""
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepresentationLayer:
"""A representation (z-state) generating layer. The value for z is the result of sampling from a categorical distribution with shape B x `num_classes`. So a computed z-state consists of `num_categoricals` one-hot vectors, each of size `num_classes_per_categorical`."""
def __init__(se... | the_stack_v2_python_sparse | rllib/algorithms/dreamerv3/tf/models/components/representation_layer.py | ray-project/ray | train | 29,482 |
43bc742e88650eb5c8cbe3c29336985cf2a8c8c7 | [
"super(ChamferkNNDist, self).__init__()\nself.chamfer_dist = ChamferDist(method=chamfer_method)\nself.knn_dist = KNNDist(k=knn_k, alpha=knn_alpha)\nself.w1 = chamfer_weight\nself.w2 = knn_weight",
"chamfer_loss = self.chamfer_dist(adv_pc, ori_pc, weights=weights, batch_avg=batch_avg)\nknn_loss = self.knn_dist(adv... | <|body_start_0|>
super(ChamferkNNDist, self).__init__()
self.chamfer_dist = ChamferDist(method=chamfer_method)
self.knn_dist = KNNDist(k=knn_k, alpha=knn_alpha)
self.w1 = chamfer_weight
self.w2 = knn_weight
<|end_body_0|>
<|body_start_1|>
chamfer_loss = self.chamfer_dist... | ChamferkNNDist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults... | stack_v2_sparse_classes_36k_train_004987 | 11,583 | permissive | [
{
"docstring": "Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults to 5. knn_alpha (float, optional): alpha in kNN. Defaults to 1.1. chamfer_weight (float, optional): weight factor. Defaults to 5.. kn... | 2 | stack_v2_sparse_classes_30k_train_009032 | Implement the Python class `ChamferkNNDist` described below.
Class description:
Implement the ChamferkNNDist class.
Method signatures and docstrings:
- def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0): Geometry-aware distance function of AAAI'20 paper. Args: ch... | Implement the Python class `ChamferkNNDist` described below.
Class description:
Implement the ChamferkNNDist class.
Method signatures and docstrings:
- def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0): Geometry-aware distance function of AAAI'20 paper. Args: ch... | 4e2462b66fa1eac90cfbf61fa0dc635d223fdf2f | <|skeleton|>
class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults to 5. knn_alp... | the_stack_v2_python_sparse | baselines/attack/util/dist_utils.py | code-roamer/IF-Defense | train | 0 | |
19c1d2479fd5b41bbb16226b7237fcbed7863853 | [
"\"\"\" ie. not a reentrant loop \"\"\"\nFirstZ = self.Content[0].Z()\nif FirstZ <= 0.0:\n for ResidueI in self.Content:\n if ResidueI.Z() >= 0.0:\n return True\nelif FirstZ >= 0.0:\n for ResidueI in self.Content:\n if ResidueI.Z() <= 0.0:\n ... | <|body_start_0|>
""" ie. not a reentrant loop """
FirstZ = self.Content[0].Z()
if FirstZ <= 0.0:
for ResidueI in self.Content:
if ResidueI.Z() >= 0.0:
return True
elif FirstZ >= 0.0:
for Re... | stores Membrane Segment of Protein Chain | MSegment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSegment:
"""stores Membrane Segment of Protein Chain"""
def CrossingMembrane(self, MembraneBorders=[-10.0, 10.0]):
"""checks whether MSegment instance is crossing the lipid Membrane"""
<|body_0|>
def TiltConsistent(self):
"""checks whether Tilt Values are calcul... | stack_v2_sparse_classes_36k_train_004988 | 12,633 | no_license | [
{
"docstring": "checks whether MSegment instance is crossing the lipid Membrane",
"name": "CrossingMembrane",
"signature": "def CrossingMembrane(self, MembraneBorders=[-10.0, 10.0])"
},
{
"docstring": "checks whether Tilt Values are calculated by PCA and MassCenter method are consistent",
"n... | 6 | stack_v2_sparse_classes_30k_train_015023 | Implement the Python class `MSegment` described below.
Class description:
stores Membrane Segment of Protein Chain
Method signatures and docstrings:
- def CrossingMembrane(self, MembraneBorders=[-10.0, 10.0]): checks whether MSegment instance is crossing the lipid Membrane
- def TiltConsistent(self): checks whether T... | Implement the Python class `MSegment` described below.
Class description:
stores Membrane Segment of Protein Chain
Method signatures and docstrings:
- def CrossingMembrane(self, MembraneBorders=[-10.0, 10.0]): checks whether MSegment instance is crossing the lipid Membrane
- def TiltConsistent(self): checks whether T... | 1447592c068ca52cb9ac82cabb36191b78b638e4 | <|skeleton|>
class MSegment:
"""stores Membrane Segment of Protein Chain"""
def CrossingMembrane(self, MembraneBorders=[-10.0, 10.0]):
"""checks whether MSegment instance is crossing the lipid Membrane"""
<|body_0|>
def TiltConsistent(self):
"""checks whether Tilt Values are calcul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MSegment:
"""stores Membrane Segment of Protein Chain"""
def CrossingMembrane(self, MembraneBorders=[-10.0, 10.0]):
"""checks whether MSegment instance is crossing the lipid Membrane"""
""" ie. not a reentrant loop """
FirstZ = self.Content[0... | the_stack_v2_python_sparse | myproject/myproject/myapp/ProteinChainModule.py | michalstepniewski/TMProteins | train | 0 |
0fb8d4ef80d8720ee7fac0e41a20ed460b84501b | [
"res = 0\nfor i in range(len(height)):\n max_left_height, max_right_height = (0, 0)\n for j in range(i):\n if height[j] > height[i]:\n max_left_height = max(max_left_height, height[j])\n for k in range(i + 1, len(height)):\n if height[k] > height[i]:\n max_right_height =... | <|body_start_0|>
res = 0
for i in range(len(height)):
max_left_height, max_right_height = (0, 0)
for j in range(i):
if height[j] > height[i]:
max_left_height = max(max_left_height, height[j])
for k in range(i + 1, len(height)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height: List[int]) -> int:
"""暴力,遍历每个槽,看它左边最高的柱子以及右边最高的柱子,是否这两个柱子的最小值 要比当前槽的高度要高,如果高,才能接到该槽所盛放的雨水,盛放量为: min(max_left_height, max_right_heigh) - cur_height 时间复杂度:O(N^2) 本题的关键就是 左max_height以及右max_height"""
<|body_0|>
def trap_dp(self, height: List[int]... | stack_v2_sparse_classes_36k_train_004989 | 3,075 | no_license | [
{
"docstring": "暴力,遍历每个槽,看它左边最高的柱子以及右边最高的柱子,是否这两个柱子的最小值 要比当前槽的高度要高,如果高,才能接到该槽所盛放的雨水,盛放量为: min(max_left_height, max_right_heigh) - cur_height 时间复杂度:O(N^2) 本题的关键就是 左max_height以及右max_height",
"name": "trap",
"signature": "def trap(self, height: List[int]) -> int"
},
{
"docstring": "上面在计算左边最高和右边最高的时... | 3 | stack_v2_sparse_classes_30k_train_005392 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height: List[int]) -> int: 暴力,遍历每个槽,看它左边最高的柱子以及右边最高的柱子,是否这两个柱子的最小值 要比当前槽的高度要高,如果高,才能接到该槽所盛放的雨水,盛放量为: min(max_left_height, max_right_heigh) - cur_height 时间复杂度:O(N^2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height: List[int]) -> int: 暴力,遍历每个槽,看它左边最高的柱子以及右边最高的柱子,是否这两个柱子的最小值 要比当前槽的高度要高,如果高,才能接到该槽所盛放的雨水,盛放量为: min(max_left_height, max_right_heigh) - cur_height 时间复杂度:O(N^2... | 3fa96c81f92595cf076ad675ba332e2b0eb0e071 | <|skeleton|>
class Solution:
def trap(self, height: List[int]) -> int:
"""暴力,遍历每个槽,看它左边最高的柱子以及右边最高的柱子,是否这两个柱子的最小值 要比当前槽的高度要高,如果高,才能接到该槽所盛放的雨水,盛放量为: min(max_left_height, max_right_heigh) - cur_height 时间复杂度:O(N^2) 本题的关键就是 左max_height以及右max_height"""
<|body_0|>
def trap_dp(self, height: List[int]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height: List[int]) -> int:
"""暴力,遍历每个槽,看它左边最高的柱子以及右边最高的柱子,是否这两个柱子的最小值 要比当前槽的高度要高,如果高,才能接到该槽所盛放的雨水,盛放量为: min(max_left_height, max_right_heigh) - cur_height 时间复杂度:O(N^2) 本题的关键就是 左max_height以及右max_height"""
res = 0
for i in range(len(height)):
max_left... | the_stack_v2_python_sparse | 2020-04/4-02/42接雨水/42.py | Annihilation7/Leetcode-Love | train | 0 | |
23cd80f374160d6a53637517c5389df4ae9ea7fc | [
"super(GeometryBase, self).__init__(cls_name=cls_name, type_name='object', instance_name=instance_name)\nself.mesh = None\nself.mesh_to_base = CoordinateSystemTransformBase(('object', 'mesh'), ('object', 'base'))\nself.mesh_to_xml = CoordinateSystemTransformBase(('object', 'mesh'), ('object', 'xmlOrURDF'))",
"if ... | <|body_start_0|>
super(GeometryBase, self).__init__(cls_name=cls_name, type_name='object', instance_name=instance_name)
self.mesh = None
self.mesh_to_base = CoordinateSystemTransformBase(('object', 'mesh'), ('object', 'base'))
self.mesh_to_xml = CoordinateSystemTransformBase(('object', '... | ObjectGeometryBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectGeometryBase:
def __init__(self, cls_name, instance_name):
"""pass the class and instance name on @param cls_name: derived class @param instance_name: Optional string for name of object"""
<|body_0|>
def get_vertices(self):
"""Generator function that returns al... | stack_v2_sparse_classes_36k_train_004990 | 2,862 | no_license | [
{
"docstring": "pass the class and instance name on @param cls_name: derived class @param instance_name: Optional string for name of object",
"name": "__init__",
"signature": "def __init__(self, cls_name, instance_name)"
},
{
"docstring": "Generator function that returns all vertices in the form... | 2 | stack_v2_sparse_classes_30k_train_007149 | Implement the Python class `ObjectGeometryBase` described below.
Class description:
Implement the ObjectGeometryBase class.
Method signatures and docstrings:
- def __init__(self, cls_name, instance_name): pass the class and instance name on @param cls_name: derived class @param instance_name: Optional string for name... | Implement the Python class `ObjectGeometryBase` described below.
Class description:
Implement the ObjectGeometryBase class.
Method signatures and docstrings:
- def __init__(self, cls_name, instance_name): pass the class and instance name on @param cls_name: derived class @param instance_name: Optional string for name... | 951be2e19c10108f390662d0535faed1dc5058bd | <|skeleton|>
class ObjectGeometryBase:
def __init__(self, cls_name, instance_name):
"""pass the class and instance name on @param cls_name: derived class @param instance_name: Optional string for name of object"""
<|body_0|>
def get_vertices(self):
"""Generator function that returns al... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectGeometryBase:
def __init__(self, cls_name, instance_name):
"""pass the class and instance name on @param cls_name: derived class @param instance_name: Optional string for name of object"""
super(GeometryBase, self).__init__(cls_name=cls_name, type_name='object', instance_name=instance_na... | the_stack_v2_python_sparse | geometry_classes/object_geometry_base.py | buckmole/KinovaGrasping | train | 0 | |
da710ea156ccda3cb46ad8b77295ef658655f03e | [
"self.service = DooCppSubService()\nself.service.init(host, port)\nself.server_id = server_id\nself.licences = licences",
"self.service.send(cmd, self.server_id, self.licences, self.params, is_sub=True)\nresult = self.service.receive()\nif result['response_status'] == 0 and result['response_details'] == 'O.K.':\n... | <|body_start_0|>
self.service = DooCppSubService()
self.service.init(host, port)
self.server_id = server_id
self.licences = licences
<|end_body_0|>
<|body_start_1|>
self.service.send(cmd, self.server_id, self.licences, self.params, is_sub=True)
result = self.service.rece... | SubService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubService:
def __init__(self, host, port, server_id, licences):
"""初始化 :param host: :param port: :param server_id: :param licences:"""
<|body_0|>
def sub(self, cmd):
"""订阅订单 :return"""
<|body_1|>
def sub_order(self):
"""订阅order订单 :return"""
... | stack_v2_sparse_classes_36k_train_004991 | 3,723 | no_license | [
{
"docstring": "初始化 :param host: :param port: :param server_id: :param licences:",
"name": "__init__",
"signature": "def __init__(self, host, port, server_id, licences)"
},
{
"docstring": "订阅订单 :return",
"name": "sub",
"signature": "def sub(self, cmd)"
},
{
"docstring": "订阅order订... | 6 | null | Implement the Python class `SubService` described below.
Class description:
Implement the SubService class.
Method signatures and docstrings:
- def __init__(self, host, port, server_id, licences): 初始化 :param host: :param port: :param server_id: :param licences:
- def sub(self, cmd): 订阅订单 :return
- def sub_order(self)... | Implement the Python class `SubService` described below.
Class description:
Implement the SubService class.
Method signatures and docstrings:
- def __init__(self, host, port, server_id, licences): 初始化 :param host: :param port: :param server_id: :param licences:
- def sub(self, cmd): 订阅订单 :return
- def sub_order(self)... | 8120cc60437ef92e5a462634360e107917d8d9d2 | <|skeleton|>
class SubService:
def __init__(self, host, port, server_id, licences):
"""初始化 :param host: :param port: :param server_id: :param licences:"""
<|body_0|>
def sub(self, cmd):
"""订阅订单 :return"""
<|body_1|>
def sub_order(self):
"""订阅order订单 :return"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubService:
def __init__(self, host, port, server_id, licences):
"""初始化 :param host: :param port: :param server_id: :param licences:"""
self.service = DooCppSubService()
self.service.init(host, port)
self.server_id = server_id
self.licences = licences
def sub(self,... | the_stack_v2_python_sparse | cpp_service/SubService.py | Samuel875154270/src | train | 0 | |
4477298cab0656c2197b1e224c8392b77378711d | [
"curboard = response.selector.xpath('//h2[contains(@class, \"forum-title\")]/a/text()').extract()\nif curboard[0].lower() == 'Merseyside/Fylde Coast/Cumbrian Venues/Directions'.lower():\n last_link = None\nelif curboard[0].lower() == 'Easy Access Venues/Directions For All Areas'.lower():\n last_link = 30\neli... | <|body_start_0|>
curboard = response.selector.xpath('//h2[contains(@class, "forum-title")]/a/text()').extract()
if curboard[0].lower() == 'Merseyside/Fylde Coast/Cumbrian Venues/Directions'.lower():
last_link = None
elif curboard[0].lower() == 'Easy Access Venues/Directions For All A... | scrape reports from angling addicts forum | WirralSeaFishingVenuesSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WirralSeaFishingVenuesSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33... | stack_v2_sparse_classes_36k_train_004992 | 9,325 | no_license | [
{
"docstring": "generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33&start=30 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33&start=3420 assert isinstance(response, scra... | 3 | null | Implement the Python class `WirralSeaFishingVenuesSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://w... | Implement the Python class `WirralSeaFishingVenuesSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://w... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class WirralSeaFishingVenuesSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WirralSeaFishingVenuesSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33&start=30 htt... | the_stack_v2_python_sparse | imgscrape/spiders/wirralseafishing.py | gmonkman/python | train | 0 |
97dd1b37636d5a29cf4b624ffa5550946ac1e874 | [
"self._axis = axis\nself._title = title\nself._xlabel = x_label\nself._ylabel = y_label\nself.canvas = scene.SceneCanvas(keys='interactive', bgcolor=bgcolor, show=False, title=name, **cargs)\nif axis:\n grid = self.canvas.central_widget.add_grid(margin=10)\n grid.spacing = 0\n self._titleObj = scene.Label(... | <|body_start_0|>
self._axis = axis
self._title = title
self._xlabel = x_label
self._ylabel = y_label
self.canvas = scene.SceneCanvas(keys='interactive', bgcolor=bgcolor, show=False, title=name, **cargs)
if axis:
grid = self.canvas.central_widget.add_grid(margi... | Create a canvas with an embeded axis. | AxisCanvas | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisCanvas:
"""Create a canvas with an embeded axis."""
def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={}):
... | stack_v2_sparse_classes_36k_train_004993 | 11,761 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={})"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_002826 | Implement the Python class `AxisCanvas` described below.
Class description:
Create a canvas with an embeded axis.
Method signatures and docstrings:
- def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, n... | Implement the Python class `AxisCanvas` described below.
Class description:
Create a canvas with an embeded axis.
Method signatures and docstrings:
- def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, n... | b5f480a16555a10b0032465699a0c371e2be31db | <|skeleton|>
class AxisCanvas:
"""Create a canvas with an embeded axis."""
def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={}):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxisCanvas:
"""Create a canvas with an embeded axis."""
def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={}):
"""Init."... | the_stack_v2_python_sparse | visbrain/ndviz/interface/uiInit.py | christian-oreilly/visbrain | train | 0 |
8c0bdd9dfc85dcb79806a87e3786c5c848a81be0 | [
"super(ArcFaceLoss, self).__init__()\nself.scale = scale\nself.mergin = mergin\nself.arccos = torch.arccos\nself.cross_entropy = nn.CrossEntropyLoss()",
"one_hot = torch.zeros(logits.size(), device='cuda')\none_hot.scatter_(1, labels.view(-1, 1).long(), 1)\ntheta = torch.arccos(logits)\ntheta = theta + self.mergi... | <|body_start_0|>
super(ArcFaceLoss, self).__init__()
self.scale = scale
self.mergin = mergin
self.arccos = torch.arccos
self.cross_entropy = nn.CrossEntropyLoss()
<|end_body_0|>
<|body_start_1|>
one_hot = torch.zeros(logits.size(), device='cuda')
one_hot.scatter_... | ArcFaceLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArcFaceLoss:
def __init__(self, scale=26.0, mergin=0.5):
"""scale: parameter "s" in Arcface paper. Feature scale parameter mergin: parameter "m" in ArcFace paper."""
<|body_0|>
def forward(self, logits, labels):
"""logits: feature through by ArcFaceLayer Module. e.g.... | stack_v2_sparse_classes_36k_train_004994 | 1,858 | permissive | [
{
"docstring": "scale: parameter \"s\" in Arcface paper. Feature scale parameter mergin: parameter \"m\" in ArcFace paper.",
"name": "__init__",
"signature": "def __init__(self, scale=26.0, mergin=0.5)"
},
{
"docstring": "logits: feature through by ArcFaceLayer Module. e.g. logits' value is cosi... | 2 | stack_v2_sparse_classes_30k_train_021030 | Implement the Python class `ArcFaceLoss` described below.
Class description:
Implement the ArcFaceLoss class.
Method signatures and docstrings:
- def __init__(self, scale=26.0, mergin=0.5): scale: parameter "s" in Arcface paper. Feature scale parameter mergin: parameter "m" in ArcFace paper.
- def forward(self, logit... | Implement the Python class `ArcFaceLoss` described below.
Class description:
Implement the ArcFaceLoss class.
Method signatures and docstrings:
- def __init__(self, scale=26.0, mergin=0.5): scale: parameter "s" in Arcface paper. Feature scale parameter mergin: parameter "m" in ArcFace paper.
- def forward(self, logit... | d01ba3dcba292b06c23d2e8c7a68a4c15d005ea7 | <|skeleton|>
class ArcFaceLoss:
def __init__(self, scale=26.0, mergin=0.5):
"""scale: parameter "s" in Arcface paper. Feature scale parameter mergin: parameter "m" in ArcFace paper."""
<|body_0|>
def forward(self, logits, labels):
"""logits: feature through by ArcFaceLayer Module. e.g.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArcFaceLoss:
def __init__(self, scale=26.0, mergin=0.5):
"""scale: parameter "s" in Arcface paper. Feature scale parameter mergin: parameter "m" in ArcFace paper."""
super(ArcFaceLoss, self).__init__()
self.scale = scale
self.mergin = mergin
self.arccos = torch.arccos
... | the_stack_v2_python_sparse | src/arcface.py | rinchieeeee/cnn-pipline-for-data-competition | train | 0 | |
e725164a00aec9092d9529d696a3b55ed3a5b6fa | [
"channel_options = self.declaration.recipe_options or {}\ntask_recipe_options = task_recipe_options or {}\nself.check_conflicting_options(channel_options, task_recipe_options)\nrecipe_options = {**task_recipe_options, **channel_options}\nreturn recipe_options",
"double_specified_options = set(task_recipe_options.... | <|body_start_0|>
channel_options = self.declaration.recipe_options or {}
task_recipe_options = task_recipe_options or {}
self.check_conflicting_options(channel_options, task_recipe_options)
recipe_options = {**task_recipe_options, **channel_options}
return recipe_options
<|end_bo... | A channel represents a connection to Salesforce via a username. It can also have recipe options and other documented properties. https://github.com/SFDO-Tooling/Snowfakery/search?q=ChannelDeclaration | ChannelConfig | [
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelConfig:
"""A channel represents a connection to Salesforce via a username. It can also have recipe options and other documented properties. https://github.com/SFDO-Tooling/Snowfakery/search?q=ChannelDeclaration"""
def merge_recipe_options(self, task_recipe_options):
"""Merge t... | stack_v2_sparse_classes_36k_train_004995 | 28,418 | permissive | [
{
"docstring": "Merge the recipe options from the channel declaration with those from the task config",
"name": "merge_recipe_options",
"signature": "def merge_recipe_options(self, task_recipe_options)"
},
{
"docstring": "Check that options do not conflict",
"name": "check_conflicting_option... | 2 | stack_v2_sparse_classes_30k_train_000898 | Implement the Python class `ChannelConfig` described below.
Class description:
A channel represents a connection to Salesforce via a username. It can also have recipe options and other documented properties. https://github.com/SFDO-Tooling/Snowfakery/search?q=ChannelDeclaration
Method signatures and docstrings:
- def... | Implement the Python class `ChannelConfig` described below.
Class description:
A channel represents a connection to Salesforce via a username. It can also have recipe options and other documented properties. https://github.com/SFDO-Tooling/Snowfakery/search?q=ChannelDeclaration
Method signatures and docstrings:
- def... | 9ccf3c9566f78c6e9102ac214db30470cef660c1 | <|skeleton|>
class ChannelConfig:
"""A channel represents a connection to Salesforce via a username. It can also have recipe options and other documented properties. https://github.com/SFDO-Tooling/Snowfakery/search?q=ChannelDeclaration"""
def merge_recipe_options(self, task_recipe_options):
"""Merge t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChannelConfig:
"""A channel represents a connection to Salesforce via a username. It can also have recipe options and other documented properties. https://github.com/SFDO-Tooling/Snowfakery/search?q=ChannelDeclaration"""
def merge_recipe_options(self, task_recipe_options):
"""Merge the recipe opt... | the_stack_v2_python_sparse | cumulusci/tasks/bulkdata/snowfakery.py | SFDO-Tooling/CumulusCI | train | 226 |
d91c6af0dd2ba70391d785b296f46f9070e0a9d0 | [
"self.name = name\nself.scope = scope\nself.app_bundle_identifier = app_bundle_identifier\nself.provider_bundle_identifier = provider_bundle_identifier\nself.provider_configuration = provider_configuration\nself.uses_cert = uses_cert",
"if dictionary is None:\n return None\nname = dictionary.get('name')\nscope... | <|body_start_0|>
self.name = name
self.scope = scope
self.app_bundle_identifier = app_bundle_identifier
self.provider_bundle_identifier = provider_bundle_identifier
self.provider_configuration = provider_configuration
self.uses_cert = uses_cert
<|end_body_0|>
<|body_star... | Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, withoutAny, or withoutAll) and a set of tags of the devices to be as... | UpdateNetworkSmProfileUmbrellaModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkSmProfileUmbrellaModel:
"""Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, witho... | stack_v2_sparse_classes_36k_train_004996 | 3,762 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkSmProfileUmbrellaModel class",
"name": "__init__",
"signature": "def __init__(self, name=None, scope=None, app_bundle_identifier=None, provider_bundle_identifier=None, provider_configuration=None, uses_cert=None)"
},
{
"docstring": "Creates an ins... | 2 | stack_v2_sparse_classes_30k_train_003207 | Implement the Python class `UpdateNetworkSmProfileUmbrellaModel` described below.
Class description:
Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (on... | Implement the Python class `UpdateNetworkSmProfileUmbrellaModel` described below.
Class description:
Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (on... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkSmProfileUmbrellaModel:
"""Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, witho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateNetworkSmProfileUmbrellaModel:
"""Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, withoutAny, or wit... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_sm_profile_umbrella_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
6f5bf1475447565543f34822df10f7e59262fcd2 | [
"super(Worker, self).__init__()\nself.func = func\nself.args = args\nself.kwargs = kwargs",
"try:\n result = self.func(*self.args, **self.kwargs)\n self.result.emit(result)\nexcept:\n import sys\n self.error.emit(sys.exc_info())"
] | <|body_start_0|>
super(Worker, self).__init__()
self.func = func
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
try:
result = self.func(*self.args, **self.kwargs)
self.result.emit(result)
except:
import sys
... | Worker | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
def __init__(self, func, *args, **kwargs):
"""Execute a function call on a different QThread :param func: The function object to call :param args: arguments to pass to the function :param kwargs: kwargs to pass to the function"""
<|body_0|>
def run(self):
"""... | stack_v2_sparse_classes_36k_train_004997 | 1,096 | permissive | [
{
"docstring": "Execute a function call on a different QThread :param func: The function object to call :param args: arguments to pass to the function :param kwargs: kwargs to pass to the function",
"name": "__init__",
"signature": "def __init__(self, func, *args, **kwargs)"
},
{
"docstring": "I... | 2 | stack_v2_sparse_classes_30k_train_020071 | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, func, *args, **kwargs): Execute a function call on a different QThread :param func: The function object to call :param args: arguments to pass to the function :par... | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, func, *args, **kwargs): Execute a function call on a different QThread :param func: The function object to call :param args: arguments to pass to the function :par... | 4aa8c64a6f65629207e40df9963232473a24c9f6 | <|skeleton|>
class Worker:
def __init__(self, func, *args, **kwargs):
"""Execute a function call on a different QThread :param func: The function object to call :param args: arguments to pass to the function :param kwargs: kwargs to pass to the function"""
<|body_0|>
def run(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Worker:
def __init__(self, func, *args, **kwargs):
"""Execute a function call on a different QThread :param func: The function object to call :param args: arguments to pass to the function :param kwargs: kwargs to pass to the function"""
super(Worker, self).__init__()
self.func = func
... | the_stack_v2_python_sparse | glue/utils/qt/threading.py | astrofrog/glue | train | 3 | |
bd2327b9a07beccc9c235fee98787f8fcf234d18 | [
"self.__connection = sqlite3.connect(cfg.dataBasePath)\nexc = self.__connection.cursor()\nexc.execute('create table if not exists table_configmanage(id integer primary key autoincrement, userid integer, type text, content text, comment text, constraint cm_ua foreign key(userid) references table_useraccount(id) ... | <|body_start_0|>
self.__connection = sqlite3.connect(cfg.dataBasePath)
exc = self.__connection.cursor()
exc.execute('create table if not exists table_configmanage(id integer primary key autoincrement, userid integer, type text, content text, comment text, constraint cm_ua foreign key(userid) ... | ConfigManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigManage:
def __init__(self):
"""通过构造函数构建与数据库文件的连接,以及初始化数据库"""
<|body_0|>
def saveUserConfig(self, accountName: str, type: str, content: str):
"""本函数用于存储用户的自定义配置 :param accountName: 用户账户名 :param type: 配置类型 :param content: 配置内容 :return: 无"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_004998 | 2,424 | no_license | [
{
"docstring": "通过构造函数构建与数据库文件的连接,以及初始化数据库",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "本函数用于存储用户的自定义配置 :param accountName: 用户账户名 :param type: 配置类型 :param content: 配置内容 :return: 无",
"name": "saveUserConfig",
"signature": "def saveUserConfig(self, accountName... | 3 | stack_v2_sparse_classes_30k_train_014751 | Implement the Python class `ConfigManage` described below.
Class description:
Implement the ConfigManage class.
Method signatures and docstrings:
- def __init__(self): 通过构造函数构建与数据库文件的连接,以及初始化数据库
- def saveUserConfig(self, accountName: str, type: str, content: str): 本函数用于存储用户的自定义配置 :param accountName: 用户账户名 :param typ... | Implement the Python class `ConfigManage` described below.
Class description:
Implement the ConfigManage class.
Method signatures and docstrings:
- def __init__(self): 通过构造函数构建与数据库文件的连接,以及初始化数据库
- def saveUserConfig(self, accountName: str, type: str, content: str): 本函数用于存储用户的自定义配置 :param accountName: 用户账户名 :param typ... | 98e715c3cd88cc82c9b49f6e4dc7e9dfd89c00cd | <|skeleton|>
class ConfigManage:
def __init__(self):
"""通过构造函数构建与数据库文件的连接,以及初始化数据库"""
<|body_0|>
def saveUserConfig(self, accountName: str, type: str, content: str):
"""本函数用于存储用户的自定义配置 :param accountName: 用户账户名 :param type: 配置类型 :param content: 配置内容 :return: 无"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigManage:
def __init__(self):
"""通过构造函数构建与数据库文件的连接,以及初始化数据库"""
self.__connection = sqlite3.connect(cfg.dataBasePath)
exc = self.__connection.cursor()
exc.execute('create table if not exists table_configmanage(id integer primary key autoincrement, userid integer, type text, ... | the_stack_v2_python_sparse | cgi-bin/ConfigOperate.py | heisehuanyin/MyWebsite | train | 1 | |
378456f16df603ea6cdc9db70547fdc5f5231d49 | [
"self._func = func\nself._concurrency_provider = concurrency_provider or (asyncio.get_event_loop() if six.PY3 and concurrency_provider is False else ThreadPool(processes=1))\nself._is_asyncio_provider = six.PY3 and (not isinstance(self._concurrency_provider, ThreadPool))\nself._is_awaitable = self._is_asyncio_provi... | <|body_start_0|>
self._func = func
self._concurrency_provider = concurrency_provider or (asyncio.get_event_loop() if six.PY3 and concurrency_provider is False else ThreadPool(processes=1))
self._is_asyncio_provider = six.PY3 and (not isinstance(self._concurrency_provider, ThreadPool))
se... | Wraps a potentially asynchronous function to provide a consistent API | AsyncWrapper | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncWrapper:
"""Wraps a potentially asynchronous function to provide a consistent API"""
def __init__(self, func=None, concurrency_provider=None):
"""Creates a wrapper for a potentially asynchronous function. :param func: blocking call, asyncio coroutine or future :param concurrency... | stack_v2_sparse_classes_36k_train_004999 | 5,482 | permissive | [
{
"docstring": "Creates a wrapper for a potentially asynchronous function. :param func: blocking call, asyncio coroutine or future :param concurrency_provider: ThreadPool or asyncio BaseEventLoop or None: default ThreadPool or False: default EventLoop",
"name": "__init__",
"signature": "def __init__(sel... | 3 | stack_v2_sparse_classes_30k_train_015087 | Implement the Python class `AsyncWrapper` described below.
Class description:
Wraps a potentially asynchronous function to provide a consistent API
Method signatures and docstrings:
- def __init__(self, func=None, concurrency_provider=None): Creates a wrapper for a potentially asynchronous function. :param func: bloc... | Implement the Python class `AsyncWrapper` described below.
Class description:
Wraps a potentially asynchronous function to provide a consistent API
Method signatures and docstrings:
- def __init__(self, func=None, concurrency_provider=None): Creates a wrapper for a potentially asynchronous function. :param func: bloc... | 76ef009903415f37f69dcc5778be8f5fb14c08fe | <|skeleton|>
class AsyncWrapper:
"""Wraps a potentially asynchronous function to provide a consistent API"""
def __init__(self, func=None, concurrency_provider=None):
"""Creates a wrapper for a potentially asynchronous function. :param func: blocking call, asyncio coroutine or future :param concurrency... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncWrapper:
"""Wraps a potentially asynchronous function to provide a consistent API"""
def __init__(self, func=None, concurrency_provider=None):
"""Creates a wrapper for a potentially asynchronous function. :param func: blocking call, asyncio coroutine or future :param concurrency_provider: Th... | the_stack_v2_python_sparse | src/mbed_cloud/subscribe/async_wrapper.py | GQMai/mbed-cloud-sdk-python | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.