blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16477679afcc0ba738c30538c6a0b7c9eb6dd499 | [
"sql_str = '\\n SELECT id, email\\n FROM auth_user\\n '\nquery = ResetPassword._make_select(sql_str)\nuser_emails = []\nfor element in query:\n if 'email' in element:\n user_emails.append(element['email'])\nreturn user_emails",
"sql_str = '\\n ... | <|body_start_0|>
sql_str = '\n SELECT id, email\n FROM auth_user\n '
query = ResetPassword._make_select(sql_str)
user_emails = []
for element in query:
if 'email' in element:
user_emails.append(element['email'... | Class for reseting password. | ResetPassword | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPassword:
"""Class for reseting password."""
def get_list_of_user_emails():
"""Find user in database by his email. :return: List with all user emails."""
<|body_0|>
def update_password(user_email):
"""Method to find user in database by his email. :param user... | stack_v2_sparse_classes_10k_train_005400 | 1,405 | no_license | [
{
"docstring": "Find user in database by his email. :return: List with all user emails.",
"name": "get_list_of_user_emails",
"signature": "def get_list_of_user_emails()"
},
{
"docstring": "Method to find user in database by his email. :param user_email: Email from user.",
"name": "update_pas... | 2 | stack_v2_sparse_classes_30k_train_005581 | Implement the Python class `ResetPassword` described below.
Class description:
Class for reseting password.
Method signatures and docstrings:
- def get_list_of_user_emails(): Find user in database by his email. :return: List with all user emails.
- def update_password(user_email): Method to find user in database by h... | Implement the Python class `ResetPassword` described below.
Class description:
Class for reseting password.
Method signatures and docstrings:
- def get_list_of_user_emails(): Find user in database by his email. :return: List with all user emails.
- def update_password(user_email): Method to find user in database by h... | 7d8f85323cd553e1b7788b407f84f14d2563bd2b | <|skeleton|>
class ResetPassword:
"""Class for reseting password."""
def get_list_of_user_emails():
"""Find user in database by his email. :return: List with all user emails."""
<|body_0|>
def update_password(user_email):
"""Method to find user in database by his email. :param user... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResetPassword:
"""Class for reseting password."""
def get_list_of_user_emails():
"""Find user in database by his email. :return: List with all user emails."""
sql_str = '\n SELECT id, email\n FROM auth_user\n '
query = ResetPasswo... | the_stack_v2_python_sparse | moneta/src/python/db/reset_password.py | lv-386-python/moneta | train | 7 |
d0c44c99119ac2e02260ff2f0b0d23a3c6d45be4 | [
"super().__init__()\nself.weight_query = torch.nn.Parameter(torch.zeros(feature_number, feature_number // 2))\nself.weight_key = torch.nn.Parameter(torch.zeros(feature_number, feature_number // 2))\nself.bias = torch.nn.Parameter(torch.zeros(feature_number // 2))\nself.attention = torch.nn.Parameter(torch.zeros(fea... | <|body_start_0|>
super().__init__()
self.weight_query = torch.nn.Parameter(torch.zeros(feature_number, feature_number // 2))
self.weight_key = torch.nn.Parameter(torch.zeros(feature_number, feature_number // 2))
self.bias = torch.nn.Parameter(torch.zeros(feature_number // 2))
sel... | Co-attention layer for drug pairs. | DrugDrugAttentionLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DrugDrugAttentionLayer:
"""Co-attention layer for drug pairs."""
def __init__(self, feature_number: int):
"""Initialize the co-attention layer. :param feature_number: Number of input features."""
<|body_0|>
def forward(self, left_representations: torch.Tensor, right_repr... | stack_v2_sparse_classes_10k_train_005401 | 25,672 | no_license | [
{
"docstring": "Initialize the co-attention layer. :param feature_number: Number of input features.",
"name": "__init__",
"signature": "def __init__(self, feature_number: int)"
},
{
"docstring": "Make a forward pass with the co-attention calculation. :param left_representations: Matrix of left h... | 2 | stack_v2_sparse_classes_30k_train_002638 | Implement the Python class `DrugDrugAttentionLayer` described below.
Class description:
Co-attention layer for drug pairs.
Method signatures and docstrings:
- def __init__(self, feature_number: int): Initialize the co-attention layer. :param feature_number: Number of input features.
- def forward(self, left_represent... | Implement the Python class `DrugDrugAttentionLayer` described below.
Class description:
Co-attention layer for drug pairs.
Method signatures and docstrings:
- def __init__(self, feature_number: int): Initialize the co-attention layer. :param feature_number: Number of input features.
- def forward(self, left_represent... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class DrugDrugAttentionLayer:
"""Co-attention layer for drug pairs."""
def __init__(self, feature_number: int):
"""Initialize the co-attention layer. :param feature_number: Number of input features."""
<|body_0|>
def forward(self, left_representations: torch.Tensor, right_repr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DrugDrugAttentionLayer:
"""Co-attention layer for drug pairs."""
def __init__(self, feature_number: int):
"""Initialize the co-attention layer. :param feature_number: Number of input features."""
super().__init__()
self.weight_query = torch.nn.Parameter(torch.zeros(feature_number,... | the_stack_v2_python_sparse | generated/test_AstraZeneca_chemicalx.py | jansel/pytorch-jit-paritybench | train | 35 |
fedef0e420a8c8a0895dae29fc3ac74b1676fb4f | [
"self.entity_description = description\nserial_number = coordinator.envoy.serial_number\nassert serial_number is not None\nself.envoy_serial_num = serial_number\nsuper().__init__(coordinator)",
"data = self.coordinator.envoy.data\nassert data is not None\nreturn data"
] | <|body_start_0|>
self.entity_description = description
serial_number = coordinator.envoy.serial_number
assert serial_number is not None
self.envoy_serial_num = serial_number
super().__init__(coordinator)
<|end_body_0|>
<|body_start_1|>
data = self.coordinator.envoy.data
... | Defines a base envoy entity. | EnvoyBaseEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvoyBaseEntity:
"""Defines a base envoy entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EntityDescription) -> None:
"""Init the Enphase base entity."""
<|body_0|>
def data(self) -> EnvoyData:
"""Return envoy data."""
<|b... | stack_v2_sparse_classes_10k_train_005402 | 1,029 | permissive | [
{
"docstring": "Init the Enphase base entity.",
"name": "__init__",
"signature": "def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EntityDescription) -> None"
},
{
"docstring": "Return envoy data.",
"name": "data",
"signature": "def data(self) -> EnvoyData"
}
] | 2 | stack_v2_sparse_classes_30k_train_005250 | Implement the Python class `EnvoyBaseEntity` described below.
Class description:
Defines a base envoy entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EntityDescription) -> None: Init the Enphase base entity.
- def data(self) -> EnvoyData: Return envoy... | Implement the Python class `EnvoyBaseEntity` described below.
Class description:
Defines a base envoy entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EntityDescription) -> None: Init the Enphase base entity.
- def data(self) -> EnvoyData: Return envoy... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EnvoyBaseEntity:
"""Defines a base envoy entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EntityDescription) -> None:
"""Init the Enphase base entity."""
<|body_0|>
def data(self) -> EnvoyData:
"""Return envoy data."""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnvoyBaseEntity:
"""Defines a base envoy entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EntityDescription) -> None:
"""Init the Enphase base entity."""
self.entity_description = description
serial_number = coordinator.envoy.serial_number
... | the_stack_v2_python_sparse | homeassistant/components/enphase_envoy/entity.py | home-assistant/core | train | 35,501 |
6c378e5a0f41a3a08895a836d8063ffff4878d0b | [
"employee_env = self.env['hr.employee']\nuser_env = self.env['res.users']\nemployee_obj = employee_env.search([('user_id', '=', self._uid)])\nis_allow = False\nfor rec in self:\n if user_env.has_group('base.group_hr_manager') or employee_obj.id == rec.manager_id.id:\n is_allow = True\n else:\n i... | <|body_start_0|>
employee_env = self.env['hr.employee']
user_env = self.env['res.users']
employee_obj = employee_env.search([('user_id', '=', self._uid)])
is_allow = False
for rec in self:
if user_env.has_group('base.group_hr_manager') or employee_obj.id == rec.manage... | HrAppraisal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HrAppraisal:
def _password_security_salary(self):
"""HR manager and the Manager of the employee can see and edit Salary Information"""
<|body_0|>
def _password_security_interview_result(self):
"""Interview Result - HR manager and the Manager of the employee can see a... | stack_v2_sparse_classes_10k_train_005403 | 2,753 | no_license | [
{
"docstring": "HR manager and the Manager of the employee can see and edit Salary Information",
"name": "_password_security_salary",
"signature": "def _password_security_salary(self)"
},
{
"docstring": "Interview Result - HR manager and the Manager of the employee can see and edit - Employee ca... | 3 | stack_v2_sparse_classes_30k_train_003357 | Implement the Python class `HrAppraisal` described below.
Class description:
Implement the HrAppraisal class.
Method signatures and docstrings:
- def _password_security_salary(self): HR manager and the Manager of the employee can see and edit Salary Information
- def _password_security_interview_result(self): Intervi... | Implement the Python class `HrAppraisal` described below.
Class description:
Implement the HrAppraisal class.
Method signatures and docstrings:
- def _password_security_salary(self): HR manager and the Manager of the employee can see and edit Salary Information
- def _password_security_interview_result(self): Intervi... | 673dd0f2a7c0b69a984342b20f55164a97a00529 | <|skeleton|>
class HrAppraisal:
def _password_security_salary(self):
"""HR manager and the Manager of the employee can see and edit Salary Information"""
<|body_0|>
def _password_security_interview_result(self):
"""Interview Result - HR manager and the Manager of the employee can see a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HrAppraisal:
def _password_security_salary(self):
"""HR manager and the Manager of the employee can see and edit Salary Information"""
employee_env = self.env['hr.employee']
user_env = self.env['res.users']
employee_obj = employee_env.search([('user_id', '=', self._uid)])
... | the_stack_v2_python_sparse | addons/app-trobz-hr/trobz_hr_simple_appraisal_secure/model/hr_appraisal.py | TinPlusIT05/tms | train | 0 | |
1fc23e16fa9033fb5d66df522f7ba9b1829e8bc0 | [
"a = [[None] * n for x in range(n)]\ni = 0\nj = 0\np = 0\na, j, x = self.set_initial_row(a, i, j, n)\nfor q in self.gen_part_len(n):\n for t in range(0, q):\n i, j = self.eval_next_loc(p, i, j)\n a[i][j] = x\n x += 1\n p += 1\nreturn a",
"for x in range(1, n):\n a[i][j] = x\n j +=... | <|body_start_0|>
a = [[None] * n for x in range(n)]
i = 0
j = 0
p = 0
a, j, x = self.set_initial_row(a, i, j, n)
for q in self.gen_part_len(n):
for t in range(0, q):
i, j = self.eval_next_loc(p, i, j)
a[i][j] = x
... | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def make_spiral_matrix(self, n):
"""Creates spiral matrix from given characteristic factor "n". :param int n: characteristic factor for spiral matrix :return: completed 2D spiral matrix :rtype: list[list[int]]"""
<|body_0|>
def set_initial_row(self, a, i, j, n):
... | stack_v2_sparse_classes_10k_train_005404 | 3,472 | permissive | [
{
"docstring": "Creates spiral matrix from given characteristic factor \"n\". :param int n: characteristic factor for spiral matrix :return: completed 2D spiral matrix :rtype: list[list[int]]",
"name": "make_spiral_matrix",
"signature": "def make_spiral_matrix(self, n)"
},
{
"docstring": "Comple... | 4 | stack_v2_sparse_classes_30k_train_007215 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def make_spiral_matrix(self, n): Creates spiral matrix from given characteristic factor "n". :param int n: characteristic factor for spiral matrix :return: completed 2D spiral ma... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def make_spiral_matrix(self, n): Creates spiral matrix from given characteristic factor "n". :param int n: characteristic factor for spiral matrix :return: completed 2D spiral ma... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
def make_spiral_matrix(self, n):
"""Creates spiral matrix from given characteristic factor "n". :param int n: characteristic factor for spiral matrix :return: completed 2D spiral matrix :rtype: list[list[int]]"""
<|body_0|>
def set_initial_row(self, a, i, j, n):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def make_spiral_matrix(self, n):
"""Creates spiral matrix from given characteristic factor "n". :param int n: characteristic factor for spiral matrix :return: completed 2D spiral matrix :rtype: list[list[int]]"""
a = [[None] * n for x in range(n)]
i = 0
j = 0
... | the_stack_v2_python_sparse | 0059_spiral_matrix_2/python_source.py | arthurdysart/LeetCode | train | 0 | |
1b78c7d9d8a926db4786577ea8ebd650eecd1d3c | [
"super(LandmarkGeneratorMask, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation)\nself.output_size_np = list(reversed(self.output_size))\nself.ones_if_every_point_is_invalid = ones_if_every_point_is_invalid",
"flip = self.is_flipped(transf... | <|body_start_0|>
super(LandmarkGeneratorMask, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation)
self.output_size_np = list(reversed(self.output_size))
self.ones_if_every_point_is_invalid = ones_if_every_point_is_invalid
... | Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks | LandmarkGeneratorMask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LandmarkGeneratorMask:
"""Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks"""
def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post... | stack_v2_sparse_classes_10k_train_005405 | 16,690 | no_license | [
{
"docstring": "Initializer :param output_size: output image size :param ones_if_every_point_is_invalid: if True, create ones mask, if every point is invalid otherwise, create zeros mask, if every point is invalid :param landmark_indizes: list of landmark indizes that will be used for generating the output :par... | 2 | stack_v2_sparse_classes_30k_train_002319 | Implement the Python class `LandmarkGeneratorMask` described below.
Class description:
Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks
Method signatures and docstrings:
- def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pai... | Implement the Python class `LandmarkGeneratorMask` described below.
Class description:
Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks
Method signatures and docstrings:
- def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pai... | ef6cee91264ba1fe6b40d9823a07647b95bcc2c4 | <|skeleton|>
class LandmarkGeneratorMask:
"""Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks"""
def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LandmarkGeneratorMask:
"""Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks"""
def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformati... | the_stack_v2_python_sparse | generators/landmark_generator.py | XiaoweiXu/MedicalDataAugmentationTool | train | 1 |
fa6d606cd33e967df12b90335c47859ac2393bdb | [
"if isinstance(v, str):\n return v\nreturn PostgresDsn.build(scheme='postgresql', user=values.get('POSTGRES_USER'), password=values.get('POSTGRES_PASSWORD'), host=values.get('POSTGRES_SERVER'), port=values.get('POSTGRES_PORT'), path=f\"/{values.get('POSTGRES_DB') or ''}\")",
"env = os.getenv('PYTHON_ENV', 'dev... | <|body_start_0|>
if isinstance(v, str):
return v
return PostgresDsn.build(scheme='postgresql', user=values.get('POSTGRES_USER'), password=values.get('POSTGRES_PASSWORD'), host=values.get('POSTGRES_SERVER'), port=values.get('POSTGRES_PORT'), path=f"/{values.get('POSTGRES_DB') or ''}")
<|end_b... | Global Settings. | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Global Settings."""
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]:
"""PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url conn... | stack_v2_sparse_classes_10k_train_005406 | 2,572 | no_license | [
{
"docstring": "PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url connection.",
"name": "assemble_db_connection",
"signature": "def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[s... | 2 | stack_v2_sparse_classes_30k_val_000243 | Implement the Python class `Settings` described below.
Class description:
Global Settings.
Method signatures and docstrings:
- def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]: PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others ... | Implement the Python class `Settings` described below.
Class description:
Global Settings.
Method signatures and docstrings:
- def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]: PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others ... | 8082d3ce9c999c79228a36aa160b4171140440cb | <|skeleton|>
class Settings:
"""Global Settings."""
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]:
"""PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url conn... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Settings:
"""Global Settings."""
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]:
"""PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url connection."""
... | the_stack_v2_python_sparse | app/config.py | douglaspands/api-server-py | train | 2 |
f735c1ecfddca8b864f4a04ebd4e3acad7119169 | [
"deg = [0] * n\nedgeCounter = defaultdict(int)\nfor u, v in edges:\n u, v = (u - 1, v - 1)\n deg[u] += 1\n deg[v] += 1\n if u > v:\n u, v = (v, u)\n edgeCounter[u, v] += 1\ndegFreq = Counter(deg)\npairDegSum = [0] * (max(deg) * 2 + 2)\nfor deg1, freq1 in degFreq.items():\n for deg2, freq2 i... | <|body_start_0|>
deg = [0] * n
edgeCounter = defaultdict(int)
for u, v in edges:
u, v = (u - 1, v - 1)
deg[u] += 1
deg[v] += 1
if u > v:
u, v = (v, u)
edgeCounter[u, v] += 1
degFreq = Counter(deg)
pairDeg... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:
"""O(n+m+q) !无向图本质不同的度数只有根号m个.因此可以二重循环枚举度数."""
<|body_0|>
def countPairs2(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:
"""!排序+双指针 O(nlogn+q(n+m... | stack_v2_sparse_classes_10k_train_005407 | 3,486 | no_license | [
{
"docstring": "O(n+m+q) !无向图本质不同的度数只有根号m个.因此可以二重循环枚举度数.",
"name": "countPairs",
"signature": "def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]"
},
{
"docstring": "!排序+双指针 O(nlogn+q(n+m))",
"name": "countPairs2",
"signature": "def countPairs2(self, n:... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]: O(n+m+q) !无向图本质不同的度数只有根号m个.因此可以二重循环枚举度数.
- def countPairs2(self, n: int, edges: List[List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]: O(n+m+q) !无向图本质不同的度数只有根号m个.因此可以二重循环枚举度数.
- def countPairs2(self, n: int, edges: List[List[i... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:
"""O(n+m+q) !无向图本质不同的度数只有根号m个.因此可以二重循环枚举度数."""
<|body_0|>
def countPairs2(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:
"""!排序+双指针 O(nlogn+q(n+m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:
"""O(n+m+q) !无向图本质不同的度数只有根号m个.因此可以二重循环枚举度数."""
deg = [0] * n
edgeCounter = defaultdict(int)
for u, v in edges:
u, v = (u - 1, v - 1)
deg[u] += 1
... | the_stack_v2_python_sparse | 7_graph/经典题/度数/1782. 统计点对的数目.py | 981377660LMT/algorithm-study | train | 225 | |
08747748a4c5268ae195f91b7576f0a88fa76a08 | [
"current = self.head\nwhile current is not None:\n if current.value[0] == key:\n return current.value[1]\n current = current.next\nreturn None",
"if self.is_empty():\n print('Список пуст')\nelse:\n current = self.head\n ind = 0\n while current is not None:\n if current.value[0] == ... | <|body_start_0|>
current = self.head
while current is not None:
if current.value[0] == key:
return current.value[1]
current = current.next
return None
<|end_body_0|>
<|body_start_1|>
if self.is_empty():
print('Список пуст')
els... | This is the linked list class for the hash table | LinkedListHash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedListHash:
"""This is the linked list class for the hash table"""
def this_value(self, key):
"""Method for checking the existence of a node with a given value in the list"""
<|body_0|>
def delete_value(self, key):
"""Method for removing a node / nodes by a g... | stack_v2_sparse_classes_10k_train_005408 | 2,309 | no_license | [
{
"docstring": "Method for checking the existence of a node with a given value in the list",
"name": "this_value",
"signature": "def this_value(self, key)"
},
{
"docstring": "Method for removing a node / nodes by a given key from the list",
"name": "delete_value",
"signature": "def delet... | 2 | stack_v2_sparse_classes_30k_train_004517 | Implement the Python class `LinkedListHash` described below.
Class description:
This is the linked list class for the hash table
Method signatures and docstrings:
- def this_value(self, key): Method for checking the existence of a node with a given value in the list
- def delete_value(self, key): Method for removing ... | Implement the Python class `LinkedListHash` described below.
Class description:
This is the linked list class for the hash table
Method signatures and docstrings:
- def this_value(self, key): Method for checking the existence of a node with a given value in the list
- def delete_value(self, key): Method for removing ... | 44d27242789d670efa64dd72f9a112a80df8373c | <|skeleton|>
class LinkedListHash:
"""This is the linked list class for the hash table"""
def this_value(self, key):
"""Method for checking the existence of a node with a given value in the list"""
<|body_0|>
def delete_value(self, key):
"""Method for removing a node / nodes by a g... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinkedListHash:
"""This is the linked list class for the hash table"""
def this_value(self, key):
"""Method for checking the existence of a node with a given value in the list"""
current = self.head
while current is not None:
if current.value[0] == key:
... | the_stack_v2_python_sparse | structures/hash_table.py | SvetlanaSumets11/python-education | train | 0 |
9f2065af49d9664128352b00bc328f2204476599 | [
"self.name = name\nself.birthday = birthday\nself.premium = premium",
"if self.birthday == datetime.date.today():\n print('Happy Birthday!')\nelse:\n current_year = datetime.date.today().year\n birth_month = self.birthday.month\n birth_day = self.birthday.day\n print(datetime.date(current_year, bir... | <|body_start_0|>
self.name = name
self.birthday = birthday
self.premium = premium
<|end_body_0|>
<|body_start_1|>
if self.birthday == datetime.date.today():
print('Happy Birthday!')
else:
current_year = datetime.date.today().year
birth_month =... | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def __init__(self, name, birthday, premium):
"""A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Meth... | stack_v2_sparse_classes_10k_train_005409 | 23,101 | permissive | [
{
"docstring": "A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Methods ------- next_birthday: Determines the users' birthday in t... | 2 | stack_v2_sparse_classes_30k_train_004075 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, name, birthday, premium): A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of... | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, name, birthday, premium): A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of... | 767ba750e5cae0d213b9abfd709ff8f6e4d4a1ac | <|skeleton|>
class User:
def __init__(self, name, birthday, premium):
"""A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Meth... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class User:
def __init__(self, name, birthday, premium):
"""A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Methods ------- ne... | the_stack_v2_python_sparse | Solutions.py | Descent098/PYTH-101 | train | 0 | |
93deaaefc92950bb0a26747f82bc7a4da22fea15 | [
"m = context.accessor.get_metric(name)\nif not m:\n rp.abort(404)\nreturn m.as_string_dict()",
"if not context.accessor.has_metric(name):\n return (\"Unknown metric: '%s'\" % name, 404)\npayload = request.json\nmetadata = bg_metric.MetricMetadata.create(aggregator=bg_metric.Aggregator.from_config_name(paylo... | <|body_start_0|>
m = context.accessor.get_metric(name)
if not m:
rp.abort(404)
return m.as_string_dict()
<|end_body_0|>
<|body_start_1|>
if not context.accessor.has_metric(name):
return ("Unknown metric: '%s'" % name, 404)
payload = request.json
m... | A Metric. | MetricResource | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
<|body_0|>
def post(self, name):
"""Update a metric."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = context.accessor.get_metric(name)
if not m:
rp.... | stack_v2_sparse_classes_10k_train_005410 | 2,775 | permissive | [
{
"docstring": "Get a metric.",
"name": "get",
"signature": "def get(self, name)"
},
{
"docstring": "Update a metric.",
"name": "post",
"signature": "def post(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007226 | Implement the Python class `MetricResource` described below.
Class description:
A Metric.
Method signatures and docstrings:
- def get(self, name): Get a metric.
- def post(self, name): Update a metric. | Implement the Python class `MetricResource` described below.
Class description:
A Metric.
Method signatures and docstrings:
- def get(self, name): Get a metric.
- def post(self, name): Update a metric.
<|skeleton|>
class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
... | 1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30 | <|skeleton|>
class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
<|body_0|>
def post(self, name):
"""Update a metric."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
m = context.accessor.get_metric(name)
if not m:
rp.abort(404)
return m.as_string_dict()
def post(self, name):
"""Update a metric."""
if not context.accessor.has_metric... | the_stack_v2_python_sparse | biggraphite/cli/web/namespaces/biggraphite.py | criteo/biggraphite | train | 129 |
507d6e943fae3f94482a600603543b449d49051b | [
"self._date_one = kwargs.pop('date_one', DEFAULT_DATE_ONE)\nself._date_two = kwargs.pop('date_two', DEFAULT_DATE_TWO)\nself.db = DBCommunication()\nsuper().__init__(**kwargs)",
"fetched_data = self.db.get_data_for_specific_dates(self._date_one, self._date_two)\nweather_data = {}\nrow_data = {}\ncounter = 0\nfor i... | <|body_start_0|>
self._date_one = kwargs.pop('date_one', DEFAULT_DATE_ONE)
self._date_two = kwargs.pop('date_two', DEFAULT_DATE_TWO)
self.db = DBCommunication()
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
fetched_data = self.db.get_data_for_specific_dates(self._da... | This class defines a strategy for the agent. | Strategy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Strategy:
"""This class defines a strategy for the agent."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize the strategy of the agent. :param kwargs: keyword arguments"""
<|body_0|>
def collect_from_data_source(self) -> Dict[str, str]:
"""Build the data... | stack_v2_sparse_classes_10k_train_005411 | 2,746 | permissive | [
{
"docstring": "Initialize the strategy of the agent. :param kwargs: keyword arguments",
"name": "__init__",
"signature": "def __init__(self, **kwargs: Any) -> None"
},
{
"docstring": "Build the data payload. :return: a tuple of the data and the rows",
"name": "collect_from_data_source",
... | 2 | null | Implement the Python class `Strategy` described below.
Class description:
This class defines a strategy for the agent.
Method signatures and docstrings:
- def __init__(self, **kwargs: Any) -> None: Initialize the strategy of the agent. :param kwargs: keyword arguments
- def collect_from_data_source(self) -> Dict[str,... | Implement the Python class `Strategy` described below.
Class description:
This class defines a strategy for the agent.
Method signatures and docstrings:
- def __init__(self, **kwargs: Any) -> None: Initialize the strategy of the agent. :param kwargs: keyword arguments
- def collect_from_data_source(self) -> Dict[str,... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class Strategy:
"""This class defines a strategy for the agent."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize the strategy of the agent. :param kwargs: keyword arguments"""
<|body_0|>
def collect_from_data_source(self) -> Dict[str, str]:
"""Build the data... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Strategy:
"""This class defines a strategy for the agent."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize the strategy of the agent. :param kwargs: keyword arguments"""
self._date_one = kwargs.pop('date_one', DEFAULT_DATE_ONE)
self._date_two = kwargs.pop('date_two', DE... | the_stack_v2_python_sparse | packages/fetchai/skills/weather_station/strategy.py | fetchai/agents-aea | train | 192 |
029f59df7a4007938fefed469693a8f5cedc34e5 | [
"if gateway == 'admin_pay':\n request = Request(HttpRequest)\n try:\n setattr(request.user, 'id', orders.user_id)\n except Exception as e:\n return e\nresult = Wallet.update_balance(request=request, orders=orders, method=WALLET_ACTION_METHOD[0])\nif isinstance(result, Exception):\n return ... | <|body_start_0|>
if gateway == 'admin_pay':
request = Request(HttpRequest)
try:
setattr(request.user, 'id', orders.user_id)
except Exception as e:
return e
result = Wallet.update_balance(request=request, orders=orders, method=WALLET_ACT... | 钱包相关功能 | WalletAction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WalletAction:
"""钱包相关功能"""
def recharge(self, request, orders, gateway='auth', does_give_coupons=False):
"""充值"""
<|body_0|>
def orders_refund(self, request, orders, gateway='auth'):
"""订单退款(从订单的应付款中退款到钱包中) 适用场景:1.管理员取消用户的未核销订单(此时需要把订单的应付款返回到用户钱包中)"""
<|b... | stack_v2_sparse_classes_10k_train_005412 | 14,801 | no_license | [
{
"docstring": "充值",
"name": "recharge",
"signature": "def recharge(self, request, orders, gateway='auth', does_give_coupons=False)"
},
{
"docstring": "订单退款(从订单的应付款中退款到钱包中) 适用场景:1.管理员取消用户的未核销订单(此时需要把订单的应付款返回到用户钱包中)",
"name": "orders_refund",
"signature": "def orders_refund(self, request,... | 2 | stack_v2_sparse_classes_30k_train_006707 | Implement the Python class `WalletAction` described below.
Class description:
钱包相关功能
Method signatures and docstrings:
- def recharge(self, request, orders, gateway='auth', does_give_coupons=False): 充值
- def orders_refund(self, request, orders, gateway='auth'): 订单退款(从订单的应付款中退款到钱包中) 适用场景:1.管理员取消用户的未核销订单(此时需要把订单的应付款返回到... | Implement the Python class `WalletAction` described below.
Class description:
钱包相关功能
Method signatures and docstrings:
- def recharge(self, request, orders, gateway='auth', does_give_coupons=False): 充值
- def orders_refund(self, request, orders, gateway='auth'): 订单退款(从订单的应付款中退款到钱包中) 适用场景:1.管理员取消用户的未核销订单(此时需要把订单的应付款返回到... | 5a0d42cf794b5e0cd127e625d36e6f8e96812ae5 | <|skeleton|>
class WalletAction:
"""钱包相关功能"""
def recharge(self, request, orders, gateway='auth', does_give_coupons=False):
"""充值"""
<|body_0|>
def orders_refund(self, request, orders, gateway='auth'):
"""订单退款(从订单的应付款中退款到钱包中) 适用场景:1.管理员取消用户的未核销订单(此时需要把订单的应付款返回到用户钱包中)"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WalletAction:
"""钱包相关功能"""
def recharge(self, request, orders, gateway='auth', does_give_coupons=False):
"""充值"""
if gateway == 'admin_pay':
request = Request(HttpRequest)
try:
setattr(request.user, 'id', orders.user_id)
except Exception... | the_stack_v2_python_sparse | Consumer_App/cs_wallet/models.py | dennis1984/YSAdminApp | train | 0 |
5533738cfe772ea3bb4f6f84500b97841a7e4725 | [
"if self.field:\n return 'Summary aggregations for \"{0:s}\"'.format(self.field)\nreturn 'Summary aggregations for an unknown field.'",
"self.field = field\nself.field_query_string = field_query_string\nformatted_field_name = self.format_field_by_type(field)\nif field_query_string == '*':\n formatted_field_... | <|body_start_0|>
if self.field:
return 'Summary aggregations for "{0:s}"'.format(self.field)
return 'Summary aggregations for an unknown field.'
<|end_body_0|>
<|body_start_1|>
self.field = field
self.field_query_string = field_query_string
formatted_field_name = sel... | Summary Aggregations. | SummaryAggregation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SummaryAggregation:
"""Summary Aggregations."""
def chart_title(self):
"""Returns a title for the chart."""
<|body_0|>
def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit=5):
"""Runs the Summary... | stack_v2_sparse_classes_10k_train_005413 | 13,136 | permissive | [
{
"docstring": "Returns a title for the chart.",
"name": "chart_title",
"signature": "def chart_title(self)"
},
{
"docstring": "Runs the SummaryAggregation aggregator. Args: field: What field to aggregate on. field_query_string: The field value(s) to aggregate on. supported_charts: The chart typ... | 2 | null | Implement the Python class `SummaryAggregation` described below.
Class description:
Summary Aggregations.
Method signatures and docstrings:
- def chart_title(self): Returns a title for the chart.
- def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit... | Implement the Python class `SummaryAggregation` described below.
Class description:
Summary Aggregations.
Method signatures and docstrings:
- def chart_title(self): Returns a title for the chart.
- def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class SummaryAggregation:
"""Summary Aggregations."""
def chart_title(self):
"""Returns a title for the chart."""
<|body_0|>
def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit=5):
"""Runs the Summary... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SummaryAggregation:
"""Summary Aggregations."""
def chart_title(self):
"""Returns a title for the chart."""
if self.field:
return 'Summary aggregations for "{0:s}"'.format(self.field)
return 'Summary aggregations for an unknown field.'
def run(self, field, field_q... | the_stack_v2_python_sparse | timesketch/lib/aggregators/summary.py | google/timesketch | train | 2,263 |
c4732d63492c06e01dbf9868ec7caaa1720a6817 | [
"self.posn_x = posn_x\nself.posn_y = posn_y\nself.velocity_x = velocity_x\nself.velocity_y = 100.0\nself.color = kula\nself.ball_width = 20.0\nself.ball_height = 20.0\nself.coef_restitution = 0.9",
"if self.posn_x > cw - self.ball_width:\n self.velocity_x = -self.velocity_x * self.coef_restitution\n self.po... | <|body_start_0|>
self.posn_x = posn_x
self.posn_y = posn_y
self.velocity_x = velocity_x
self.velocity_y = 100.0
self.color = kula
self.ball_width = 20.0
self.ball_height = 20.0
self.coef_restitution = 0.9
<|end_body_0|>
<|body_start_1|>
if self.po... | The behaviors and properties of bouncing balls. | BallBounce | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BallBounce:
"""The behaviors and properties of bouncing balls."""
def __init__(self, posn_x, posn_y, velocity_x, velocity_y, kula):
"""Initialize values at instantiation."""
<|body_0|>
def detectWallCollision(self):
"""Collision detection with the walls of the co... | stack_v2_sparse_classes_10k_train_005414 | 4,695 | no_license | [
{
"docstring": "Initialize values at instantiation.",
"name": "__init__",
"signature": "def __init__(self, posn_x, posn_y, velocity_x, velocity_y, kula)"
},
{
"docstring": "Collision detection with the walls of the container",
"name": "detectWallCollision",
"signature": "def detectWallCo... | 3 | stack_v2_sparse_classes_30k_train_005392 | Implement the Python class `BallBounce` described below.
Class description:
The behaviors and properties of bouncing balls.
Method signatures and docstrings:
- def __init__(self, posn_x, posn_y, velocity_x, velocity_y, kula): Initialize values at instantiation.
- def detectWallCollision(self): Collision detection wit... | Implement the Python class `BallBounce` described below.
Class description:
The behaviors and properties of bouncing balls.
Method signatures and docstrings:
- def __init__(self, posn_x, posn_y, velocity_x, velocity_y, kula): Initialize values at instantiation.
- def detectWallCollision(self): Collision detection wit... | 0407c04c5776e0d38eaaba2331e9a7e5d962d653 | <|skeleton|>
class BallBounce:
"""The behaviors and properties of bouncing balls."""
def __init__(self, posn_x, posn_y, velocity_x, velocity_y, kula):
"""Initialize values at instantiation."""
<|body_0|>
def detectWallCollision(self):
"""Collision detection with the walls of the co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BallBounce:
"""The behaviors and properties of bouncing balls."""
def __init__(self, posn_x, posn_y, velocity_x, velocity_y, kula):
"""Initialize values at instantiation."""
self.posn_x = posn_x
self.posn_y = posn_y
self.velocity_x = velocity_x
self.velocity_y = 10... | the_stack_v2_python_sparse | ch2_prog7_ball_collisions_class_1.py | mikeodf/Python_Graphics_Animation | train | 3 |
2c56abeb2396749edb0ac6a156b985fc6cf2b939 | [
"form_opts = self.request.GET.copy()\ntry:\n del form_opts['page']\nexcept KeyError:\n pass\nself.form = self.form_class(form_opts or self.form_class.defaults)\nif self.form.is_valid():\n search_opts = self.form.cleaned_data\n if search_opts['content_type'] != 'all':\n if search_opts['content_typ... | <|body_start_0|>
form_opts = self.request.GET.copy()
try:
del form_opts['page']
except KeyError:
pass
self.form = self.form_class(form_opts or self.form_class.defaults)
if self.form.is_valid():
search_opts = self.form.cleaned_data
i... | SearchView | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchView:
def get(self, *args, **kwargs):
"""Process form for :class:`SearchView`."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Retrieve Solr queries for :class:`SearchView` context."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form_o... | stack_v2_sparse_classes_10k_train_005415 | 37,410 | permissive | [
{
"docstring": "Process form for :class:`SearchView`.",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Retrieve Solr queries for :class:`SearchView` context.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006509 | Implement the Python class `SearchView` described below.
Class description:
Implement the SearchView class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): Process form for :class:`SearchView`.
- def get_context_data(self, **kwargs): Retrieve Solr queries for :class:`SearchView` context. | Implement the Python class `SearchView` described below.
Class description:
Implement the SearchView class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): Process form for :class:`SearchView`.
- def get_context_data(self, **kwargs): Retrieve Solr queries for :class:`SearchView` context.
<|skelet... | 6371bb1266d7751af59aeaa3426ef7ac02a1fe17 | <|skeleton|>
class SearchView:
def get(self, *args, **kwargs):
"""Process form for :class:`SearchView`."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Retrieve Solr queries for :class:`SearchView` context."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SearchView:
def get(self, *args, **kwargs):
"""Process form for :class:`SearchView`."""
form_opts = self.request.GET.copy()
try:
del form_opts['page']
except KeyError:
pass
self.form = self.form_class(form_opts or self.form_class.defaults)
... | the_stack_v2_python_sparse | derrida/books/views.py | Princeton-CDH/derrida-django | train | 13 | |
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a | [
"super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.weight, wav2vec2_layer.attention.k_proj.weight, wav2vec2_layer.attention.v_proj.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.bias, wav2vec2_layer.attention.k_proj.bias, ... | <|body_start_0|>
super().__init__(config)
self.in_proj_weight = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.weight, wav2vec2_layer.attention.k_proj.weight, wav2vec2_layer.attention.v_proj.weight]))
self.in_proj_bias = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.bias, wav2... | Wav2Vec2EncoderLayerBetterTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wav2Vec2EncoderLayerBetterTransformer:
def __init__(self, wav2vec2_layer, config):
"""A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be ret... | stack_v2_sparse_classes_10k_train_005416 | 43,670 | no_license | [
{
"docstring": "A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, wav2vec2_layer, config)... | 2 | stack_v2_sparse_classes_30k_train_002627 | Implement the Python class `Wav2Vec2EncoderLayerBetterTransformer` described below.
Class description:
Implement the Wav2Vec2EncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, wav2vec2_layer, config): A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` i... | Implement the Python class `Wav2Vec2EncoderLayerBetterTransformer` described below.
Class description:
Implement the Wav2Vec2EncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, wav2vec2_layer, config): A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` i... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Wav2Vec2EncoderLayerBetterTransformer:
def __init__(self, wav2vec2_layer, config):
"""A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Wav2Vec2EncoderLayerBetterTransformer:
def __init__(self, wav2vec2_layer, config):
"""A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be retrieved."""
... | the_stack_v2_python_sparse | generated/test_huggingface_optimum.py | jansel/pytorch-jit-paritybench | train | 35 | |
e0416be9a7b208860b912f07d9a5a0e52a8a25b6 | [
"if not password_file:\n raise RuntimeError('No password file specified')\nif not os.path.exists(password_file):\n raise RuntimeError(f\"password file '{password_file}' does not exist\")\nself.password_file = password_file\nself.newt_base_url = newt_base_url if newt_base_url else _NEWT_BASE_URL\nif not self.n... | <|body_start_0|>
if not password_file:
raise RuntimeError('No password file specified')
if not os.path.exists(password_file):
raise RuntimeError(f"password file '{password_file}' does not exist")
self.password_file = password_file
self.newt_base_url = newt_base_ur... | Newt | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Newt:
def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0):
"""Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)"... | stack_v2_sparse_classes_10k_train_005417 | 5,141 | permissive | [
{
"docstring": "Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)",
"name": "__init__",
"signature": "def __init__(self, password_file, newt_base_url=None, max_retries=0... | 6 | stack_v2_sparse_classes_30k_train_006321 | Implement the Python class `Newt` described below.
Class description:
Implement the Newt class.
Method signatures and docstrings:
- def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0): Constructor that takes path to password file and optional Newt base URL :param password_file... | Implement the Python class `Newt` described below.
Class description:
Implement the Newt class.
Method signatures and docstrings:
- def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0): Constructor that takes path to password file and optional Newt base URL :param password_file... | 842fdc91a31879084906d71a7d0c317e5035a925 | <|skeleton|>
class Newt:
def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0):
"""Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Newt:
def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0):
"""Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)"""
if ... | the_stack_v2_python_sparse | src/decisionengine_modules/NERSC/util/newt.py | HEPCloud/decisionengine_modules | train | 2 | |
81c5025444b4700a88f39b9173f6bd13bf73fd75 | [
"import heapq\nself._min_heap = []\nself._max_heap = []",
"if not self._min_heap or num < self._min_heap[0]:\n heapq.heappush(self._max_heap, -num)\nelse:\n heapq.heappush(self._min_heap, num)\nwhile len(self._min_heap) > len(self._max_heap) + 1:\n heapq.heappush(self._max_heap, -heapq.heappop(self._min_... | <|body_start_0|>
import heapq
self._min_heap = []
self._max_heap = []
<|end_body_0|>
<|body_start_1|>
if not self._min_heap or num < self._min_heap[0]:
heapq.heappush(self._max_heap, -num)
else:
heapq.heappush(self._min_heap, num)
while len(self._... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_005418 | 1,209 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | null | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | 33b6b68a8136109d2aaa26bb8bf9e873f995d5ab | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
import heapq
self._min_heap = []
self._max_heap = []
def addNum(self, num):
""":type num: int :rtype: void"""
if not self._min_heap or num < self._min_heap[0]:
heapq.he... | the_stack_v2_python_sparse | python2/l0295_find_median_from_data_stream.py | sprax/1337 | train | 0 | |
92942f69195622cb3268a1ee33d3d1bb9e93bbeb | [
"super().__init__()\nnout_new = nout - nin\nself.eesp = VGGBlock(nin, nout_new, stride=2, down_method='avg')\nself.avg = nn.AvgPool2d(kernel_size=3, padding=1, stride=2)\nif reinf:\n self.inp_reinf = nn.Sequential(CBR(config_inp_reinf, config_inp_reinf, 3, 1), CB(config_inp_reinf, nout, 1, 1))\nself.act = nn.PRe... | <|body_start_0|>
super().__init__()
nout_new = nout - nin
self.eesp = VGGBlock(nin, nout_new, stride=2, down_method='avg')
self.avg = nn.AvgPool2d(kernel_size=3, padding=1, stride=2)
if reinf:
self.inp_reinf = nn.Sequential(CBR(config_inp_reinf, config_inp_reinf, 3, 1... | Down-sampling fucntion that has three parallel branches: (1) avg pooling, (2) EESP block with stride of 2 and (3) efficient long-range connection with the input. The output feature maps of branches from (1) and (2) are concatenated and then additively fused with (3) to produce the final output. | DownSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownSampler:
"""Down-sampling fucntion that has three parallel branches: (1) avg pooling, (2) EESP block with stride of 2 and (3) efficient long-range connection with the input. The output feature maps of branches from (1) and (2) are concatenated and then additively fused with (3) to produce the... | stack_v2_sparse_classes_10k_train_005419 | 8,682 | permissive | [
{
"docstring": ":param nin: number of input channels :param nout: number of output channels :param k: # of parallel branches :param r_lim: A maximum value of receptive field allowed for EESP block :param reinf: Use long range shortcut connection with the input or not.",
"name": "__init__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_002982 | Implement the Python class `DownSampler` described below.
Class description:
Down-sampling fucntion that has three parallel branches: (1) avg pooling, (2) EESP block with stride of 2 and (3) efficient long-range connection with the input. The output feature maps of branches from (1) and (2) are concatenated and then a... | Implement the Python class `DownSampler` described below.
Class description:
Down-sampling fucntion that has three parallel branches: (1) avg pooling, (2) EESP block with stride of 2 and (3) efficient long-range connection with the input. The output feature maps of branches from (1) and (2) are concatenated and then a... | d00a290cb1c86cb079acef69f914805737cb3696 | <|skeleton|>
class DownSampler:
"""Down-sampling fucntion that has three parallel branches: (1) avg pooling, (2) EESP block with stride of 2 and (3) efficient long-range connection with the input. The output feature maps of branches from (1) and (2) are concatenated and then additively fused with (3) to produce the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DownSampler:
"""Down-sampling fucntion that has three parallel branches: (1) avg pooling, (2) EESP block with stride of 2 and (3) efficient long-range connection with the input. The output feature maps of branches from (1) and (2) are concatenated and then additively fused with (3) to produce the final output... | the_stack_v2_python_sparse | affspec/models/vgg.py | BeibinLi/affspec | train | 0 |
5b0500661a868e1922a93a3abd6f634c0d08e8ec | [
"self.name = name\nself.num = num\nself.school = school\nself.course = course\nself.classes = classes",
"ret = MyPickle.load(file)\nfor i in ret.values():\n if self.name == i.name:\n Public.print('%s已经存在!' % self.name, 'error')\n return 0\nself.num = len(ret) + 1\nself.school = school_obj\nret[se... | <|body_start_0|>
self.name = name
self.num = num
self.school = school
self.course = course
self.classes = classes
<|end_body_0|>
<|body_start_1|>
ret = MyPickle.load(file)
for i in ret.values():
if self.name == i.name:
Public.print('%s... | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def __init__(self, name, num=0, school='', course={}, classes={}):
""":param name: 老师、学生名称 :param num: 老师、学生ID :param school: 所属学校 一个老师、学生只能属于一所学校 :param course: 老师、学生可以有多个课程{} :param classes: 老师、学生可以有多个班级{}"""
<|body_0|>
def create(self, school_obj, file, types):
... | stack_v2_sparse_classes_10k_train_005420 | 3,775 | no_license | [
{
"docstring": ":param name: 老师、学生名称 :param num: 老师、学生ID :param school: 所属学校 一个老师、学生只能属于一所学校 :param course: 老师、学生可以有多个课程{} :param classes: 老师、学生可以有多个班级{}",
"name": "__init__",
"signature": "def __init__(self, name, num=0, school='', course={}, classes={})"
},
{
"docstring": "创建老师 :param school_o... | 2 | stack_v2_sparse_classes_30k_train_005076 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, name, num=0, school='', course={}, classes={}): :param name: 老师、学生名称 :param num: 老师、学生ID :param school: 所属学校 一个老师、学生只能属于一所学校 :param course: 老师、学生可以有多个课程{} :param class... | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, name, num=0, school='', course={}, classes={}): :param name: 老师、学生名称 :param num: 老师、学生ID :param school: 所属学校 一个老师、学生只能属于一所学校 :param course: 老师、学生可以有多个课程{} :param class... | d7fc68d3d23345df5bfb09d4a84686c8b49a5ad7 | <|skeleton|>
class User:
def __init__(self, name, num=0, school='', course={}, classes={}):
""":param name: 老师、学生名称 :param num: 老师、学生ID :param school: 所属学校 一个老师、学生只能属于一所学校 :param course: 老师、学生可以有多个课程{} :param classes: 老师、学生可以有多个班级{}"""
<|body_0|>
def create(self, school_obj, file, types):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class User:
def __init__(self, name, num=0, school='', course={}, classes={}):
""":param name: 老师、学生名称 :param num: 老师、学生ID :param school: 所属学校 一个老师、学生只能属于一所学校 :param course: 老师、学生可以有多个课程{} :param classes: 老师、学生可以有多个班级{}"""
self.name = name
self.num = num
self.school = school
... | the_stack_v2_python_sparse | Homework/day07/core/school.py | 214031230/Python21 | train | 0 | |
8ae77dd3bd20febd7b55ee9856d2252ec4e85ae7 | [
"super(Test200SmartSanityUpload005, self).prepare()\nself.logger.info('Preconditions:')\nself.logger.info('1. Open Micro/WINr; ')\nself.logger.info('2. Set up connection with PLC;')",
"super(Test200SmartSanityUpload005, self).process()\nself.logger.info('Step actions:')\nself.logger.info('1. Generate subroutine... | <|body_start_0|>
super(Test200SmartSanityUpload005, self).prepare()
self.logger.info('Preconditions:')
self.logger.info('1. Open Micro/WINr; ')
self.logger.info('2. Set up connection with PLC;')
<|end_body_0|>
<|body_start_1|>
super(Test200SmartSanityUpload005, self).process()
... | Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data logs with the frequency of 1 times 1s; 3. Download all... | Test200SmartSanityUpload005 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test200SmartSanityUpload005:
"""Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data... | stack_v2_sparse_classes_10k_train_005421 | 3,776 | no_license | [
{
"docstring": "the preparation before executing the test steps Args: Example: Return: Author: Cai, Yong IsInterface: False ChangeInfo: Cai, Yong 2019-09-20 create",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "execute the test steps Args: Example: Return: Author: Cai, ... | 3 | null | Implement the Python class `Test200SmartSanityUpload005` described below.
Class description:
Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a n... | Implement the Python class `Test200SmartSanityUpload005` described below.
Class description:
Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a n... | 2d3490393737b3e5f086cb6623369b988ffce67f | <|skeleton|>
class Test200SmartSanityUpload005:
"""Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test200SmartSanityUpload005:
"""Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data logs with th... | the_stack_v2_python_sparse | test_case/no_piling/sanity/base/upload/test_200smart_sanity_upload_005.py | Lewescaiyong/auto_test_framework | train | 1 |
ac03b07363e0644afe73ddc8348c18d9a3582ffa | [
"super(TestPmd, self).__init__()\nself.host = host\nself.ssh_prompt = self.host.config.get('cli_user_prompt', self.host.config.get('ssh_user', 'root') + '@')\nself.interactive_prompt = 'testpmd>'\nself.non_interactive_prompt = 'Press enter to exit'\nself.interactive = False\nself.run_status = False",
"inserts = r... | <|body_start_0|>
super(TestPmd, self).__init__()
self.host = host
self.ssh_prompt = self.host.config.get('cli_user_prompt', self.host.config.get('ssh_user', 'root') + '@')
self.interactive_prompt = 'testpmd>'
self.non_interactive_prompt = 'Press enter to exit'
self.intera... | TestPmd | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPmd:
def __init__(self, host):
"""Initialize TestPmd class."""
<|body_0|>
def start(self, interactive_shell=True, end_options='', timeout=10, **kwargs):
"""Start testpmd tool. Args: interactive_shell(bool): Interactive shell flag end_options(str): Arguments to be... | stack_v2_sparse_classes_10k_train_005422 | 5,825 | permissive | [
{
"docstring": "Initialize TestPmd class.",
"name": "__init__",
"signature": "def __init__(self, host)"
},
{
"docstring": "Start testpmd tool. Args: interactive_shell(bool): Interactive shell flag end_options(str): Arguments to be passed after '--' in command line timeout(int): Timeout kwargs(di... | 4 | null | Implement the Python class `TestPmd` described below.
Class description:
Implement the TestPmd class.
Method signatures and docstrings:
- def __init__(self, host): Initialize TestPmd class.
- def start(self, interactive_shell=True, end_options='', timeout=10, **kwargs): Start testpmd tool. Args: interactive_shell(boo... | Implement the Python class `TestPmd` described below.
Class description:
Implement the TestPmd class.
Method signatures and docstrings:
- def __init__(self, host): Initialize TestPmd class.
- def start(self, interactive_shell=True, end_options='', timeout=10, **kwargs): Start testpmd tool. Args: interactive_shell(boo... | 2007bf3fe66edfe704e485141c55caed54fe13aa | <|skeleton|>
class TestPmd:
def __init__(self, host):
"""Initialize TestPmd class."""
<|body_0|>
def start(self, interactive_shell=True, end_options='', timeout=10, **kwargs):
"""Start testpmd tool. Args: interactive_shell(bool): Interactive shell flag end_options(str): Arguments to be... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestPmd:
def __init__(self, host):
"""Initialize TestPmd class."""
super(TestPmd, self).__init__()
self.host = host
self.ssh_prompt = self.host.config.get('cli_user_prompt', self.host.config.get('ssh_user', 'root') + '@')
self.interactive_prompt = 'testpmd>'
sel... | the_stack_v2_python_sparse | taf/testlib/linux/testpmd.py | AndriyZabavskyy/taf | train | 0 | |
e53f5b36f7ba730f6b1c917f031edf2513b8f21c | [
"self.groups = game.all_sprites\npygame.sprite.Sprite.__init__(self, self.groups)\nself.game = game\nself.image = game.player_img\nself.rect = self.image.get_rect()\nself.vel = vec(0, 0)\nself.pos = vec(x, y) * TILESIZE",
"self.handle_input()\nself.pos += self.vel * self.game.dt\nself.rect.x = self.pos.x\nself.co... | <|body_start_0|>
self.groups = game.all_sprites
pygame.sprite.Sprite.__init__(self, self.groups)
self.game = game
self.image = game.player_img
self.rect = self.image.get_rect()
self.vel = vec(0, 0)
self.pos = vec(x, y) * TILESIZE
<|end_body_0|>
<|body_start_1|>
... | Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
def __init__(self, game, x, y):
"""Use a game image, preloaded in Game, and add new vectors to handle position and desired velocity (input)"""
<|body_0|>
def update(self):
"""Let's get those vectors to work!"""
<|body_1|>
def handle_input(self):
... | stack_v2_sparse_classes_10k_train_005423 | 2,790 | no_license | [
{
"docstring": "Use a game image, preloaded in Game, and add new vectors to handle position and desired velocity (input)",
"name": "__init__",
"signature": "def __init__(self, game, x, y)"
},
{
"docstring": "Let's get those vectors to work!",
"name": "update",
"signature": "def update(se... | 4 | stack_v2_sparse_classes_30k_train_003105 | Implement the Python class `Player` described below.
Class description:
Implement the Player class.
Method signatures and docstrings:
- def __init__(self, game, x, y): Use a game image, preloaded in Game, and add new vectors to handle position and desired velocity (input)
- def update(self): Let's get those vectors t... | Implement the Python class `Player` described below.
Class description:
Implement the Player class.
Method signatures and docstrings:
- def __init__(self, game, x, y): Use a game image, preloaded in Game, and add new vectors to handle position and desired velocity (input)
- def update(self): Let's get those vectors t... | 349367254f85e3e4273cede067ca950913a1332c | <|skeleton|>
class Player:
def __init__(self, game, x, y):
"""Use a game image, preloaded in Game, and add new vectors to handle position and desired velocity (input)"""
<|body_0|>
def update(self):
"""Let's get those vectors to work!"""
<|body_1|>
def handle_input(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Player:
def __init__(self, game, x, y):
"""Use a game image, preloaded in Game, and add new vectors to handle position and desired velocity (input)"""
self.groups = game.all_sprites
pygame.sprite.Sprite.__init__(self, self.groups)
self.game = game
self.image = game.play... | the_stack_v2_python_sparse | 11-videogames/Referencia/05-Vectores y sprites/sprites.py | pythoncanarias/eoi | train | 26 | |
cb3c659d628ce19299a30bf96fa5288c23c34547 | [
"if len(self.size) != len(self.grain_size):\n raise RuntimeError('Dimensions of size and grain_size are not equal.')\nX = np.random.random((self.n_samples,) + self.size)\n_gaussian_size = np.around(self.grain_size).astype(int)\ngaussian = fourier_gaussian(np.ones(_gaussian_size), np.ones(len(self.size)))\nfilter... | <|body_start_0|>
if len(self.size) != len(self.grain_size):
raise RuntimeError('Dimensions of size and grain_size are not equal.')
X = np.random.random((self.n_samples,) + self.size)
_gaussian_size = np.around(self.grain_size).astype(int)
gaussian = fourier_gaussian(np.ones(_... | Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator = MicrostructureGenerator(n_samples, size, ... n_p... | MicrostructureGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicrostructureGenerator:
"""Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator... | stack_v2_sparse_classes_10k_train_005424 | 3,149 | permissive | [
{
"docstring": "Generates a microstructure of dimensions of self.size and grains with dimensions self.grain_size. Returns: periodic microstructure",
"name": "generate",
"signature": "def generate(self)"
},
{
"docstring": "Takes in blurred array and assigns phase values. Args: X_blur: random fiel... | 2 | stack_v2_sparse_classes_30k_train_004144 | Implement the Python class `MicrostructureGenerator` described below.
Class description:
Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases... | Implement the Python class `MicrostructureGenerator` described below.
Class description:
Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases... | 9b582ddd5e120ea50d9023301577797ae5c434c3 | <|skeleton|>
class MicrostructureGenerator:
"""Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MicrostructureGenerator:
"""Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator = Microstruc... | the_stack_v2_python_sparse | pymks/datasets/microstructure_generator.py | materialsinnovation/pymks | train | 118 |
1c97b39681d97a0e07772b633d3625a89aa4842f | [
"self.cleanup_error = cleanup_error\nself.data_migration_error = data_migration_error\nself.error = error\nself.finished = finished\nself.instant_recovery_finished = instant_recovery_finished\nself.migrate_task_moref = migrate_task_moref\nself.restore_disks_task_info_proto = restore_disks_task_info_proto\nself.slav... | <|body_start_0|>
self.cleanup_error = cleanup_error
self.data_migration_error = data_migration_error
self.error = error
self.finished = finished
self.instant_recovery_finished = instant_recovery_finished
self.migrate_task_moref = migrate_task_moref
self.restore_di... | Implementation of the 'RecoverVirtualDiskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RecoverVirtualDiskInfoProto extension Location =============================================================================... | RecoverVirtualDiskInfoProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecoverVirtualDiskInfoProto:
"""Implementation of the 'RecoverVirtualDiskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RecoverVirtualDiskInfoProto extension Location ======================... | stack_v2_sparse_classes_10k_train_005425 | 5,669 | permissive | [
{
"docstring": "Constructor for the RecoverVirtualDiskInfoProto class",
"name": "__init__",
"signature": "def __init__(self, cleanup_error=None, data_migration_error=None, error=None, finished=None, instant_recovery_finished=None, migrate_task_moref=None, restore_disks_task_info_proto=None, slave_task_s... | 2 | stack_v2_sparse_classes_30k_train_005226 | Implement the Python class `RecoverVirtualDiskInfoProto` described below.
Class description:
Implementation of the 'RecoverVirtualDiskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RecoverVirtualDiskInfoProto ex... | Implement the Python class `RecoverVirtualDiskInfoProto` described below.
Class description:
Implementation of the 'RecoverVirtualDiskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RecoverVirtualDiskInfoProto ex... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RecoverVirtualDiskInfoProto:
"""Implementation of the 'RecoverVirtualDiskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RecoverVirtualDiskInfoProto extension Location ======================... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RecoverVirtualDiskInfoProto:
"""Implementation of the 'RecoverVirtualDiskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RecoverVirtualDiskInfoProto extension Location ===================================... | the_stack_v2_python_sparse | cohesity_management_sdk/models/recover_virtual_disk_info_proto.py | cohesity/management-sdk-python | train | 24 |
5f45935372d3cb33d0e21d88a390bcc90e986189 | [
"super(YoloDetector, self).__init__()\nkernel_depth = num_anchors * (4 + 1 + num_classes)\nself.in_channels = in_ch\nself.mid_channels = round(in_ch / 2)\nself.out_channels = kernel_depth\nself.batch_norm = batch_norm\nself.num_anchors = num_anchors\nself.num_classes = num_classes\nself.index_in = index\nself.conv_... | <|body_start_0|>
super(YoloDetector, self).__init__()
kernel_depth = num_anchors * (4 + 1 + num_classes)
self.in_channels = in_ch
self.mid_channels = round(in_ch / 2)
self.out_channels = kernel_depth
self.batch_norm = batch_norm
self.num_anchors = num_anchors
... | Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p+2, ..., p_C] x B | YoloDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YoloDetector:
"""Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p... | stack_v2_sparse_classes_10k_train_005426 | 28,014 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, in_ch, num_classes=3, num_anchors=3, batch_norm=True, index=0)"
},
{
"docstring": "Foward method",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000237 | Implement the Python class `YoloDetector` described below.
Class description:
Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangemen... | Implement the Python class `YoloDetector` described below.
Class description:
Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangemen... | 69edb5ecd569395086cf610df9c8aa345284259a | <|skeleton|>
class YoloDetector:
"""Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class YoloDetector:
"""Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p+2, ..., p_C]... | the_stack_v2_python_sparse | python/models/modules.py | dswanderley/detntorch | train | 2 |
68e95eca89b6aadc4c04613e1128a108ba1357ae | [
"if not s:\n return ''\ntemp = ''.join(map(''.join, zip(['#'] * len(s), s)) + ['#'])\nlen_temp = len(temp)\np = [0] * len_temp\nrb = 0\nc = 0\nmax_idx = max_len = 0\nfor idx in xrange(1, len_temp):\n p[idx] = min(p[2 * c - idx], rb - idx) if rb > idx else 0\n while idx - p[idx] > 0 and idx + p[idx] + 1 < l... | <|body_start_0|>
if not s:
return ''
temp = ''.join(map(''.join, zip(['#'] * len(s), s)) + ['#'])
len_temp = len(temp)
p = [0] * len_temp
rb = 0
c = 0
max_idx = max_len = 0
for idx in xrange(1, len_temp):
p[idx] = min(p[2 * c - idx]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k_train_005427 | 2,202 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
},
{
"docstring": ":type s: str :rtype:... | 3 | stack_v2_sparse_classes_30k_train_003719 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: str
... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
if not s:
return ''
temp = ''.join(map(''.join, zip(['#'] * len(s), s)) + ['#'])
len_temp = len(temp)
p = [0] * len_temp
rb = 0
c = 0
max_idx = max_len = 0
... | the_stack_v2_python_sparse | LC5.py | Qiao-Liang/LeetCode | train | 0 | |
534f87f72a5e7f27a9d9f89e635dd515e651247e | [
"queryset = super(GroupReportListView, self).get_queryset().extra(select={'reply_count': \"SELECT COUNT(*) from connectmessages_message m JOIN connectmessages_thread t ON m.thread_id = t.id JOIN accounts_user u ON m.sender_id = u.id WHERE t.group_id = groups_group.id AND m.id != t.first_message_id AND u.is_banned ... | <|body_start_0|>
queryset = super(GroupReportListView, self).get_queryset().extra(select={'reply_count': "SELECT COUNT(*) from connectmessages_message m JOIN connectmessages_thread t ON m.thread_id = t.id JOIN accounts_user u ON m.sender_id = u.id WHERE t.group_id = groups_group.id AND m.id != t.first_message_... | View for reporting on groups. | GroupReportListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupReportListView:
"""View for reporting on groups."""
def get_queryset(self):
"""Update the queryset with some annotations."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Pass in extra context to the view"""
<|body_1|>
def render_to_respon... | stack_v2_sparse_classes_10k_train_005428 | 10,353 | permissive | [
{
"docstring": "Update the queryset with some annotations.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Pass in extra context to the view",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "If ... | 3 | stack_v2_sparse_classes_30k_train_003007 | Implement the Python class `GroupReportListView` described below.
Class description:
View for reporting on groups.
Method signatures and docstrings:
- def get_queryset(self): Update the queryset with some annotations.
- def get_context_data(self, **kwargs): Pass in extra context to the view
- def render_to_response(s... | Implement the Python class `GroupReportListView` described below.
Class description:
View for reporting on groups.
Method signatures and docstrings:
- def get_queryset(self): Update the queryset with some annotations.
- def get_context_data(self, **kwargs): Pass in extra context to the view
- def render_to_response(s... | a56c0f89df82694bf5db32a04d8b092974791972 | <|skeleton|>
class GroupReportListView:
"""View for reporting on groups."""
def get_queryset(self):
"""Update the queryset with some annotations."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Pass in extra context to the view"""
<|body_1|>
def render_to_respon... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupReportListView:
"""View for reporting on groups."""
def get_queryset(self):
"""Update the queryset with some annotations."""
queryset = super(GroupReportListView, self).get_queryset().extra(select={'reply_count': "SELECT COUNT(*) from connectmessages_message m JOIN connectmessages_th... | the_stack_v2_python_sparse | open_connect/reporting/views.py | ofa/connect | train | 66 |
151525e898ec500441bfc8112922cff8c6b1d582 | [
"self.position = [(0, 0)]\nself.food = food\nself.width, self.height = (width, height)\nself.moves = {'U': (0, -1), 'L': (-1, 0), 'R': (1, 0), 'D': (0, 1)}\nself.score = 0",
"x = self.position[0][0] + self.moves[direction][0]\ny = self.position[0][1] + self.moves[direction][1]\nif not self.width > x >= 0 or not s... | <|body_start_0|>
self.position = [(0, 0)]
self.food = food
self.width, self.height = (width, height)
self.moves = {'U': (0, -1), 'L': (-1, 0), 'R': (1, 0), 'D': (0, 1)}
self.score = 0
<|end_body_0|>
<|body_start_1|>
x = self.position[0][0] + self.moves[direction][0]
... | https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1 | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
"""https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1"""
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param f... | stack_v2_sparse_classes_10k_train_005429 | 1,779 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_004436 | Implement the Python class `SnakeGame` described below.
Class description:
https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param wi... | Implement the Python class `SnakeGame` described below.
Class description:
https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param wi... | 54d777e11b91c5debe49c1aef723234c66a5d2cc | <|skeleton|>
class SnakeGame:
"""https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1"""
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnakeGame:
"""https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1"""
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list ... | the_stack_v2_python_sparse | leetcode_solution/design/#353.Design_Snake_Game.py | HsiangHung/Code-Challenges | train | 0 |
3491ad03c0f4d6f13dec2594eada7be988e69cd8 | [
"parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory)\nUnmarshaller._unmarshal_relationships(pkg_reader, package, parts)\nfor part in parts.values():\n part.after_unmarshal()\npackage.after_unmarshal()",
"parts = {}\nfor partname, content_type, blob in pkg_reader.iter_sparts():\n parts[p... | <|body_start_0|>
parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory)
Unmarshaller._unmarshal_relationships(pkg_reader, package, parts)
for part in parts.values():
part.after_unmarshal()
package.after_unmarshal()
<|end_body_0|>
<|body_start_1|>
pa... | Hosts static methods for unmarshalling a package from a |PackageReader| instance. | Unmarshaller | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unmarshaller:
"""Hosts static methods for unmarshalling a package from a |PackageReader| instance."""
def unmarshal(pkg_reader, package, part_factory):
"""Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part t... | stack_v2_sparse_classes_10k_train_005430 | 20,155 | permissive | [
{
"docstring": "Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part to *part_factory*. Package relationships are added to *pkg*.",
"name": "unmarshal",
"signature": "def unmarshal(pkg_reader, package, part_factory)"
},
{
... | 3 | null | Implement the Python class `Unmarshaller` described below.
Class description:
Hosts static methods for unmarshalling a package from a |PackageReader| instance.
Method signatures and docstrings:
- def unmarshal(pkg_reader, package, part_factory): Construct graph of parts and realized relationships based on the content... | Implement the Python class `Unmarshaller` described below.
Class description:
Hosts static methods for unmarshalling a package from a |PackageReader| instance.
Method signatures and docstrings:
- def unmarshal(pkg_reader, package, part_factory): Construct graph of parts and realized relationships based on the content... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class Unmarshaller:
"""Hosts static methods for unmarshalling a package from a |PackageReader| instance."""
def unmarshal(pkg_reader, package, part_factory):
"""Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Unmarshaller:
"""Hosts static methods for unmarshalling a package from a |PackageReader| instance."""
def unmarshal(pkg_reader, package, part_factory):
"""Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part to *part_facto... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/opc/package.py | ryfeus/lambda-packs | train | 1,283 |
da4708d020c852337f1a7a47888e898f53352091 | [
"msg = msg or 'List request successfully processed.'\ndata = {'header': response_header(msg=msg, username=username, api_status=constants.STATUS_OK), 'detail': serializer.data}\nif add_pagination:\n data['header']['pagination'] = dict()\nreturn data",
"queryset = self.filter_queryset(self.get_queryset())\npage ... | <|body_start_0|>
msg = msg or 'List request successfully processed.'
data = {'header': response_header(msg=msg, username=username, api_status=constants.STATUS_OK), 'detail': serializer.data}
if add_pagination:
data['header']['pagination'] = dict()
return data
<|end_body_0|>
... | Django rest framework list model mixin class | DRFListModelMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DRFListModelMixin:
"""Django rest framework list model mixin class"""
def build_list_data(self, serializer, username, msg=None, add_pagination=False):
"""build list data"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""Fetch instance list Called on GET ... | stack_v2_sparse_classes_10k_train_005431 | 12,654 | no_license | [
{
"docstring": "build list data",
"name": "build_list_data",
"signature": "def build_list_data(self, serializer, username, msg=None, add_pagination=False)"
},
{
"docstring": "Fetch instance list Called on GET request for collection endpoint",
"name": "list",
"signature": "def list(self, ... | 2 | stack_v2_sparse_classes_30k_train_002422 | Implement the Python class `DRFListModelMixin` described below.
Class description:
Django rest framework list model mixin class
Method signatures and docstrings:
- def build_list_data(self, serializer, username, msg=None, add_pagination=False): build list data
- def list(self, request, *args, **kwargs): Fetch instanc... | Implement the Python class `DRFListModelMixin` described below.
Class description:
Django rest framework list model mixin class
Method signatures and docstrings:
- def build_list_data(self, serializer, username, msg=None, add_pagination=False): build list data
- def list(self, request, *args, **kwargs): Fetch instanc... | 974ff553d93823312df906e9986155422b9d730b | <|skeleton|>
class DRFListModelMixin:
"""Django rest framework list model mixin class"""
def build_list_data(self, serializer, username, msg=None, add_pagination=False):
"""build list data"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""Fetch instance list Called on GET ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DRFListModelMixin:
"""Django rest framework list model mixin class"""
def build_list_data(self, serializer, username, msg=None, add_pagination=False):
"""build list data"""
msg = msg or 'List request successfully processed.'
data = {'header': response_header(msg=msg, username=user... | the_stack_v2_python_sparse | src/ondalear/backend/api/base_views.py | ajaniv/document-management | train | 0 |
5dac373331926eb7c96493ca13e52938fb7906f1 | [
"self.trie = Trie()\nfor i, sentence in enumerate(sentences):\n self.trie.insert(sentence, times[i])\nself.cur_sentence = ''",
"if c != '#':\n self.cur_sentence += c\n candidates = self.trie.find_words(self.cur_sentence)\n candidates_times = []\n for candidate in candidates:\n cur_node = sel... | <|body_start_0|>
self.trie = Trie()
for i, sentence in enumerate(sentences):
self.trie.insert(sentence, times[i])
self.cur_sentence = ''
<|end_body_0|>
<|body_start_1|>
if c != '#':
self.cur_sentence += c
candidates = self.trie.find_words(self.cur_sen... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.trie = Trie()
... | stack_v2_sparse_classes_10k_train_005432 | 7,846 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | e7e529f2c04dc0cca8d823b7774871974422f7a6 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.trie = Trie()
for i, sentence in enumerate(sentences):
self.trie.insert(sentence, times[i])
self.cur_sentence = ''
def input(self, c):
... | the_stack_v2_python_sparse | Trie/642. Design Search Autocomplete System.py | Jason101616/LeetCode_Solution | train | 2 | |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(DQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=... | <|body_start_0|>
super(DQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = FCE... | DQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optio... | stack_v2_sparse_classes_10k_train_005433 | 30,380 | permissive | [
{
"docstring": "Overview: Init the DQN (encoder + head) Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation space shape, such as 8 or [4, 84, 84]. - action_shape (:obj:`Union[int, SequenceType]`): Action space shape, such as 6 or [2, 3, 3]. - encoder_hidden_... | 2 | null | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size:... | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size:... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optio... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None)... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 | |
13cba4b5ea1f788566ccf02592fc13fd3f7ae042 | [
"super().__init__(name, level=level)\nself.Deque = collections.deque([], 50)\nself._metrics_counter = metrics_counter",
"if record.levelno == logging.WARNING:\n self._metrics_counter.add('warning', 1)\nelif record.levelno >= logging.ERROR:\n self._metrics_counter.add('error', 1)\nrecord.timestamp = self._fo... | <|body_start_0|>
super().__init__(name, level=level)
self.Deque = collections.deque([], 50)
self._metrics_counter = metrics_counter
<|end_body_0|>
<|body_start_1|>
if record.levelno == logging.WARNING:
self._metrics_counter.add('warning', 1)
elif record.levelno >= lo... | PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp. | PipelineLogger | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineLogger:
"""PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp."""
def __init__(self, name, metrics_counter, level=logging.NO... | stack_v2_sparse_classes_10k_train_005434 | 24,170 | permissive | [
{
"docstring": "Itialize a metrics counter.",
"name": "__init__",
"signature": "def __init__(self, name, metrics_counter, level=logging.NOTSET)"
},
{
"docstring": "Counts and add errors to the error counter. **Parameters** record : Record that is evaluated.",
"name": "handle",
"signature... | 3 | null | Implement the Python class `PipelineLogger` described below.
Class description:
PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp.
Method signatures and docs... | Implement the Python class `PipelineLogger` described below.
Class description:
PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp.
Method signatures and docs... | 11ee3689d0ff6e9b662deeb3fc5e18bb0aabc8f2 | <|skeleton|>
class PipelineLogger:
"""PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp."""
def __init__(self, name, metrics_counter, level=logging.NO... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PipelineLogger:
"""PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp."""
def __init__(self, name, metrics_counter, level=logging.NOTSET):
... | the_stack_v2_python_sparse | bspump/pipeline.py | LibertyAces/BitSwanPump | train | 24 |
1abe9da6a20bb1086c0837faf9fd4e7af63f03e8 | [
"self._payment_dates = payment_dates\nself._payment_steps = payment_steps\nself._maturity = payment_dates[len(payment_dates) - 1]\nself._steps = payment_steps[len(payment_steps) - 1]\nself._bond_tree = {}",
"if not hw_tree._is_built:\n hw_tree.hw_prob()\n hw_tree.calibrate()",
"self.build_hw_tree(hw_tree)... | <|body_start_0|>
self._payment_dates = payment_dates
self._payment_steps = payment_steps
self._maturity = payment_dates[len(payment_dates) - 1]
self._steps = payment_steps[len(payment_steps) - 1]
self._bond_tree = {}
<|end_body_0|>
<|body_start_1|>
if not hw_tree._is_bui... | Representation of a Zero Coupon Bond | ZCBond | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZCBond:
"""Representation of a Zero Coupon Bond"""
def __init__(self, payment_dates, payment_steps):
"""Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with inte... | stack_v2_sparse_classes_10k_train_005435 | 6,090 | no_license | [
{
"docstring": "Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with integer payment steps that corresponds to the tree coupon_rates : scalar or array_like of shape (1, ) with the coupon ra... | 3 | stack_v2_sparse_classes_30k_train_000564 | Implement the Python class `ZCBond` described below.
Class description:
Representation of a Zero Coupon Bond
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps): Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment ... | Implement the Python class `ZCBond` described below.
Class description:
Representation of a Zero Coupon Bond
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps): Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment ... | 9f710a8de56fb9b4456c6f98be91f4b22ef5ede5 | <|skeleton|>
class ZCBond:
"""Representation of a Zero Coupon Bond"""
def __init__(self, payment_dates, payment_steps):
"""Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with inte... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZCBond:
"""Representation of a Zero Coupon Bond"""
def __init__(self, payment_dates, payment_steps):
"""Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with integer payment s... | the_stack_v2_python_sparse | Hull-White Model/simple_bond.py | jesusmramirez/Term-Structure-Models | train | 1 |
c9a663c85bab3e44f79a3548d2329cc05a1271a0 | [
"filter_parser = reqparse.RequestParser(bundle_errors=True)\nfilter_parser.add_argument('last_pk', type=int, default=0, location='args')\nfilter_parser.add_argument('limit_num', type=int, default=20, location='args')\nfilter_parser_args = filter_parser.parse_args()\ndata = get_inventory_limit_rows_by_last_id(**filt... | <|body_start_0|>
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('last_pk', type=int, default=0, location='args')
filter_parser.add_argument('limit_num', type=int, default=20, location='args')
filter_parser_args = filter_parser.parse_args()
d... | InventoryListResource | InventoryListResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InventoryListResource:
"""InventoryListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:... | stack_v2_sparse_classes_10k_train_005436 | 5,543 | permissive | [
{
"docstring": "Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Example: curl http://0.0.0.0:5000/bearings/inventories -H \"Content-Type: applicati... | 2 | stack_v2_sparse_classes_30k_train_007129 | Implement the Python class `InventoryListResource` described below.
Class description:
InventoryListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:
- def post(self): Example:... | Implement the Python class `InventoryListResource` described below.
Class description:
InventoryListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:
- def post(self): Example:... | 6ef54f3f7efbbaff6169e963dcf45ab25e11e593 | <|skeleton|>
class InventoryListResource:
"""InventoryListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InventoryListResource:
"""InventoryListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:"""
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_... | the_stack_v2_python_sparse | web_api/bearings/resources/inventory.py | zhanghe06/flask_restful | train | 2 |
744b85f377a0d84048fbf5c614a594194706623f | [
"processed = 0\nfor base in queryset:\n base.ResetNames()\n processed += 1\nself.message_user(request, '%s reset.' % GetMessageBit(processed))",
"processed = 0\nfor base in queryset:\n base.stateManaged = 'new'\n base.ResetNames()\n processed += 1\nself.message_user(request, '%s reset and marked as... | <|body_start_0|>
processed = 0
for base in queryset:
base.ResetNames()
processed += 1
self.message_user(request, '%s reset.' % GetMessageBit(processed))
<|end_body_0|>
<|body_start_1|>
processed = 0
for base in queryset:
base.stateManaged = 'n... | XrumerBaseSpamAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XrumerBaseSpamAdmin:
def ResetNames(self, request, queryset):
"""Сбрасываем имена"""
<|body_0|>
def ResetNamesAndNew(self, request, queryset):
"""Сбрасываем имена и помечаем как новые"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
processed = 0
... | stack_v2_sparse_classes_10k_train_005437 | 29,849 | no_license | [
{
"docstring": "Сбрасываем имена",
"name": "ResetNames",
"signature": "def ResetNames(self, request, queryset)"
},
{
"docstring": "Сбрасываем имена и помечаем как новые",
"name": "ResetNamesAndNew",
"signature": "def ResetNamesAndNew(self, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000026 | Implement the Python class `XrumerBaseSpamAdmin` described below.
Class description:
Implement the XrumerBaseSpamAdmin class.
Method signatures and docstrings:
- def ResetNames(self, request, queryset): Сбрасываем имена
- def ResetNamesAndNew(self, request, queryset): Сбрасываем имена и помечаем как новые | Implement the Python class `XrumerBaseSpamAdmin` described below.
Class description:
Implement the XrumerBaseSpamAdmin class.
Method signatures and docstrings:
- def ResetNames(self, request, queryset): Сбрасываем имена
- def ResetNamesAndNew(self, request, queryset): Сбрасываем имена и помечаем как новые
<|skeleton... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class XrumerBaseSpamAdmin:
def ResetNames(self, request, queryset):
"""Сбрасываем имена"""
<|body_0|>
def ResetNamesAndNew(self, request, queryset):
"""Сбрасываем имена и помечаем как новые"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XrumerBaseSpamAdmin:
def ResetNames(self, request, queryset):
"""Сбрасываем имена"""
processed = 0
for base in queryset:
base.ResetNames()
processed += 1
self.message_user(request, '%s reset.' % GetMessageBit(processed))
def ResetNamesAndNew(self, r... | the_stack_v2_python_sparse | doorsadmin/admin.py | cash2one/doorscenter | train | 0 | |
a6c281e8f305aa16daccbae177e1962225fcf450 | [
"if not nums:\n return True\nsum_all = sum(nums)\nif sum_all & 1 == 1:\n return False\nsum_half = sum_all / 2\ndp = [[False for j in range(sum_half + 1)] for i in range(len(nums))]\nfor i in range(len(nums)):\n dp[i][0] = True\nfor i in range(1, len(nums)):\n for j in range(1, sum_half + 1):\n dp... | <|body_start_0|>
if not nums:
return True
sum_all = sum(nums)
if sum_all & 1 == 1:
return False
sum_half = sum_all / 2
dp = [[False for j in range(sum_half + 1)] for i in range(len(nums))]
for i in range(len(nums)):
dp[i][0] = True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return True
... | stack_v2_sparse_classes_10k_train_005438 | 1,997 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartition",
"signature": "def canPartition(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartition",
"signature": "def canPartition(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004904 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): :type nums: List[int] :rtype: bool
- def canPartition(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): :type nums: List[int] :rtype: bool
- def canPartition(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
def canPart... | 8853f85214ac88db024d26e228f1848dd5acd933 | <|skeleton|>
class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
if not nums:
return True
sum_all = sum(nums)
if sum_all & 1 == 1:
return False
sum_half = sum_all / 2
dp = [[False for j in range(sum_half + 1)] for i in ran... | the_stack_v2_python_sparse | 416-PartitionEqualSubsetSum/PartitionEqualSubsetSum.py | cqxmzhc/my_leetcode_solutions | train | 2 | |
ab473e48183d95ef12932b7c1151ce6c242a0d49 | [
"if not devices:\n devices = [0]\nself._device_queue = Queue()\nself._done_queue = Queue()\nfor d in devices:\n self._device_queue.put(str(d))\n_LOGGER.info(f'Initialized profiler runner with devices: {devices}')\nself._timeout = timeout\nself._executor = concurrent.futures.ThreadPoolExecutor(max_workers=len(... | <|body_start_0|>
if not devices:
devices = [0]
self._device_queue = Queue()
self._done_queue = Queue()
for d in devices:
self._device_queue.put(str(d))
_LOGGER.info(f'Initialized profiler runner with devices: {devices}')
self._timeout = timeout
... | Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on its dedicated GPU. This property hasn't bee... | ProfilerRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilerRunner:
"""Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on i... | stack_v2_sparse_classes_10k_train_005439 | 12,702 | permissive | [
{
"docstring": "Parameters ---------- devices : List[str] device identifiers (contents of {CUDA,HIP}_VISIBLE_DEVICES) postprocessing_delegate : object responsible for postprocessing results after futures completion timeout : int timeout to wait for all profilers completion in seconds",
"name": "__init__",
... | 3 | stack_v2_sparse_classes_30k_val_000089 | Implement the Python class `ProfilerRunner` described below.
Class description:
Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each... | Implement the Python class `ProfilerRunner` described below.
Class description:
Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each... | c60dc19788217556ba12ea378c02b9fd0aea9ffe | <|skeleton|>
class ProfilerRunner:
"""Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProfilerRunner:
"""Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on its dedicated ... | the_stack_v2_python_sparse | python/aitemplate/backend/profiler_runner.py | facebookincubator/AITemplate | train | 4,065 |
a81dbc485d1fe5d0a1f03fec649204af9001c197 | [
"s = s.strip()\nif not len(s):\n return 0\nk = 1 if s[0] in ['+', '-'] else 0\nwhile k < len(s) and s[k].isdigit():\n k += 1\nif k == 1 and s[0] in ['+', '-']:\n return 0\nnum = int(s[0:k]) if k > 0 else 0\nif num < -2 ** 31:\n return -2 ** 31\nelif num > 2 ** 31 - 1:\n return 2 ** 31 - 1\nelse:\n ... | <|body_start_0|>
s = s.strip()
if not len(s):
return 0
k = 1 if s[0] in ['+', '-'] else 0
while k < len(s) and s[k].isdigit():
k += 1
if k == 1 and s[0] in ['+', '-']:
return 0
num = int(s[0:k]) if k > 0 else 0
if num < -2 ** 31... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type s: str :rtype: int 时间击败66.28%,内存击败35.18%"""
<|body_0|>
def myAtoi1(self, s: str) -> int:
""":type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处理的题目往往涉及复杂的流程以及条件情况,如果直接上手写程序,一不小心就会写出极其臃肿的代码。 因此,为了有条理地分析每个输... | stack_v2_sparse_classes_10k_train_005440 | 3,861 | no_license | [
{
"docstring": ":type s: str :rtype: int 时间击败66.28%,内存击败35.18%",
"name": "myAtoi",
"signature": "def myAtoi(self, s)"
},
{
"docstring": ":type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处理的题目往往涉及复杂的流程以及条件情况,如果直接上手写程序,一不小心就会写出极其臃肿的代码。 因此,为了有条理地分析每个输入字符的处理方法,我们可以使用自动机这个概念: ... | 2 | stack_v2_sparse_classes_30k_train_003837 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type s: str :rtype: int 时间击败66.28%,内存击败35.18%
- def myAtoi1(self, s: str) -> int: :type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type s: str :rtype: int 时间击败66.28%,内存击败35.18%
- def myAtoi1(self, s: str) -> int: :type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处... | 2dc982e690b153c33bc7e27a63604f754a0df90c | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type s: str :rtype: int 时间击败66.28%,内存击败35.18%"""
<|body_0|>
def myAtoi1(self, s: str) -> int:
""":type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处理的题目往往涉及复杂的流程以及条件情况,如果直接上手写程序,一不小心就会写出极其臃肿的代码。 因此,为了有条理地分析每个输... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def myAtoi(self, s):
""":type s: str :rtype: int 时间击败66.28%,内存击败35.18%"""
s = s.strip()
if not len(s):
return 0
k = 1 if s[0] in ['+', '-'] else 0
while k < len(s) and s[k].isdigit():
k += 1
if k == 1 and s[0] in ['+', '-']:
... | the_stack_v2_python_sparse | 8_string-to-integer-atoi.py | 95275059/Algorithm | train | 0 | |
d7abfe5ff429b3d5fd8ffcbbb3960273d88b767f | [
"form = FormService.get_by_id(form_id=form_id)\nif form is None:\n raise BadRequest('No such form')\nif form.owner_id != current_user.id:\n raise Forbidden(\"Can't view fields of the form that doesn't belong to you\")\nform_fields = FormFieldService.filter(form_id=form.id)\nform_fields_json = []\nfor form_fie... | <|body_start_0|>
form = FormService.get_by_id(form_id=form_id)
if form is None:
raise BadRequest('No such form')
if form.owner_id != current_user.id:
raise Forbidden("Can't view fields of the form that doesn't belong to you")
form_fields = FormFieldService.filter(... | FormFields API url: 'forms/{form_id}/fields/' methods: get, post | FormFieldsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormFieldsAPI:
"""FormFields API url: 'forms/{form_id}/fields/' methods: get, post"""
def get(self, form_id):
"""Get all fields that are contained within a form :param form_id: ID of the form that contains fields"""
<|body_0|>
def post(self, form_id):
"""Add fiel... | stack_v2_sparse_classes_10k_train_005441 | 10,042 | no_license | [
{
"docstring": "Get all fields that are contained within a form :param form_id: ID of the form that contains fields",
"name": "get",
"signature": "def get(self, form_id)"
},
{
"docstring": "Add field to a form :param form_id: ID of the form to which the field will be inserted",
"name": "post... | 2 | stack_v2_sparse_classes_30k_train_002651 | Implement the Python class `FormFieldsAPI` described below.
Class description:
FormFields API url: 'forms/{form_id}/fields/' methods: get, post
Method signatures and docstrings:
- def get(self, form_id): Get all fields that are contained within a form :param form_id: ID of the form that contains fields
- def post(sel... | Implement the Python class `FormFieldsAPI` described below.
Class description:
FormFields API url: 'forms/{form_id}/fields/' methods: get, post
Method signatures and docstrings:
- def get(self, form_id): Get all fields that are contained within a form :param form_id: ID of the form that contains fields
- def post(sel... | 7344e4bd1cc977781b35a2ad1b38ff0d270163b7 | <|skeleton|>
class FormFieldsAPI:
"""FormFields API url: 'forms/{form_id}/fields/' methods: get, post"""
def get(self, form_id):
"""Get all fields that are contained within a form :param form_id: ID of the form that contains fields"""
<|body_0|>
def post(self, form_id):
"""Add fiel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FormFieldsAPI:
"""FormFields API url: 'forms/{form_id}/fields/' methods: get, post"""
def get(self, form_id):
"""Get all fields that are contained within a form :param form_id: ID of the form that contains fields"""
form = FormService.get_by_id(form_id=form_id)
if form is None:
... | the_stack_v2_python_sparse | src/app/routers/form_field.py | Lv-474-Python/ngfg | train | 0 |
58fef73df6ce18437f3c8ba1b52dd3afb7a29001 | [
"super(ConvDropoutNormNonlin, self).__init__()\nif nonlin_kwargs is None:\n nonlin_kwargs = {'alpha': 0.01, 'inplace': True}\nif dropout_op_kwargs is None:\n dropout_op_kwargs = {'p': 0.5, 'inplace': True}\nif norm_op_kwargs is None:\n norm_op_kwargs = {'eps': 1e-05, 'affine': True, 'momentum': 0.9}\nif co... | <|body_start_0|>
super(ConvDropoutNormNonlin, self).__init__()
if nonlin_kwargs is None:
nonlin_kwargs = {'alpha': 0.01, 'inplace': True}
if dropout_op_kwargs is None:
dropout_op_kwargs = {'p': 0.5, 'inplace': True}
if norm_op_kwargs is None:
norm_op_k... | fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad. | ConvDropoutNormNonlin | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvDropoutNormNonlin:
"""fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad."""
def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=Non... | stack_v2_sparse_classes_10k_train_005442 | 24,212 | permissive | [
{
"docstring": "init class",
"name": "__init__",
"signature": "def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=None, nonlin=nn.LeakyReLU, nonlin_kwargs=None)"
},
{
"docs... | 2 | null | Implement the Python class `ConvDropoutNormNonlin` described below.
Class description:
fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad.
Method signatures and docstrings:
- def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2... | Implement the Python class `ConvDropoutNormNonlin` described below.
Class description:
fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad.
Method signatures and docstrings:
- def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class ConvDropoutNormNonlin:
"""fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad."""
def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=Non... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConvDropoutNormNonlin:
"""fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad."""
def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=None, nonlin=nn.... | the_stack_v2_python_sparse | research/cv/nnUNet/src/nnunet/network_architecture/generic_UNet.py | mindspore-ai/models | train | 301 |
d13d087464b40df9ee5d4fc05ab47f609ff1c1c8 | [
"super(LockedDictionary, self).__init__()\nfor k, v in template.items():\n super(LockedDictionary, self).__setitem__(k, v)",
"if self.has_key(key):\n super(LockedDictionary, self).__setitem__(key, value)\nelse:\n msg = 'Can not ad key to LockedDictionary: %s' % key\n raise KeyError(msg)"
] | <|body_start_0|>
super(LockedDictionary, self).__init__()
for k, v in template.items():
super(LockedDictionary, self).__setitem__(k, v)
<|end_body_0|>
<|body_start_1|>
if self.has_key(key):
super(LockedDictionary, self).__setitem__(key, value)
else:
m... | Defines a dictionary subclass with a pre-determined set of keys. It is not possible to add new keys after construction. | LockedDictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LockedDictionary:
"""Defines a dictionary subclass with a pre-determined set of keys. It is not possible to add new keys after construction."""
def __init__(self, template):
"""Construct new LockedDictionary. ARGS: template - dictionary which defined allowed keys and initial values."... | stack_v2_sparse_classes_10k_train_005443 | 1,021 | no_license | [
{
"docstring": "Construct new LockedDictionary. ARGS: template - dictionary which defined allowed keys and initial values.",
"name": "__init__",
"signature": "def __init__(self, template)"
},
{
"docstring": "Sets dictionary value. Raises KeyError for invalid key.",
"name": "__setitem__",
... | 2 | null | Implement the Python class `LockedDictionary` described below.
Class description:
Defines a dictionary subclass with a pre-determined set of keys. It is not possible to add new keys after construction.
Method signatures and docstrings:
- def __init__(self, template): Construct new LockedDictionary. ARGS: template - d... | Implement the Python class `LockedDictionary` described below.
Class description:
Defines a dictionary subclass with a pre-determined set of keys. It is not possible to add new keys after construction.
Method signatures and docstrings:
- def __init__(self, template): Construct new LockedDictionary. ARGS: template - d... | 97f530ff0841b9604f0d9575e7e1f0e3c0660be0 | <|skeleton|>
class LockedDictionary:
"""Defines a dictionary subclass with a pre-determined set of keys. It is not possible to add new keys after construction."""
def __init__(self, template):
"""Construct new LockedDictionary. ARGS: template - dictionary which defined allowed keys and initial values."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LockedDictionary:
"""Defines a dictionary subclass with a pre-determined set of keys. It is not possible to add new keys after construction."""
def __init__(self, template):
"""Construct new LockedDictionary. ARGS: template - dictionary which defined allowed keys and initial values."""
su... | the_stack_v2_python_sparse | llia/locked_dictionary.py | plewto/Llia | train | 17 |
71cb7560329bfaa4a7626ebc3e96b75016849a9b | [
"super(AtomEmbedding, self).__init__()\nself._dim = dim\nself._type_num = type_num\nif pre_train is not None:\n self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0)\nelse:\n self.embedding = nn.Embedding(type_num, dim, padding_idx=0)",
"atom_list = g.ndata['nodes']\ng.ndata[p_name] = self... | <|body_start_0|>
super(AtomEmbedding, self).__init__()
self._dim = dim
self._type_num = type_num
if pre_train is not None:
self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0)
else:
self.embedding = nn.Embedding(type_num, dim, padding_id... | Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. | AtomEmbedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtomEmbedding:
"""Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding."""
def __init__(self, dim=128, type_num=100, pre_train=None):
"""Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the la... | stack_v2_sparse_classes_10k_train_005444 | 12,339 | no_license | [
{
"docstring": "Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings",
"name": "__init__",
"signature": "def __init__(self, dim=128, type_num=100, pre_train=None)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_test_000288 | Implement the Python class `AtomEmbedding` described below.
Class description:
Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding.
Method signatures and docstrings:
- def __init__(self, dim=128, type_num=100, pre_train=None): Randomly init the element embe... | Implement the Python class `AtomEmbedding` described below.
Class description:
Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding.
Method signatures and docstrings:
- def __init__(self, dim=128, type_num=100, pre_train=None): Randomly init the element embe... | 721c54bb79914275dd3bb8718b78d67ff362f0cb | <|skeleton|>
class AtomEmbedding:
"""Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding."""
def __init__(self, dim=128, type_num=100, pre_train=None):
"""Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the la... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AtomEmbedding:
"""Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding."""
def __init__(self, dim=128, type_num=100, pre_train=None):
"""Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic ... | the_stack_v2_python_sparse | bayes_al/mm_sch.py | qkqkfldis1/improved_asgn | train | 1 |
acfdcb335c32e36881c60c686687326fa053f4ca | [
"self.model_type = model_type\nself.fire = kwargs.get('fire', 2)\nself.refract = kwargs.get('refract', 4)\nself.t_max = self.fire + self.refract\nself.precision = kwargs.get('precision', 0.97)\nself.activation_time = kwargs.get('activation_time', -1)\nself.potential = kwargs.get('potential', 1)",
"self.activation... | <|body_start_0|>
self.model_type = model_type
self.fire = kwargs.get('fire', 2)
self.refract = kwargs.get('refract', 4)
self.t_max = self.fire + self.refract
self.precision = kwargs.get('precision', 0.97)
self.activation_time = kwargs.get('activation_time', -1)
se... | The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance fire : float The duration of time it takes for the neuronal current to reach its peak refract : float The duration of time it t... | Firing_Model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Firing_Model:
"""The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance fire : float The duration of time it takes for the neuronal current to reach its peak r... | stack_v2_sparse_classes_10k_train_005445 | 13,526 | permissive | [
{
"docstring": "Parameters ---------- model_type : str Describes the type of firing model for this Firing_Model instance **fire : float Specifies the duration of time it takes for the neuronal current to reach its peak **refract : float Specifies the duration of time it takes after reaching the peak current to ... | 2 | stack_v2_sparse_classes_30k_train_004642 | Implement the Python class `Firing_Model` described below.
Class description:
The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance fire : float The duration of time it takes for t... | Implement the Python class `Firing_Model` described below.
Class description:
The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance fire : float The duration of time it takes for t... | 93aa6312ab53e6a71f6ef5dd1fc6b2187d852ee1 | <|skeleton|>
class Firing_Model:
"""The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance fire : float The duration of time it takes for the neuronal current to reach its peak r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Firing_Model:
"""The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance fire : float The duration of time it takes for the neuronal current to reach its peak refract : floa... | the_stack_v2_python_sparse | neuralnet/neuron_stable_adjust.py | orrenravid1/AML | train | 0 |
3106cb9233ae0604f22467633ca8f556cb0207f5 | [
"self._r = r\nself.rotationmap = EulerAnglesMap(eulerangles)\nself.x_rotationmap = EulerAnglesMap(eulerangles=[0, np.pi / 2, 0])",
"elev, azim = self.rotationmap.invmap(elev, azim)\nelev, azim = self.x_rotationmap.invmap(elev, azim)\nrxy = self._r * np.sqrt(1 - np.sin(elev))\nx = -rxy * np.cos(azim)\ny = -rxy * n... | <|body_start_0|>
self._r = r
self.rotationmap = EulerAnglesMap(eulerangles)
self.x_rotationmap = EulerAnglesMap(eulerangles=[0, np.pi / 2, 0])
<|end_body_0|>
<|body_start_1|>
elev, azim = self.rotationmap.invmap(elev, azim)
elev, azim = self.x_rotationmap.invmap(elev, azim)
... | https://en.wikipedia.org/wiki/Albers_projection Compared to the entry of 8/21/2015 (numbers were chosen to have simpler formulas) phi1 = 90, phi2 = 0, phi0 = 90, lambda0 = 90 lambda <- 2n (lambda - lambda0) (doubles the area) => n = 0.5 rho0 = 0, C = 1, rho = 2sqrt(1-sin(phi)) | AlbersProjectionMap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbersProjectionMap:
"""https://en.wikipedia.org/wiki/Albers_projection Compared to the entry of 8/21/2015 (numbers were chosen to have simpler formulas) phi1 = 90, phi2 = 0, phi0 = 90, lambda0 = 90 lambda <- 2n (lambda - lambda0) (doubles the area) => n = 0.5 rho0 = 0, C = 1, rho = 2sqrt(1-sin(p... | stack_v2_sparse_classes_10k_train_005446 | 16,243 | permissive | [
{
"docstring": "r: radious of the sphere from which the projection is made",
"name": "__init__",
"signature": "def __init__(self, r, eulerangles=None)"
},
{
"docstring": "Returns (nan, nan) if point cannot be mapped else (x, y) arguments can be numpy arrays or scalars",
"name": "map",
"s... | 3 | stack_v2_sparse_classes_30k_train_001554 | Implement the Python class `AlbersProjectionMap` described below.
Class description:
https://en.wikipedia.org/wiki/Albers_projection Compared to the entry of 8/21/2015 (numbers were chosen to have simpler formulas) phi1 = 90, phi2 = 0, phi0 = 90, lambda0 = 90 lambda <- 2n (lambda - lambda0) (doubles the area) => n = 0... | Implement the Python class `AlbersProjectionMap` described below.
Class description:
https://en.wikipedia.org/wiki/Albers_projection Compared to the entry of 8/21/2015 (numbers were chosen to have simpler formulas) phi1 = 90, phi2 = 0, phi0 = 90, lambda0 = 90 lambda <- 2n (lambda - lambda0) (doubles the area) => n = 0... | fdab351e6c5530c8f051193158856ba6ef11d715 | <|skeleton|>
class AlbersProjectionMap:
"""https://en.wikipedia.org/wiki/Albers_projection Compared to the entry of 8/21/2015 (numbers were chosen to have simpler formulas) phi1 = 90, phi2 = 0, phi0 = 90, lambda0 = 90 lambda <- 2n (lambda - lambda0) (doubles the area) => n = 0.5 rho0 = 0, C = 1, rho = 2sqrt(1-sin(p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AlbersProjectionMap:
"""https://en.wikipedia.org/wiki/Albers_projection Compared to the entry of 8/21/2015 (numbers were chosen to have simpler formulas) phi1 = 90, phi2 = 0, phi0 = 90, lambda0 = 90 lambda <- 2n (lambda - lambda0) (doubles the area) => n = 0.5 rho0 = 0, C = 1, rho = 2sqrt(1-sin(phi))"""
... | the_stack_v2_python_sparse | retina/screen/map/mapimpl.py | neurokernel/retina | train | 5 |
f1e58c936b4258b55895310b80c3071fa46b50ec | [
"req = 'xbuddy/latest?for_update=true&return_dir=true'\nself.assertEqual(dev_server_wrapper.GenerateXbuddyRequest('latest', 'update'), req)\npath = 'xbuddy://remote/stumpy/version'\nreq = 'xbuddy/remote/stumpy/version?for_update=true&return_dir=true'\nself.assertEqual(dev_server_wrapper.GenerateXbuddyRequest(path, ... | <|body_start_0|>
req = 'xbuddy/latest?for_update=true&return_dir=true'
self.assertEqual(dev_server_wrapper.GenerateXbuddyRequest('latest', 'update'), req)
path = 'xbuddy://remote/stumpy/version'
req = 'xbuddy/remote/stumpy/version?for_update=true&return_dir=true'
self.assertEqual... | Test xbuddy helper functions. | TestXbuddyHelpers | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestXbuddyHelpers:
"""Test xbuddy helper functions."""
def testGenerateXbuddyRequestForUpdate(self):
"""Test we generate correct xbuddy requests."""
<|body_0|>
def testGenerateXbuddyRequestForImage(self):
"""Tests that we generate correct requests to get images."... | stack_v2_sparse_classes_10k_train_005447 | 4,351 | permissive | [
{
"docstring": "Test we generate correct xbuddy requests.",
"name": "testGenerateXbuddyRequestForUpdate",
"signature": "def testGenerateXbuddyRequestForUpdate(self)"
},
{
"docstring": "Tests that we generate correct requests to get images.",
"name": "testGenerateXbuddyRequestForImage",
"... | 6 | stack_v2_sparse_classes_30k_train_004014 | Implement the Python class `TestXbuddyHelpers` described below.
Class description:
Test xbuddy helper functions.
Method signatures and docstrings:
- def testGenerateXbuddyRequestForUpdate(self): Test we generate correct xbuddy requests.
- def testGenerateXbuddyRequestForImage(self): Tests that we generate correct req... | Implement the Python class `TestXbuddyHelpers` described below.
Class description:
Test xbuddy helper functions.
Method signatures and docstrings:
- def testGenerateXbuddyRequestForUpdate(self): Test we generate correct xbuddy requests.
- def testGenerateXbuddyRequestForImage(self): Tests that we generate correct req... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TestXbuddyHelpers:
"""Test xbuddy helper functions."""
def testGenerateXbuddyRequestForUpdate(self):
"""Test we generate correct xbuddy requests."""
<|body_0|>
def testGenerateXbuddyRequestForImage(self):
"""Tests that we generate correct requests to get images."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestXbuddyHelpers:
"""Test xbuddy helper functions."""
def testGenerateXbuddyRequestForUpdate(self):
"""Test we generate correct xbuddy requests."""
req = 'xbuddy/latest?for_update=true&return_dir=true'
self.assertEqual(dev_server_wrapper.GenerateXbuddyRequest('latest', 'update'),... | the_stack_v2_python_sparse | third_party/chromite/lib/dev_server_wrapper_unittest.py | metux/chromium-suckless | train | 5 |
a0266aedc1cb8b3ec3e13ebea46c7473f04bf21e | [
"if isinstance(request.auth, ProjectKey):\n return self.respond(status=401)\npaginate_kwargs = {}\ntry:\n environment = self._get_environment_from_request(request, project.organization_id)\nexcept Environment.DoesNotExist:\n queryset = UserReport.objects.none()\nelse:\n queryset = UserReport.objects.fil... | <|body_start_0|>
if isinstance(request.auth, ProjectKey):
return self.respond(status=401)
paginate_kwargs = {}
try:
environment = self._get_environment_from_request(request, project.organization_id)
except Environment.DoesNotExist:
queryset = UserRepor... | ProjectUserReportsEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectUserReportsEndpoint:
def get(self, request: Request, project) -> Response:
"""List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string proj... | stack_v2_sparse_classes_10k_train_005448 | 4,699 | permissive | [
{
"docstring": "List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string project_slug: the slug of the project. :auth: required",
"name": "get",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_004446 | Implement the Python class `ProjectUserReportsEndpoint` described below.
Class description:
Implement the ProjectUserReportsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project) -> Response: List a Project's User Feedback `````````````````````````````` Return a list of user feed... | Implement the Python class `ProjectUserReportsEndpoint` described below.
Class description:
Implement the ProjectUserReportsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project) -> Response: List a Project's User Feedback `````````````````````````````` Return a list of user feed... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class ProjectUserReportsEndpoint:
def get(self, request: Request, project) -> Response:
"""List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string proj... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectUserReportsEndpoint:
def get(self, request: Request, project) -> Response:
"""List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string project_slug: the ... | the_stack_v2_python_sparse | src/sentry/api/endpoints/project_user_reports.py | nagyist/sentry | train | 0 | |
1c5dbc3157d316e4c59177ed1004b4d71e1ed12d | [
"if not head or not head.next:\n return head\nfastNode, slowNode = (head.next, head)\nwhile fastNode and fastNode.next:\n fastNode = fastNode.next.next\n slowNode = slowNode.next\nsecondHalf = slowNode.next\nslowNode.next = None\nleftHalf = self.sortList(head)\nrightHalf = self.sortList(secondHalf)\nreturn... | <|body_start_0|>
if not head or not head.next:
return head
fastNode, slowNode = (head.next, head)
while fastNode and fastNode.next:
fastNode = fastNode.next.next
slowNode = slowNode.next
secondHalf = slowNode.next
slowNode.next = None
l... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not ... | stack_v2_sparse_classes_10k_train_005449 | 1,616 | permissive | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "sortList",
"signature": "def sortList(self, head)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortList(self, head): :type head: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortList(self, head): :type head: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|skeleton|>
class Solu... | 20ae1a048eddbc9a32c819cf61258e2b57572f05 | <|skeleton|>
class Solution:
def sortList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sortList(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return head
fastNode, slowNode = (head.next, head)
while fastNode and fastNode.next:
fastNode = fastNode.next.next
slowNode = slowNo... | the_stack_v2_python_sparse | leetcode.com/python/148_Sort_List.py | partho-maple/coding-interview-gym | train | 862 | |
4bfce75251e9be1422e99e8890b65567d20bb59e | [
"self.name = 'SVRModel'\nsuper(SVRModel, self).__init__(self.name, use_logger)\nif self.use_logger:\n self.logger = ml.SciopeLogger().get_logger()\n self.logger.info('Support Vector Regression model initialized')",
"cs = [0.001, 0.01, 0.1, 1, 10]\ngammas = [0.001, 0.01, 0.1, 1]\nparam_grid = {'C': cs, 'gamm... | <|body_start_0|>
self.name = 'SVRModel'
super(SVRModel, self).__init__(self.name, use_logger)
if self.use_logger:
self.logger = ml.SciopeLogger().get_logger()
self.logger.info('Support Vector Regression model initialized')
<|end_body_0|>
<|body_start_1|>
cs = [0.... | We use the sklearn SVM implementation here. | SVRModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVRModel:
"""We use the sklearn SVM implementation here."""
def __init__(self, use_logger=False):
"""Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default ... | stack_v2_sparse_classes_10k_train_005450 | 3,383 | permissive | [
{
"docstring": "Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default False",
"name": "__init__",
"signature": "def __init__(self, use_logger=False)"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_train_007356 | Implement the Python class `SVRModel` described below.
Class description:
We use the sklearn SVM implementation here.
Method signatures and docstrings:
- def __init__(self, use_logger=False): Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Con... | Implement the Python class `SVRModel` described below.
Class description:
We use the sklearn SVM implementation here.
Method signatures and docstrings:
- def __init__(self, use_logger=False): Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Con... | 5122107dedcee9c39458e83d853ec35f91268780 | <|skeleton|>
class SVRModel:
"""We use the sklearn SVM implementation here."""
def __init__(self, use_logger=False):
"""Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SVRModel:
"""We use the sklearn SVM implementation here."""
def __init__(self, use_logger=False):
"""Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default False"""
... | the_stack_v2_python_sparse | sciope/models/svm_regressor.py | rmjiang7/sciope | train | 0 |
7a567786be016aa8e52f9996d18bbae469960405 | [
"import pandas as pd\nraw_data = pd.read_excel(filename_1, sheet_name)\nself.df1 = raw_data[raw_data[' Whether or not metasomatism'] == 1].drop(['Whether or not metasomatism', 'CITATION'], axis=1)\nself.df2 = raw_data[raw_data['Whether or not metasomatism'] == -1].drop(['Whether or not metasomatism', 'CITATION'], a... | <|body_start_0|>
import pandas as pd
raw_data = pd.read_excel(filename_1, sheet_name)
self.df1 = raw_data[raw_data[' Whether or not metasomatism'] == 1].drop(['Whether or not metasomatism', 'CITATION'], axis=1)
self.df2 = raw_data[raw_data['Whether or not metasomatism'] == -1].drop(['Whe... | ElementsInCurve | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElementsInCurve:
def __init__(self, filename_1, filename_2, sheet_name):
"""Input the file containing the elements data :param filename_1: Trace elements total 700 + data :param filename_2: trace Standardized values (ppm) :param sheet_name: 0 = Rare earth elements; 1 = Trace multi elemen... | stack_v2_sparse_classes_10k_train_005451 | 3,811 | permissive | [
{
"docstring": "Input the file containing the elements data :param filename_1: Trace elements total 700 + data :param filename_2: trace Standardized values (ppm) :param sheet_name: 0 = Rare earth elements; 1 = Trace multi element",
"name": "__init__",
"signature": "def __init__(self, filename_1, filenam... | 2 | stack_v2_sparse_classes_30k_train_003584 | Implement the Python class `ElementsInCurve` described below.
Class description:
Implement the ElementsInCurve class.
Method signatures and docstrings:
- def __init__(self, filename_1, filename_2, sheet_name): Input the file containing the elements data :param filename_1: Trace elements total 700 + data :param filena... | Implement the Python class `ElementsInCurve` described below.
Class description:
Implement the ElementsInCurve class.
Method signatures and docstrings:
- def __init__(self, filename_1, filename_2, sheet_name): Input the file containing the elements data :param filename_1: Trace elements total 700 + data :param filena... | ca0f220598ee156028646fbefccde08b2ece62ea | <|skeleton|>
class ElementsInCurve:
def __init__(self, filename_1, filename_2, sheet_name):
"""Input the file containing the elements data :param filename_1: Trace elements total 700 + data :param filename_2: trace Standardized values (ppm) :param sheet_name: 0 = Rare earth elements; 1 = Trace multi elemen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElementsInCurve:
def __init__(self, filename_1, filename_2, sheet_name):
"""Input the file containing the elements data :param filename_1: Trace elements total 700 + data :param filename_2: trace Standardized values (ppm) :param sheet_name: 0 = Rare earth elements; 1 = Trace multi element"""
i... | the_stack_v2_python_sparse | english/others/Elements_in_Curve.py | Lyuyangdaisy/DS_package | train | 0 | |
67495304b0a2d841043606f93e7787b974301a39 | [
"ctx.num_sync_devices = num_sync_devices\nctx.num_groups = num_groups\ninput_list = [torch.zeros_like(input) for k in range(du.get_local_size())]\ndist.all_gather(input_list, input, async_op=False, group=du._LOCAL_PROCESS_GROUP)\ninputs = torch.stack(input_list, dim=0)\nif num_groups > 1:\n rank = du.get_local_r... | <|body_start_0|>
ctx.num_sync_devices = num_sync_devices
ctx.num_groups = num_groups
input_list = [torch.zeros_like(input) for k in range(du.get_local_size())]
dist.all_gather(input_list, input, async_op=False, group=du._LOCAL_PROCESS_GROUP)
inputs = torch.stack(input_list, dim=0... | GroupGather performs all gather on each of the local process/ GPU groups. | GroupGather | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupGather:
"""GroupGather performs all gather on each of the local process/ GPU groups."""
def forward(ctx, input, num_sync_devices, num_groups):
"""Perform forwarding, gathering the stats across different process/ GPU group."""
<|body_0|>
def backward(ctx, grad_output... | stack_v2_sparse_classes_10k_train_005452 | 7,462 | permissive | [
{
"docstring": "Perform forwarding, gathering the stats across different process/ GPU group.",
"name": "forward",
"signature": "def forward(ctx, input, num_sync_devices, num_groups)"
},
{
"docstring": "Perform backwarding, gathering the gradients across different process/ GPU group.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_003975 | Implement the Python class `GroupGather` described below.
Class description:
GroupGather performs all gather on each of the local process/ GPU groups.
Method signatures and docstrings:
- def forward(ctx, input, num_sync_devices, num_groups): Perform forwarding, gathering the stats across different process/ GPU group.... | Implement the Python class `GroupGather` described below.
Class description:
GroupGather performs all gather on each of the local process/ GPU groups.
Method signatures and docstrings:
- def forward(ctx, input, num_sync_devices, num_groups): Perform forwarding, gathering the stats across different process/ GPU group.... | 03279afc8d16509bf54cd9142304cd2d403f6e93 | <|skeleton|>
class GroupGather:
"""GroupGather performs all gather on each of the local process/ GPU groups."""
def forward(ctx, input, num_sync_devices, num_groups):
"""Perform forwarding, gathering the stats across different process/ GPU group."""
<|body_0|>
def backward(ctx, grad_output... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupGather:
"""GroupGather performs all gather on each of the local process/ GPU groups."""
def forward(ctx, input, num_sync_devices, num_groups):
"""Perform forwarding, gathering the stats across different process/ GPU group."""
ctx.num_sync_devices = num_sync_devices
ctx.num_gr... | the_stack_v2_python_sparse | models/SlowFast/slowfast/models/batchnorm_helper.py | artest08/LateTemporalModeling3DCNN | train | 171 |
337d251bede5507040fc47825a050dc47343107c | [
"self.parent = None\nself.value = value\nself.left = left\nself.right = right\nif left:\n self.left.parent = self\nif right:\n self.right.parent = self",
"vals = [self.value]\nif self.left:\n vals = vals + self.left.nodeValues()\nif self.right:\n vals = vals + self.right.nodeValues()\nreturn vals"
] | <|body_start_0|>
self.parent = None
self.value = value
self.left = left
self.right = right
if left:
self.left.parent = self
if right:
self.right.parent = self
<|end_body_0|>
<|body_start_1|>
vals = [self.value]
if self.left:
... | Node class for a binary tree. | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""Node class for a binary tree."""
def __init__(self, value, left=None, right=None):
"""Initialize the node."""
<|body_0|>
def nodeValues(self):
"""Get all the values in the tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.paren... | stack_v2_sparse_classes_10k_train_005453 | 1,543 | no_license | [
{
"docstring": "Initialize the node.",
"name": "__init__",
"signature": "def __init__(self, value, left=None, right=None)"
},
{
"docstring": "Get all the values in the tree.",
"name": "nodeValues",
"signature": "def nodeValues(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007092 | Implement the Python class `Node` described below.
Class description:
Node class for a binary tree.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): Initialize the node.
- def nodeValues(self): Get all the values in the tree. | Implement the Python class `Node` described below.
Class description:
Node class for a binary tree.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): Initialize the node.
- def nodeValues(self): Get all the values in the tree.
<|skeleton|>
class Node:
"""Node class for a binar... | 97eae3ee806756f4d646d600f434b1e68164ad34 | <|skeleton|>
class Node:
"""Node class for a binary tree."""
def __init__(self, value, left=None, right=None):
"""Initialize the node."""
<|body_0|>
def nodeValues(self):
"""Get all the values in the tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Node:
"""Node class for a binary tree."""
def __init__(self, value, left=None, right=None):
"""Initialize the node."""
self.parent = None
self.value = value
self.left = left
self.right = right
if left:
self.left.parent = self
if right:
... | the_stack_v2_python_sparse | Python/2019_05_20_Problem_125_Sum_Node_Pair_to_k.py | BaoCaiH/Daily_Coding_Problem | train | 0 |
87f603b715a1859ca1275bcf28cd6c2565bf93a0 | [
"self.initial_date = initial_date\nself.until_date = until_date\nlog.debug('self.initial_date: {}'.format(self.initial_date))\nlog.debug('self.until_date: {}'.format(self.until_date))",
"log.debug('Build all')\nprint('Building...')\nlog.debug('Detail')\nprint('\\nAdding to details table for:')\nself.dict_parse('D... | <|body_start_0|>
self.initial_date = initial_date
self.until_date = until_date
log.debug('self.initial_date: {}'.format(self.initial_date))
log.debug('self.until_date: {}'.format(self.until_date))
<|end_body_0|>
<|body_start_1|>
log.debug('Build all')
print('Building...'... | Take structured data and enter into database. | Build | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Build:
"""Take structured data and enter into database."""
def __init__(self, initial_date=None, until_date=None):
"""Create class variables for date range and connect to database."""
<|body_0|>
def build_all(self):
"""Run through all of the building methods."""
... | stack_v2_sparse_classes_10k_train_005454 | 4,162 | no_license | [
{
"docstring": "Create class variables for date range and connect to database.",
"name": "__init__",
"signature": "def __init__(self, initial_date=None, until_date=None)"
},
{
"docstring": "Run through all of the building methods.",
"name": "build_all",
"signature": "def build_all(self)"... | 5 | stack_v2_sparse_classes_30k_train_006426 | Implement the Python class `Build` described below.
Class description:
Take structured data and enter into database.
Method signatures and docstrings:
- def __init__(self, initial_date=None, until_date=None): Create class variables for date range and connect to database.
- def build_all(self): Run through all of the ... | Implement the Python class `Build` described below.
Class description:
Take structured data and enter into database.
Method signatures and docstrings:
- def __init__(self, initial_date=None, until_date=None): Create class variables for date range and connect to database.
- def build_all(self): Run through all of the ... | 4ad7c77ab56681e9ca8e1dd1033a32c21c498d75 | <|skeleton|>
class Build:
"""Take structured data and enter into database."""
def __init__(self, initial_date=None, until_date=None):
"""Create class variables for date range and connect to database."""
<|body_0|>
def build_all(self):
"""Run through all of the building methods."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Build:
"""Take structured data and enter into database."""
def __init__(self, initial_date=None, until_date=None):
"""Create class variables for date range and connect to database."""
self.initial_date = initial_date
self.until_date = until_date
log.debug('self.initial_dat... | the_stack_v2_python_sparse | scripts/build.py | TheLens/realestate | train | 1 |
8cc52ef865c61466dc07b260ae6d756ed843f84b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TeamworkActivityTopic()",
"from .teamwork_activity_topic_source import TeamworkActivityTopicSource\nfrom .teamwork_activity_topic_source import TeamworkActivityTopicSource\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lam... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TeamworkActivityTopic()
<|end_body_0|>
<|body_start_1|>
from .teamwork_activity_topic_source import TeamworkActivityTopicSource
from .teamwork_activity_topic_source import TeamworkActivi... | TeamworkActivityTopic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamworkActivityTopic:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkActivityTopic:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_10k_train_005455 | 3,494 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TeamworkActivityTopic",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `TeamworkActivityTopic` described below.
Class description:
Implement the TeamworkActivityTopic class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkActivityTopic: Creates a new instance of the appropriate class base... | Implement the Python class `TeamworkActivityTopic` described below.
Class description:
Implement the TeamworkActivityTopic class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkActivityTopic: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TeamworkActivityTopic:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkActivityTopic:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeamworkActivityTopic:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkActivityTopic:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | the_stack_v2_python_sparse | msgraph/generated/models/teamwork_activity_topic.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d3dd88cb08d0f53335d53af3d6c1000101e69745 | [
"super(Lexer, self).__init__(TOKENS, TokenNamespace)\nif t_regexp is None:\n unique = {}\n for token in tokens:\n token.compile(alphabet)\n self._debug(fmt('Token: {0}', token))\n unique[token.id_] = token\n t_regexp = Compiler.multiple(alphabet, [(t.id_, t.regexp) for t in unique.valu... | <|body_start_0|>
super(Lexer, self).__init__(TOKENS, TokenNamespace)
if t_regexp is None:
unique = {}
for token in tokens:
token.compile(alphabet)
self._debug(fmt('Token: {0}', token))
unique[token.id_] = token
t_regexp ... | This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user. | Lexer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lexer:
"""This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""
def __init__(self, m... | stack_v2_sparse_classes_10k_train_005456 | 6,369 | no_license | [
{
"docstring": "matcher is the head of the original matcher graph, which will be called with a tokenised stream. tokens is the set of `Token` instances that define the lexer. alphabet is the alphabet for which the regexps are defined. discard is the regular expression for spaces (which are silently dropped if n... | 4 | stack_v2_sparse_classes_30k_train_002934 | Implement the Python class `Lexer` described below.
Class description:
This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by... | Implement the Python class `Lexer` described below.
Class description:
This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by... | 0603505f187acc3c7da2e1a6083833a201f8b061 | <|skeleton|>
class Lexer:
"""This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""
def __init__(self, m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Lexer:
"""This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""
def __init__(self, matcher, token... | the_stack_v2_python_sparse | src/lepl/lexer/lexer.py | nyimbi/LEPL | train | 2 |
0bce5d590b96e434cd8aee7531a321bc648c1981 | [
"self.graph = graph\nself.color = dict(((node, 'WHITE') for node in self.graph.iternodes()))\nself.distance = dict(((node, float('inf')) for node in self.graph.iternodes()))\nself.parent = dict(((node, None) for node in self.graph.iternodes()))\nself.dag = self.graph.__class__(self.graph.v(), directed=True)\nfor no... | <|body_start_0|>
self.graph = graph
self.color = dict(((node, 'WHITE') for node in self.graph.iternodes()))
self.distance = dict(((node, float('inf')) for node in self.graph.iternodes()))
self.parent = dict(((node, None) for node in self.graph.iternodes()))
self.dag = self.graph.... | Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >... | BFSWithQueue | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BFSWithQueue:
"""Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from grap... | stack_v2_sparse_classes_10k_train_005457 | 6,370 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None, pre_action=None, post_action=None)"
},
{
"docstring": "Explore the conn... | 4 | stack_v2_sparse_classes_30k_train_003094 | Implement the Python class `BFSWithQueue` described below.
Class description:
Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.str... | Implement the Python class `BFSWithQueue` described below.
Class description:
Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.str... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class BFSWithQueue:
"""Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from grap... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BFSWithQueue:
"""Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.struc... | the_stack_v2_python_sparse | graphtheory/traversing/bfs.py | kgashok/graphs-dict | train | 0 |
2f6ba4cc20176528312b371586d926ac57a78300 | [
"iter1 = iter(tt)\niter2 = iter(tt)\nself.assertEquals(lines[0], iter1.next())\nself.assertEquals(lines[0], iter2.next())\nself.assertEquals(lines[1], iter2.next())\nfor ix, line in enumerate(tt):\n self.assertEquals(lines[ix], line)\nfor i in xrange(len(tt)):\n self.assertEquals(lines[i], tt.GetInputs(i))\ns... | <|body_start_0|>
iter1 = iter(tt)
iter2 = iter(tt)
self.assertEquals(lines[0], iter1.next())
self.assertEquals(lines[0], iter2.next())
self.assertEquals(lines[1], iter2.next())
for ix, line in enumerate(tt):
self.assertEquals(lines[ix], line)
for i in ... | Test TruthTable functionality. | TruthTableTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TruthTableTest:
"""Test TruthTable functionality."""
def _TestTableSanity(self, tt, lines):
"""Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples)."""
<|body_0|>
def testTwoDimensi... | stack_v2_sparse_classes_10k_train_005458 | 9,390 | permissive | [
{
"docstring": "Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples).",
"name": "_TestTableSanity",
"signature": "def _TestTableSanity(self, tt, lines)"
},
{
"docstring": "Test TruthTable behavior for two b... | 3 | stack_v2_sparse_classes_30k_train_000174 | Implement the Python class `TruthTableTest` described below.
Class description:
Test TruthTable functionality.
Method signatures and docstrings:
- def _TestTableSanity(self, tt, lines): Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list ... | Implement the Python class `TruthTableTest` described below.
Class description:
Test TruthTable functionality.
Method signatures and docstrings:
- def _TestTableSanity(self, tt, lines): Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list ... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TruthTableTest:
"""Test TruthTable functionality."""
def _TestTableSanity(self, tt, lines):
"""Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples)."""
<|body_0|>
def testTwoDimensi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TruthTableTest:
"""Test TruthTable functionality."""
def _TestTableSanity(self, tt, lines):
"""Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples)."""
iter1 = iter(tt)
iter2 = iter(tt)
... | the_stack_v2_python_sparse | third_party/chromite/lib/cros_test_lib_unittest.py | metux/chromium-suckless | train | 5 |
4a5224aa4828debaa4142235558bf35b9e75e097 | [
"sdram = SDRAMResource(128 * 2 ** 20)\nself.assertEqual(sdram.get_value(), 128 * 2 ** 20)\nsdram = SDRAMResource(128 * 2 ** 19)\nself.assertEqual(sdram.get_value(), 128 * 2 ** 19)\nsdram = SDRAMResource(128 * 2 ** 21)\nself.assertEqual(sdram.get_value(), 128 * 2 ** 21)",
"dtcm = DTCMResource(128 * 2 ** 20)\nself.... | <|body_start_0|>
sdram = SDRAMResource(128 * 2 ** 20)
self.assertEqual(sdram.get_value(), 128 * 2 ** 20)
sdram = SDRAMResource(128 * 2 ** 19)
self.assertEqual(sdram.get_value(), 128 * 2 ** 19)
sdram = SDRAMResource(128 * 2 ** 21)
self.assertEqual(sdram.get_value(), 128 * ... | unit tests on the resources object | TestResourceModels | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestResourceModels:
"""unit tests on the resources object"""
def test_sdram(self):
"""test that adding a sdram resource to a resoruce container works correctly :return:"""
<|body_0|>
def test_dtcm(self):
"""test that adding a dtcm resource to a resoruce container... | stack_v2_sparse_classes_10k_train_005459 | 3,274 | no_license | [
{
"docstring": "test that adding a sdram resource to a resoruce container works correctly :return:",
"name": "test_sdram",
"signature": "def test_sdram(self)"
},
{
"docstring": "test that adding a dtcm resource to a resoruce container works correctly :return:",
"name": "test_dtcm",
"sign... | 4 | stack_v2_sparse_classes_30k_train_001580 | Implement the Python class `TestResourceModels` described below.
Class description:
unit tests on the resources object
Method signatures and docstrings:
- def test_sdram(self): test that adding a sdram resource to a resoruce container works correctly :return:
- def test_dtcm(self): test that adding a dtcm resource to... | Implement the Python class `TestResourceModels` described below.
Class description:
unit tests on the resources object
Method signatures and docstrings:
- def test_sdram(self): test that adding a sdram resource to a resoruce container works correctly :return:
- def test_dtcm(self): test that adding a dtcm resource to... | 5c2faba4d823e9341e5c18f61ea9bf8c6e15b687 | <|skeleton|>
class TestResourceModels:
"""unit tests on the resources object"""
def test_sdram(self):
"""test that adding a sdram resource to a resoruce container works correctly :return:"""
<|body_0|>
def test_dtcm(self):
"""test that adding a dtcm resource to a resoruce container... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestResourceModels:
"""unit tests on the resources object"""
def test_sdram(self):
"""test that adding a sdram resource to a resoruce container works correctly :return:"""
sdram = SDRAMResource(128 * 2 ** 20)
self.assertEqual(sdram.get_value(), 128 * 2 ** 20)
sdram = SDRAM... | the_stack_v2_python_sparse | unittests/model_tests/resources_tests/test_resources_model.py | kfriesth/PACMAN | train | 0 |
a09465adfa5927cc209244e1db8fa01f76b18081 | [
"company = self.env.company\nfor user in self:\n if user.branch_id and user.branch_id.company_id != company:\n raise exceptions.UserError(_(\"Sorry! The selected Branch does not belong to the current Company '%s'\", company.name))",
"if self.property_warehouse_id:\n return self.property_warehouse_id\... | <|body_start_0|>
company = self.env.company
for user in self:
if user.branch_id and user.branch_id.company_id != company:
raise exceptions.UserError(_("Sorry! The selected Branch does not belong to the current Company '%s'", company.name))
<|end_body_0|>
<|body_start_1|>
... | inherited res users | ResUsers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResUsers:
"""inherited res users"""
def branch_constrains(self):
"""branch constrains"""
<|body_0|>
def _get_default_warehouse_id(self):
"""methode to get default warehouse id"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
company = self.env.co... | stack_v2_sparse_classes_10k_train_005460 | 2,986 | no_license | [
{
"docstring": "branch constrains",
"name": "branch_constrains",
"signature": "def branch_constrains(self)"
},
{
"docstring": "methode to get default warehouse id",
"name": "_get_default_warehouse_id",
"signature": "def _get_default_warehouse_id(self)"
}
] | 2 | null | Implement the Python class `ResUsers` described below.
Class description:
inherited res users
Method signatures and docstrings:
- def branch_constrains(self): branch constrains
- def _get_default_warehouse_id(self): methode to get default warehouse id | Implement the Python class `ResUsers` described below.
Class description:
inherited res users
Method signatures and docstrings:
- def branch_constrains(self): branch constrains
- def _get_default_warehouse_id(self): methode to get default warehouse id
<|skeleton|>
class ResUsers:
"""inherited res users"""
d... | 4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14 | <|skeleton|>
class ResUsers:
"""inherited res users"""
def branch_constrains(self):
"""branch constrains"""
<|body_0|>
def _get_default_warehouse_id(self):
"""methode to get default warehouse id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResUsers:
"""inherited res users"""
def branch_constrains(self):
"""branch constrains"""
company = self.env.company
for user in self:
if user.branch_id and user.branch_id.company_id != company:
raise exceptions.UserError(_("Sorry! The selected Branch do... | the_stack_v2_python_sparse | multi_branch_base/models/branch_res_users.py | CybroOdoo/CybroAddons | train | 209 |
874dd371bffd0e9f338c22ecf963d9cb794a4d79 | [
"self.nb_dir = os.path.abspath(texinputs) if texinputs else ''\nself.ancestor_dirs = self.nb_dir.split('/')\nsuper().__init__(**kwargs)",
"if self.nb_dir:\n return applyJSONFilters([self.action], source)\nreturn source",
"if key == 'Image':\n attr, caption, [filename, typedef] = value\n if filename[:2]... | <|body_start_0|>
self.nb_dir = os.path.abspath(texinputs) if texinputs else ''
self.ancestor_dirs = self.nb_dir.split('/')
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if self.nb_dir:
return applyJSONFilters([self.action], source)
return source
<|end_bo... | A converter that handles relative path references. | ConvertExplicitlyRelativePaths | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertExplicitlyRelativePaths:
"""A converter that handles relative path references."""
def __init__(self, texinputs=None, **kwargs):
"""Initialize the converter."""
<|body_0|>
def __call__(self, source):
"""Invoke the converter."""
<|body_1|>
def a... | stack_v2_sparse_classes_10k_train_005461 | 2,786 | permissive | [
{
"docstring": "Initialize the converter.",
"name": "__init__",
"signature": "def __init__(self, texinputs=None, **kwargs)"
},
{
"docstring": "Invoke the converter.",
"name": "__call__",
"signature": "def __call__(self, source)"
},
{
"docstring": "Perform the action.",
"name"... | 3 | stack_v2_sparse_classes_30k_train_002845 | Implement the Python class `ConvertExplicitlyRelativePaths` described below.
Class description:
A converter that handles relative path references.
Method signatures and docstrings:
- def __init__(self, texinputs=None, **kwargs): Initialize the converter.
- def __call__(self, source): Invoke the converter.
- def actio... | Implement the Python class `ConvertExplicitlyRelativePaths` described below.
Class description:
A converter that handles relative path references.
Method signatures and docstrings:
- def __init__(self, texinputs=None, **kwargs): Initialize the converter.
- def __call__(self, source): Invoke the converter.
- def actio... | 51c6e0a7d40918366e2a68c5ea471fd2c65722cb | <|skeleton|>
class ConvertExplicitlyRelativePaths:
"""A converter that handles relative path references."""
def __init__(self, texinputs=None, **kwargs):
"""Initialize the converter."""
<|body_0|>
def __call__(self, source):
"""Invoke the converter."""
<|body_1|>
def a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConvertExplicitlyRelativePaths:
"""A converter that handles relative path references."""
def __init__(self, texinputs=None, **kwargs):
"""Initialize the converter."""
self.nb_dir = os.path.abspath(texinputs) if texinputs else ''
self.ancestor_dirs = self.nb_dir.split('/')
... | the_stack_v2_python_sparse | nbconvert/filters/pandoc.py | jupyter/nbconvert | train | 1,645 |
bdb86ce15529df916ceeb80ca00b34f2d6deb028 | [
"password1 = self.cleaned_data.get('password1')\npassword2 = self.cleaned_data.get('password2')\nif password1 and password2 and (password1 != password2):\n raise forms.ValidationError(\"Passwords don't match\")\nreturn password2",
"user = super(UserCreationForm, self).save(commit=False)\nuser.set_password(self... | <|body_start_0|>
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and (password1 != password2):
raise forms.ValidationError("Passwords don't match")
return password2
<|end_body_0|>
<|body_start_1|>
... | A form for creating new users. Includes all the required fields, plus a repeated password. | UserCreationForm | [
"CC-BY-SA-4.0",
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match"""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in ... | stack_v2_sparse_classes_10k_train_005462 | 2,893 | permissive | [
{
"docstring": "Check that the two password entries match",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Save the provided password in hashed format",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005471 | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match
- def save(self, commit=True): Save the ... | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match
- def save(self, commit=True): Save the ... | a60dbb43141210cc0950cc2e7490af1fd98b2ec0 | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match"""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match"""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2... | the_stack_v2_python_sparse | sitePjt/accounts/forms.py | returnturn/200OK | train | 0 |
6f57081234bf8bafac5407c33d554d30cf321321 | [
"if left > right:\n return 0\nelif right - left <= 1:\n return max(self.nums[left:right + 1])\n'memoization: 있으면 그거 return'\nif (left, right) in self.memo:\n return self.memo[left, right]\n'left(0)번째 집을 훔치는 경우'\ninclude_left = self.nums[left] + self.help(left + 2, right)\n'left(0)번째 집을 안 훔치는 경우'\nexclude_l... | <|body_start_0|>
if left > right:
return 0
elif right - left <= 1:
return max(self.nums[left:right + 1])
'memoization: 있으면 그거 return'
if (left, right) in self.memo:
return self.memo[left, right]
'left(0)번째 집을 훔치는 경우'
include_left = self... | nums에서 left부터 right까지의 부분을 놓고 봤을 때 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""nums에서 left부터 right까지의 부분을 놓고 봤을 때"""
def help(self, left, right):
"""base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much"""
... | stack_v2_sparse_classes_10k_train_005463 | 1,893 | no_license | [
{
"docstring": "base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much",
"name": "help",
"signature": "def help(self, left, right)"
},
{
"docstring": "예외 처리: 3개 ... | 2 | stack_v2_sparse_classes_30k_train_004574 | Implement the Python class `Solution` described below.
Class description:
nums에서 left부터 right까지의 부분을 놓고 봤을 때
Method signatures and docstrings:
- def help(self, left, right): base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐... | Implement the Python class `Solution` described below.
Class description:
nums에서 left부터 right까지의 부분을 놓고 봤을 때
Method signatures and docstrings:
- def help(self, left, right): base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐... | 9c29941e19b7dd2a2037b110dd6e16690e9a0cc2 | <|skeleton|>
class Solution:
"""nums에서 left부터 right까지의 부분을 놓고 봤을 때"""
def help(self, left, right):
"""base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""nums에서 left부터 right까지의 부분을 놓고 봤을 때"""
def help(self, left, right):
"""base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much"""
if left > rig... | the_stack_v2_python_sparse | algorithm/2022/0705_213_House_Robber_II/Wooseong.py | ai-kmu/etc | train | 3 |
4461b2eba907b9afb6292ad0ef79f692485cc5db | [
"super(RegressionTaskModel, self).__init__()\nmodel_type = model_config.get('model_type', 'transformer')\nhidden_size = model_config.get('hidden_size', 512)\nin_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size\nself.fc_decoder = nn.Sequential(nn.Linear(in_features=in_channels, out_features=hidden... | <|body_start_0|>
super(RegressionTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size
self.fc_decoder = nn.Sequential(nn.Lin... | RegressionTaskModel | RegressionTaskModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegressionTaskModel:
"""RegressionTaskModel"""
def __init__(self, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(RegressionTaskModel, self).... | stack_v2_sparse_classes_10k_train_005464 | 17,522 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, model_config, encoder_model)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, input, pos)"
}
] | 2 | null | Implement the Python class `RegressionTaskModel` described below.
Class description:
RegressionTaskModel
Method signatures and docstrings:
- def __init__(self, model_config, encoder_model): __init__
- def forward(self, input, pos): forward | Implement the Python class `RegressionTaskModel` described below.
Class description:
RegressionTaskModel
Method signatures and docstrings:
- def __init__(self, model_config, encoder_model): __init__
- def forward(self, input, pos): forward
<|skeleton|>
class RegressionTaskModel:
"""RegressionTaskModel"""
de... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class RegressionTaskModel:
"""RegressionTaskModel"""
def __init__(self, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegressionTaskModel:
"""RegressionTaskModel"""
def __init__(self, model_config, encoder_model):
"""__init__"""
super(RegressionTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
... | the_stack_v2_python_sparse | pahelix/model_zoo/protein_sequence_model.py | PaddlePaddle/PaddleHelix | train | 771 |
9689eeca03569387815b68344597f6e1c00654f0 | [
"super(InformationRatio, self).__init__()\nself.mtm = mtm\nself.benchmark = benchmark\npReturns = AnnualReturn(self.mtm)\nbReturns = AnnualReturn(self.benchmark)\nself.portfolioReturn = pReturns.getValue()\nself.benchmarkReturn = bReturns.getValue()\nvolatility = Volatility(self.mtm.shift() / self.mtm - self.benchm... | <|body_start_0|>
super(InformationRatio, self).__init__()
self.mtm = mtm
self.benchmark = benchmark
pReturns = AnnualReturn(self.mtm)
bReturns = AnnualReturn(self.benchmark)
self.portfolioReturn = pReturns.getValue()
self.benchmarkReturn = bReturns.getValue()
... | Information ratio of the data. | InformationRatio | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InformationRatio:
"""Information ratio of the data."""
def __init__(self, mtm, benchmark):
"""Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmar... | stack_v2_sparse_classes_10k_train_005465 | 10,010 | permissive | [
{
"docstring": "Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmark daily mark-to-market indexed by trading date as strings in the format %Y%m%d.",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_test_000303 | Implement the Python class `InformationRatio` described below.
Class description:
Information ratio of the data.
Method signatures and docstrings:
- def __init__(self, mtm, benchmark): Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings... | Implement the Python class `InformationRatio` described below.
Class description:
Information ratio of the data.
Method signatures and docstrings:
- def __init__(self, mtm, benchmark): Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings... | 139d604177da3855503643e0fcfa87711ba7e588 | <|skeleton|>
class InformationRatio:
"""Information ratio of the data."""
def __init__(self, mtm, benchmark):
"""Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InformationRatio:
"""Information ratio of the data."""
def __init__(self, mtm, benchmark):
"""Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmark daily mark-... | the_stack_v2_python_sparse | analytics/riskMeasurement/riskMetric.py | WinQuant/arsenal | train | 0 |
68947c9ca630bdad67c88ccd610cce695ed0ce28 | [
"self.channel_owner_vec = channel_owner_vec\nself.channel_type = channel_type\nself.create_new_channel = create_new_channel\nself.id = id\nself.name = name",
"if dictionary is None:\n return None\nchannel_owner_vec = None\nif dictionary.get('channelOwnerVec') != None:\n channel_owner_vec = list()\n for s... | <|body_start_0|>
self.channel_owner_vec = channel_owner_vec
self.channel_type = channel_type
self.create_new_channel = create_new_channel
self.id = id
self.name = name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
channel_owner_ve... | Implementation of the 'RestoreO365TeamsParams_TargetChannel' model. Target channel for teams granular restore to alternate loc. At least one of id or name must be specified. name must be specified if create_new_channel is true. Attributes: channel_owner_vec (list of EntityProto): Owners for the private channel. This is... | RestoreO365TeamsParams_TargetChannel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365TeamsParams_TargetChannel:
"""Implementation of the 'RestoreO365TeamsParams_TargetChannel' model. Target channel for teams granular restore to alternate loc. At least one of id or name must be specified. name must be specified if create_new_channel is true. Attributes: channel_owner_ve... | stack_v2_sparse_classes_10k_train_005466 | 2,919 | permissive | [
{
"docstring": "Constructor for the RestoreO365TeamsParams_TargetChannel class",
"name": "__init__",
"signature": "def __init__(self, channel_owner_vec=None, channel_type=None, create_new_channel=None, id=None, name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Ar... | 2 | null | Implement the Python class `RestoreO365TeamsParams_TargetChannel` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_TargetChannel' model. Target channel for teams granular restore to alternate loc. At least one of id or name must be specified. name must be specified if create_new_channe... | Implement the Python class `RestoreO365TeamsParams_TargetChannel` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_TargetChannel' model. Target channel for teams granular restore to alternate loc. At least one of id or name must be specified. name must be specified if create_new_channe... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365TeamsParams_TargetChannel:
"""Implementation of the 'RestoreO365TeamsParams_TargetChannel' model. Target channel for teams granular restore to alternate loc. At least one of id or name must be specified. name must be specified if create_new_channel is true. Attributes: channel_owner_ve... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreO365TeamsParams_TargetChannel:
"""Implementation of the 'RestoreO365TeamsParams_TargetChannel' model. Target channel for teams granular restore to alternate loc. At least one of id or name must be specified. name must be specified if create_new_channel is true. Attributes: channel_owner_vec (list of En... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_teams_params_target_channel.py | cohesity/management-sdk-python | train | 24 |
86438f7e8f37ab524c52b50d5a8c93cdcd5d502e | [
"test_directory = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集'\nfiles_list = get_all_files_path_with_fix(test_directory, ['mp4', 'mp3'])\ntest_file1 = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集/[Dymy][Shingeki no Kyojin][17][BIG5][1280X720].mp4'\nself.assertIn(test_file1, files_list)\ntest_file2 = '/Users/L1n/De... | <|body_start_0|>
test_directory = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集'
files_list = get_all_files_path_with_fix(test_directory, ['mp4', 'mp3'])
test_file1 = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集/[Dymy][Shingeki no Kyojin][17][BIG5][1280X720].mp4'
self.assertIn(test_file1,... | TestGetRightFileInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetRightFileInfo:
def test_get_all_files_path(self):
"""测试是否能获取到指定路径下的所有指定后缀的文件 :return:"""
<|body_0|>
def test_open_a_file_with_right_app(self):
"""测试是否能够正确打开一个文件 :return:"""
<|body_1|>
def test_random_choice(self):
"""测试是否能够实现随机选择功能 :return... | stack_v2_sparse_classes_10k_train_005467 | 2,710 | no_license | [
{
"docstring": "测试是否能获取到指定路径下的所有指定后缀的文件 :return:",
"name": "test_get_all_files_path",
"signature": "def test_get_all_files_path(self)"
},
{
"docstring": "测试是否能够正确打开一个文件 :return:",
"name": "test_open_a_file_with_right_app",
"signature": "def test_open_a_file_with_right_app(self)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_001030 | Implement the Python class `TestGetRightFileInfo` described below.
Class description:
Implement the TestGetRightFileInfo class.
Method signatures and docstrings:
- def test_get_all_files_path(self): 测试是否能获取到指定路径下的所有指定后缀的文件 :return:
- def test_open_a_file_with_right_app(self): 测试是否能够正确打开一个文件 :return:
- def test_random... | Implement the Python class `TestGetRightFileInfo` described below.
Class description:
Implement the TestGetRightFileInfo class.
Method signatures and docstrings:
- def test_get_all_files_path(self): 测试是否能获取到指定路径下的所有指定后缀的文件 :return:
- def test_open_a_file_with_right_app(self): 测试是否能够正确打开一个文件 :return:
- def test_random... | 73022b40d26ad09051329ae7ff8aae7201d8de6d | <|skeleton|>
class TestGetRightFileInfo:
def test_get_all_files_path(self):
"""测试是否能获取到指定路径下的所有指定后缀的文件 :return:"""
<|body_0|>
def test_open_a_file_with_right_app(self):
"""测试是否能够正确打开一个文件 :return:"""
<|body_1|>
def test_random_choice(self):
"""测试是否能够实现随机选择功能 :return... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestGetRightFileInfo:
def test_get_all_files_path(self):
"""测试是否能获取到指定路径下的所有指定后缀的文件 :return:"""
test_directory = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集'
files_list = get_all_files_path_with_fix(test_directory, ['mp4', 'mp3'])
test_file1 = '/Users/L1n/Desktop/Entertainment... | the_stack_v2_python_sparse | 随机选择器/test_my_random_choicer.py | L1nwatch/Mac-Python-3.X | train | 10 | |
8b2fe18a12eafa35398360f6e569a220e3450582 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ItemActivityStat()",
"from .entity import Entity\nfrom .incomplete_data import IncompleteData\nfrom .item_action_stat import ItemActionStat\nfrom .item_activity import ItemActivity\nfrom .entity import Entity\nfrom .incomplete_data imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ItemActivityStat()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .incomplete_data import IncompleteData
from .item_action_stat import ItemActionStat
fro... | ItemActivityStat | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemActivityStat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_10k_train_005468 | 4,958 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ItemActivityStat",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | null | Implement the Python class `ItemActivityStat` described below.
Class description:
Implement the ItemActivityStat class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ItemActivityStat` described below.
Class description:
Implement the ItemActivityStat class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ItemActivityStat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ItemActivityStat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ItemAc... | the_stack_v2_python_sparse | msgraph/generated/models/item_activity_stat.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
6a930c8a1353c5becbaa2a1cf78191bacd40dd5c | [
"cur = head\na = []\nwhile cur:\n a.append(cur.val)\n cur = cur.next\nfor i in range(len(a)):\n if a[i] != a[len(a) - 1 - i]:\n return False\nreturn True",
"if not head.next:\n return True\ndummy = ListNode()\ndummy.next = head\none, two = (dummy, dummy)\nwhile two and two.next:\n one = one.... | <|body_start_0|>
cur = head
a = []
while cur:
a.append(cur.val)
cur = cur.next
for i in range(len(a)):
if a[i] != a[len(a) - 1 - i]:
return False
return True
<|end_body_0|>
<|body_start_1|>
if not head.next:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교"""
<|body_0|>
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(1) Solution ... | stack_v2_sparse_classes_10k_train_005469 | 2,407 | no_license | [
{
"docstring": "Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head: ListNode) -> bool"
},
{
"docstring": "Time Complexity : O(N), Space Complexity : O(1) Solution : 아래 방식과 동일한데 절반 위치를 구하고 리스트를 분리... | 3 | stack_v2_sparse_classes_30k_train_004393 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교
- def isPalindrome(self, head: ListNode) -> bo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교
- def isPalindrome(self, head: ListNode) -> bo... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교"""
<|body_0|>
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(1) Solution ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교"""
cur = head
a = []
while cur:
a.append(cur.val)
cur = cur.next
for i in range(len(a)):
... | the_stack_v2_python_sparse | Leetcode/Palindrome_Linked_List.py | hanwgyu/algorithm_problem_solving | train | 5 | |
2b359d6db42ad1456a284127373bd437ce5f25cb | [
"with self._lock:\n if not self._done:\n self._Print('.')\nreturn self._done",
"if self._spinner_only or not self._output_enabled:\n return\ndisplay_message = self._GetPrefix()\nself._stream.write(message or display_message + '\\n')\nreturn"
] | <|body_start_0|>
with self._lock:
if not self._done:
self._Print('.')
return self._done
<|end_body_0|>
<|body_start_1|>
if self._spinner_only or not self._output_enabled:
return
display_message = self._GetPrefix()
self._stream.write(messag... | A context manager for telling the user about long-running progress. | _NonInteractiveProgressTracker | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _NonInteractiveProgressTracker:
"""A context manager for telling the user about long-running progress."""
def Tick(self):
"""Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether ... | stack_v2_sparse_classes_10k_train_005470 | 47,411 | permissive | [
{
"docstring": "Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether progress has completed.",
"name": "Tick",
"signature": "def Tick(self)"
},
{
"docstring": "Reprints the prefix followed b... | 2 | null | Implement the Python class `_NonInteractiveProgressTracker` described below.
Class description:
A context manager for telling the user about long-running progress.
Method signatures and docstrings:
- def Tick(self): Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. N... | Implement the Python class `_NonInteractiveProgressTracker` described below.
Class description:
A context manager for telling the user about long-running progress.
Method signatures and docstrings:
- def Tick(self): Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. N... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class _NonInteractiveProgressTracker:
"""A context manager for telling the user about long-running progress."""
def Tick(self):
"""Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _NonInteractiveProgressTracker:
"""A context manager for telling the user about long-running progress."""
def Tick(self):
"""Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether progress has ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/core/console/progress_tracker.py | bopopescu/socialliteapp | train | 0 |
b4dc1fcdd1aad4db485cb445eabea1fd477eedfb | [
"input_spec = TensorSpec((10,), torch.float32)\nembedding = input_spec.ones(outer_dims=(1,))\nnet = OnehotCategoricalProjectionNetwork(input_size=input_spec.shape[0], mode=mode, action_spec=BoundedTensorSpec((1,), minimum=0, maximum=4), logits_init_output_factor=0)\ndist, _ = net(embedding)\nself.assertTrue(isinsta... | <|body_start_0|>
input_spec = TensorSpec((10,), torch.float32)
embedding = input_spec.ones(outer_dims=(1,))
net = OnehotCategoricalProjectionNetwork(input_size=input_spec.shape[0], mode=mode, action_spec=BoundedTensorSpec((1,), minimum=0, maximum=4), logits_init_output_factor=0)
dist, _ ... | TestOnehotCategoricalProjectionNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOnehotCategoricalProjectionNetwork:
def test_onehot_categorical_uniform_projection_net(self, mode):
"""A zero-weight net generates uniform actions."""
<|body_0|>
def test_onehot_samples(self, mode):
"""Samples from the projection net are onehot vectors."""
... | stack_v2_sparse_classes_10k_train_005471 | 19,986 | permissive | [
{
"docstring": "A zero-weight net generates uniform actions.",
"name": "test_onehot_categorical_uniform_projection_net",
"signature": "def test_onehot_categorical_uniform_projection_net(self, mode)"
},
{
"docstring": "Samples from the projection net are onehot vectors.",
"name": "test_onehot... | 4 | null | Implement the Python class `TestOnehotCategoricalProjectionNetwork` described below.
Class description:
Implement the TestOnehotCategoricalProjectionNetwork class.
Method signatures and docstrings:
- def test_onehot_categorical_uniform_projection_net(self, mode): A zero-weight net generates uniform actions.
- def tes... | Implement the Python class `TestOnehotCategoricalProjectionNetwork` described below.
Class description:
Implement the TestOnehotCategoricalProjectionNetwork class.
Method signatures and docstrings:
- def test_onehot_categorical_uniform_projection_net(self, mode): A zero-weight net generates uniform actions.
- def tes... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class TestOnehotCategoricalProjectionNetwork:
def test_onehot_categorical_uniform_projection_net(self, mode):
"""A zero-weight net generates uniform actions."""
<|body_0|>
def test_onehot_samples(self, mode):
"""Samples from the projection net are onehot vectors."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestOnehotCategoricalProjectionNetwork:
def test_onehot_categorical_uniform_projection_net(self, mode):
"""A zero-weight net generates uniform actions."""
input_spec = TensorSpec((10,), torch.float32)
embedding = input_spec.ones(outer_dims=(1,))
net = OnehotCategoricalProjectio... | the_stack_v2_python_sparse | alf/networks/projection_networks_test.py | HorizonRobotics/alf | train | 288 | |
f352fa80db460ea3dbed7405e7f6cad9bbb12c58 | [
"from scoop.editorial.models import Excerpt\nidentifier = self.value\ntry:\n excerpt = Excerpt.objects.get(name=identifier)\nexcept Excerpt.DoesNotExist:\n excerpt = None\nreturn {'excerpt': excerpt}",
"base = super(ExcerptInline, self).get_template_name()[0]\npath = 'editorial/%s' % base\nreturn path"
] | <|body_start_0|>
from scoop.editorial.models import Excerpt
identifier = self.value
try:
excerpt = Excerpt.objects.get(name=identifier)
except Excerpt.DoesNotExist:
excerpt = None
return {'excerpt': excerpt}
<|end_body_0|>
<|body_start_1|>
base = ... | Inline d'extrait | ExcerptInline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcerptInline:
"""Inline d'extrait"""
def get_context(self):
"""Renvoyer le contexte d'affichage du template"""
<|body_0|>
def get_template_name(self):
"""Renvoyer le chemin du template d'affichage"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005472 | 875 | no_license | [
{
"docstring": "Renvoyer le contexte d'affichage du template",
"name": "get_context",
"signature": "def get_context(self)"
},
{
"docstring": "Renvoyer le chemin du template d'affichage",
"name": "get_template_name",
"signature": "def get_template_name(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002912 | Implement the Python class `ExcerptInline` described below.
Class description:
Inline d'extrait
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte d'affichage du template
- def get_template_name(self): Renvoyer le chemin du template d'affichage | Implement the Python class `ExcerptInline` described below.
Class description:
Inline d'extrait
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte d'affichage du template
- def get_template_name(self): Renvoyer le chemin du template d'affichage
<|skeleton|>
class ExcerptInline:
"""In... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class ExcerptInline:
"""Inline d'extrait"""
def get_context(self):
"""Renvoyer le contexte d'affichage du template"""
<|body_0|>
def get_template_name(self):
"""Renvoyer le chemin du template d'affichage"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExcerptInline:
"""Inline d'extrait"""
def get_context(self):
"""Renvoyer le contexte d'affichage du template"""
from scoop.editorial.models import Excerpt
identifier = self.value
try:
excerpt = Excerpt.objects.get(name=identifier)
except Excerpt.DoesNot... | the_stack_v2_python_sparse | scoop/editorial/util/inlines.py | artscoop/scoop | train | 0 |
93d687b7ec9a79d1c8525ceabb979b9dbe821a05 | [
"self.file_name = ''\nself.urls = []\nself.rev = None\nself.hashes = {}\nself.acl = []\nself._metadata = {}\nself.size = None\nself.merge_indexd()",
"urls = []\nfor url in self.urls:\n if url.startswith('s3://'):\n url = f\"{current_app.config['GEN3_URL']}/data/{self.latest_did}\"\n urls.append(url)\... | <|body_start_0|>
self.file_name = ''
self.urls = []
self.rev = None
self.hashes = {}
self.acl = []
self._metadata = {}
self.size = None
self.merge_indexd()
<|end_body_0|>
<|body_start_1|>
urls = []
for url in self.urls:
if url.... | Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the file, a response containing a did (dig... | IndexdFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexdFile:
"""Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the ... | stack_v2_sparse_classes_10k_train_005473 | 7,013 | permissive | [
{
"docstring": "Builds the object by initializing properties and updating them from indexd.",
"name": "constructor",
"signature": "def constructor(self)"
},
{
"docstring": "Access urls should contain only links out to gen3 data endpoints that are used to download the files themselves. For urls t... | 3 | stack_v2_sparse_classes_30k_train_000489 | Implement the Python class `IndexdFile` described below.
Class description:
Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the se... | Implement the Python class `IndexdFile` described below.
Class description:
Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the se... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class IndexdFile:
"""Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IndexdFile:
"""Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the file, a respo... | the_stack_v2_python_sparse | dataservice/api/common/model.py | kids-first/kf-api-dataservice | train | 9 |
1e66cd3ea73f9ececd888f48b045a028d5899388 | [
"if not root:\n return ''\ns = []\nunique_id = 0\nd = {}\n\ndef trav(cur):\n nonlocal unique_id\n if not cur:\n return\n unique_id += 1\n copy_uid = unique_id\n d[str(unique_id)] = str(cur.val)\n for nxt in cur.children:\n nxt_uid = trav(nxt)\n s.append(f'{(copy_uid, nxt_ui... | <|body_start_0|>
if not root:
return ''
s = []
unique_id = 0
d = {}
def trav(cur):
nonlocal unique_id
if not cur:
return
unique_id += 1
copy_uid = unique_id
d[str(unique_id)] = str(cur.val)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_005474 | 2,190 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 96e086d4ee6169c0f83fff3819f38f32b8f17c98 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
s = []
unique_id = 0
d = {}
def trav(cur):
nonlocal unique_id
if not cur:
... | the_stack_v2_python_sparse | leetcode/428. Serialize and Deserialize N-ary Tree.py | DeshErBojhaa/sports_programming | train | 1 | |
a5428b1a799611dac61e81dbc7ee2f8a16a80f57 | [
"queryset = super().get_queryset().select_related('part')\nqueryset = build.serializers.BuildSerializer.annotate_queryset(queryset)\nreturn queryset",
"dataset = build.admin.BuildResource().export(queryset=queryset)\nfiledata = dataset.export(export_format)\nfilename = f'InvenTree_BuildOrders.{export_format}'\nre... | <|body_start_0|>
queryset = super().get_queryset().select_related('part')
queryset = build.serializers.BuildSerializer.annotate_queryset(queryset)
return queryset
<|end_body_0|>
<|body_start_1|>
dataset = build.admin.BuildResource().export(queryset=queryset)
filedata = dataset.e... | API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object | BuildList | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildList:
"""API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object"""
def get_queryset(self):
"""Override the queryset filtering, as some of the fields don't natively play nicely with DRF."""
<|body... | stack_v2_sparse_classes_10k_train_005475 | 20,912 | permissive | [
{
"docstring": "Override the queryset filtering, as some of the fields don't natively play nicely with DRF.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Download the queryset data as a file.",
"name": "download_queryset",
"signature": "def download_q... | 4 | null | Implement the Python class `BuildList` described below.
Class description:
API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object
Method signatures and docstrings:
- def get_queryset(self): Override the queryset filtering, as some of the fiel... | Implement the Python class `BuildList` described below.
Class description:
API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object
Method signatures and docstrings:
- def get_queryset(self): Override the queryset filtering, as some of the fiel... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class BuildList:
"""API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object"""
def get_queryset(self):
"""Override the queryset filtering, as some of the fields don't natively play nicely with DRF."""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BuildList:
"""API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object"""
def get_queryset(self):
"""Override the queryset filtering, as some of the fields don't natively play nicely with DRF."""
queryset = super().... | the_stack_v2_python_sparse | InvenTree/build/api.py | inventree/InvenTree | train | 3,077 |
55d72c67ad38d7dae4f05c6d1cb7e56ae730e236 | [
"v0 = Vertex()\nself.assertIsNot(v0, None)\nself.assertIsInstance(v0, Vertex)",
"v0 = Vertex([1])\nself.assertIsNot(v0, None)\nself.assertIsInstance(v0, Vertex)\nv1 = Vertex([1, 2, 3])\nself.assertIsNot(v1, None)\nself.assertIsInstance(v1, Vertex)\nself.assertIsInstance(v1.coordinates(), Coordinates)\nv2 = Vertex... | <|body_start_0|>
v0 = Vertex()
self.assertIsNot(v0, None)
self.assertIsInstance(v0, Vertex)
<|end_body_0|>
<|body_start_1|>
v0 = Vertex([1])
self.assertIsNot(v0, None)
self.assertIsInstance(v0, Vertex)
v1 = Vertex([1, 2, 3])
self.assertIsNot(v1, None)
... | Test Vertex class calls | TestConstructor_Vertex | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConstructor_Vertex:
"""Test Vertex class calls"""
def test_none(self):
"""Calling Vertex class with no key (key = None)"""
<|body_0|>
def test_iterable_simple(self):
"""Calling Vertex class with key containing simple types"""
<|body_1|>
def test_... | stack_v2_sparse_classes_10k_train_005476 | 6,423 | permissive | [
{
"docstring": "Calling Vertex class with no key (key = None)",
"name": "test_none",
"signature": "def test_none(self)"
},
{
"docstring": "Calling Vertex class with key containing simple types",
"name": "test_iterable_simple",
"signature": "def test_iterable_simple(self)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_val_000012 | Implement the Python class `TestConstructor_Vertex` described below.
Class description:
Test Vertex class calls
Method signatures and docstrings:
- def test_none(self): Calling Vertex class with no key (key = None)
- def test_iterable_simple(self): Calling Vertex class with key containing simple types
- def test_iter... | Implement the Python class `TestConstructor_Vertex` described below.
Class description:
Test Vertex class calls
Method signatures and docstrings:
- def test_none(self): Calling Vertex class with no key (key = None)
- def test_iterable_simple(self): Calling Vertex class with key containing simple types
- def test_iter... | f9b00a39bc16aea4abac60c0dd0aab2acac5adcf | <|skeleton|>
class TestConstructor_Vertex:
"""Test Vertex class calls"""
def test_none(self):
"""Calling Vertex class with no key (key = None)"""
<|body_0|>
def test_iterable_simple(self):
"""Calling Vertex class with key containing simple types"""
<|body_1|>
def test_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestConstructor_Vertex:
"""Test Vertex class calls"""
def test_none(self):
"""Calling Vertex class with no key (key = None)"""
v0 = Vertex()
self.assertIsNot(v0, None)
self.assertIsInstance(v0, Vertex)
def test_iterable_simple(self):
"""Calling Vertex class wi... | the_stack_v2_python_sparse | _BACKUPS_v3/v3_1/LightPicture_Test.py | nagame/LightPicture | train | 0 |
af38cf309f51c557e607a85e57ec13d720223470 | [
"super().__init__(env)\nself._time_delta = 0.1\nself._speed_max = 22.22\nself._dist_max = self._speed_max * self._time_delta",
"limited_actions: Dict[str, np.ndarray] = {}\nfor agent_name, agent_action in action.items():\n limited_actions[agent_name] = self._limit(name=agent_name, action=agent_action)\nout = s... | <|body_start_0|>
super().__init__(env)
self._time_delta = 0.1
self._speed_max = 22.22
self._dist_max = self._speed_max * self._time_delta
<|end_body_0|>
<|body_start_1|>
limited_actions: Dict[str, np.ndarray] = {}
for agent_name, agent_action in action.items():
... | Limits the delta-x and delta-y in the RelativeTargetPose action space. | LimitRelativeTargetPose | [
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"CC-BY-NC-4.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-generic-exception",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"BSD-3-Clause",
"MIT",
"LGPL-... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimitRelativeTargetPose:
"""Limits the delta-x and delta-y in the RelativeTargetPose action space."""
def __init__(self, env: gym.Env):
"""Args: env (gym.Env): Environment to be wrapped."""
<|body_0|>
def step(self, action: Dict[str, np.ndarray]) -> Tuple[Dict[str, Any],... | stack_v2_sparse_classes_10k_train_005477 | 3,732 | permissive | [
{
"docstring": "Args: env (gym.Env): Environment to be wrapped.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env)"
},
{
"docstring": "Steps the environment. Args: action (Dict[str, np.ndarray]): Action for each agent. Returns: Tuple[ Dict[str, Any], Dict[str, float], Dict[str,... | 3 | null | Implement the Python class `LimitRelativeTargetPose` described below.
Class description:
Limits the delta-x and delta-y in the RelativeTargetPose action space.
Method signatures and docstrings:
- def __init__(self, env: gym.Env): Args: env (gym.Env): Environment to be wrapped.
- def step(self, action: Dict[str, np.nd... | Implement the Python class `LimitRelativeTargetPose` described below.
Class description:
Limits the delta-x and delta-y in the RelativeTargetPose action space.
Method signatures and docstrings:
- def __init__(self, env: gym.Env): Args: env (gym.Env): Environment to be wrapped.
- def step(self, action: Dict[str, np.nd... | 2ae8bd76a0b6e4da5699629cec0fefa5aa47ce67 | <|skeleton|>
class LimitRelativeTargetPose:
"""Limits the delta-x and delta-y in the RelativeTargetPose action space."""
def __init__(self, env: gym.Env):
"""Args: env (gym.Env): Environment to be wrapped."""
<|body_0|>
def step(self, action: Dict[str, np.ndarray]) -> Tuple[Dict[str, Any],... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LimitRelativeTargetPose:
"""Limits the delta-x and delta-y in the RelativeTargetPose action space."""
def __init__(self, env: gym.Env):
"""Args: env (gym.Env): Environment to be wrapped."""
super().__init__(env)
self._time_delta = 0.1
self._speed_max = 22.22
self._... | the_stack_v2_python_sparse | smarts/env/gymnasium/wrappers/limit_relative_target_pose.py | huawei-noah/SMARTS | train | 824 |
f7b5876a13b8c3f8070c3d0b377e62ad5bb28098 | [
"self.total_offers = total_offers\nself.total_offer_pages = total_offer_pages\nself.more_offers_url = more_offers_url\nself.offer = offer",
"if dictionary is None:\n return None\ntotal_offers = dictionary.get('TotalOffers')\ntotal_offer_pages = dictionary.get('TotalOfferPages')\nmore_offers_url = dictionary.ge... | <|body_start_0|>
self.total_offers = total_offers
self.total_offer_pages = total_offer_pages
self.more_offers_url = more_offers_url
self.offer = offer
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
total_offers = dictionary.get('TotalOffer... | Implementation of the 'Offers' model. TODO: type model description here. Attributes: total_offers (int): TODO: type description here. total_offer_pages (int): TODO: type description here. more_offers_url (string): TODO: type description here. offer (list of Offer): TODO: type description here. | Offers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Offers:
"""Implementation of the 'Offers' model. TODO: type model description here. Attributes: total_offers (int): TODO: type description here. total_offer_pages (int): TODO: type description here. more_offers_url (string): TODO: type description here. offer (list of Offer): TODO: type descripti... | stack_v2_sparse_classes_10k_train_005478 | 2,403 | permissive | [
{
"docstring": "Constructor for the Offers class",
"name": "__init__",
"signature": "def __init__(self, total_offers=None, total_offer_pages=None, more_offers_url=None, offer=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary... | 2 | stack_v2_sparse_classes_30k_train_000748 | Implement the Python class `Offers` described below.
Class description:
Implementation of the 'Offers' model. TODO: type model description here. Attributes: total_offers (int): TODO: type description here. total_offer_pages (int): TODO: type description here. more_offers_url (string): TODO: type description here. offe... | Implement the Python class `Offers` described below.
Class description:
Implementation of the 'Offers' model. TODO: type model description here. Attributes: total_offers (int): TODO: type description here. total_offer_pages (int): TODO: type description here. more_offers_url (string): TODO: type description here. offe... | 26ea1019115a1de3b1b37a4b830525e164ac55ce | <|skeleton|>
class Offers:
"""Implementation of the 'Offers' model. TODO: type model description here. Attributes: total_offers (int): TODO: type description here. total_offer_pages (int): TODO: type description here. more_offers_url (string): TODO: type description here. offer (list of Offer): TODO: type descripti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Offers:
"""Implementation of the 'Offers' model. TODO: type model description here. Attributes: total_offers (int): TODO: type description here. total_offer_pages (int): TODO: type description here. more_offers_url (string): TODO: type description here. offer (list of Offer): TODO: type description here."""
... | the_stack_v2_python_sparse | awsecommerceservice/models/offers.py | nidaizamir/Test-PY | train | 0 |
53510848269c9f1f2d9c631f9de8e5cf99e962ac | [
"super(UploaderThread, self).__init__(parent, **kwargs)\nself._snapshot = snapshot\nself._output = {'urls': dict()}",
"self._log.write('<h1>Beginning Uploads...</h1>')\nprojectData = FlexProjectData(**self._snapshot)\nfor pid, active in self._snapshot['platforms'].iteritems():\n if not active or pid in self._s... | <|body_start_0|>
super(UploaderThread, self).__init__(parent, **kwargs)
self._snapshot = snapshot
self._output = {'urls': dict()}
<|end_body_0|>
<|body_start_1|>
self._log.write('<h1>Beginning Uploads...</h1>')
projectData = FlexProjectData(**self._snapshot)
for pid, act... | A class for... | UploaderThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploaderThread:
"""A class for..."""
def __init__(self, parent, snapshot, **kwargs):
"""Creates a new instance of UploaderThread."""
<|body_0|>
def _runImpl(self):
"""Doc..."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(UploaderThread, s... | stack_v2_sparse_classes_10k_train_005479 | 2,791 | no_license | [
{
"docstring": "Creates a new instance of UploaderThread.",
"name": "__init__",
"signature": "def __init__(self, parent, snapshot, **kwargs)"
},
{
"docstring": "Doc...",
"name": "_runImpl",
"signature": "def _runImpl(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004095 | Implement the Python class `UploaderThread` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, parent, snapshot, **kwargs): Creates a new instance of UploaderThread.
- def _runImpl(self): Doc... | Implement the Python class `UploaderThread` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, parent, snapshot, **kwargs): Creates a new instance of UploaderThread.
- def _runImpl(self): Doc...
<|skeleton|>
class UploaderThread:
"""A class for..."""
de... | 36ffb0fd1ef2e86c1b67feb61fd744f508b13c74 | <|skeleton|>
class UploaderThread:
"""A class for..."""
def __init__(self, parent, snapshot, **kwargs):
"""Creates a new instance of UploaderThread."""
<|body_0|>
def _runImpl(self):
"""Doc..."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UploaderThread:
"""A class for..."""
def __init__(self, parent, snapshot, **kwargs):
"""Creates a new instance of UploaderThread."""
super(UploaderThread, self).__init__(parent, **kwargs)
self._snapshot = snapshot
self._output = {'urls': dict()}
def _runImpl(self):
... | the_stack_v2_python_sparse | src/CompilerDeck/deploy/UploaderThread.py | sernst/CompilerDeck | train | 0 |
30fb8651d31439ce3ecb27f1ff145e505262f949 | [
"if not root:\n self.stack = []\n return\nself.stack = [root]\np = root\nwhile self.stack and self.stack[-1].left:\n self.stack.append(self.stack[-1].left)",
"popNode = self.stack.pop()\nif popNode.right:\n self.stack.append(popNode.right)\n while self.stack and self.stack[-1].left:\n self.s... | <|body_start_0|>
if not root:
self.stack = []
return
self.stack = [root]
p = root
while self.stack and self.stack[-1].left:
self.stack.append(self.stack[-1].left)
<|end_body_0|>
<|body_start_1|>
popNode = self.stack.pop()
if popNode.ri... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def next(self):
"""@return the next smallest number :rtype: int"""
<|body_1|>
def hasNext(self):
"""@return whether we have a next smallest number :rtype: bool"""
... | stack_v2_sparse_classes_10k_train_005480 | 1,317 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": "@return the next smallest number :rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": "@return whether we have a next smallest number :rt... | 3 | null | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def next(self): @return the next smallest number :rtype: int
- def hasNext(self): @return whether we have a next smallest n... | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def next(self): @return the next smallest number :rtype: int
- def hasNext(self): @return whether we have a next smallest n... | 1d8821da01c9c200732a6b7037b8631689e2f7e7 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def next(self):
"""@return the next smallest number :rtype: int"""
<|body_1|>
def hasNext(self):
"""@return whether we have a next smallest number :rtype: bool"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
if not root:
self.stack = []
return
self.stack = [root]
p = root
while self.stack and self.stack[-1].left:
self.stack.append(self.stack[-1].left)
def next(self):
... | the_stack_v2_python_sparse | Leetcode0173_InorderWithStack.py | xiaojinghu/Leetcode | train | 0 | |
5fd84ee1516a9cee0ef615fcf765a694833c913f | [
"self.count = 0\nself.index = []\nself.elem = dict()",
"if val not in self.elem:\n self.elem[val] = self.count\n self.index.append(val)\n self.count += 1\n return True\nelse:\n return False",
"if val not in self.elem:\n return False\nelse:\n ind = self.elem[val]\n self.elem.pop(val)\n ... | <|body_start_0|>
self.count = 0
self.index = []
self.elem = dict()
<|end_body_0|>
<|body_start_1|>
if val not in self.elem:
self.elem[val] = self.count
self.index.append(val)
self.count += 1
return True
else:
return Fal... | RandomizedSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_10k_train_005481 | 1,538 | permissive | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element.",
"name": "insert",
"signature": "def insert(self, val: int) ... | 4 | null | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | 84c229eaf5a2e617ca00cabed04dd76d508d60b8 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.count = 0
self.index = []
self.elem = dict()
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element.... | the_stack_v2_python_sparse | Code/py3/380.常数时间插入、删除和获取随机元素.py | ApocalypseMac/LeetCode | train | 1 | |
4964700ea5197f22120395e7b21236604fdc4b30 | [
"status = None\nuser = self.context['request'].user\nurl = validated_data.get('url')\ngame_record_file = validated_data.get('game_record_file')\nif game_record_file:\n status = 'file'\nelif url:\n status = 'url'\nif status is None:\n raise serializers.ValidationError('Status must be url or file')\nreturn m... | <|body_start_0|>
status = None
user = self.context['request'].user
url = validated_data.get('url')
game_record_file = validated_data.get('game_record_file')
if game_record_file:
status = 'file'
elif url:
status = 'url'
if status is None:
... | serializers to handle file object and help with extracting data | GomokuRecordFileSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GomokuRecordFileSerializer:
"""serializers to handle file object and help with extracting data"""
def create(self, validated_data):
"""Creating GameRecordFile object"""
<|body_0|>
def validate_game_record_file(self, attrs):
"""File validation"""
<|body_1|... | stack_v2_sparse_classes_10k_train_005482 | 1,763 | no_license | [
{
"docstring": "Creating GameRecordFile object",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "File validation",
"name": "validate_game_record_file",
"signature": "def validate_game_record_file(self, attrs)"
},
{
"docstring": "File validatio... | 3 | stack_v2_sparse_classes_30k_train_006996 | Implement the Python class `GomokuRecordFileSerializer` described below.
Class description:
serializers to handle file object and help with extracting data
Method signatures and docstrings:
- def create(self, validated_data): Creating GameRecordFile object
- def validate_game_record_file(self, attrs): File validation... | Implement the Python class `GomokuRecordFileSerializer` described below.
Class description:
serializers to handle file object and help with extracting data
Method signatures and docstrings:
- def create(self, validated_data): Creating GameRecordFile object
- def validate_game_record_file(self, attrs): File validation... | 4ce3e6813e16ecaf0a118e0cc5548a091aa97646 | <|skeleton|>
class GomokuRecordFileSerializer:
"""serializers to handle file object and help with extracting data"""
def create(self, validated_data):
"""Creating GameRecordFile object"""
<|body_0|>
def validate_game_record_file(self, attrs):
"""File validation"""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GomokuRecordFileSerializer:
"""serializers to handle file object and help with extracting data"""
def create(self, validated_data):
"""Creating GameRecordFile object"""
status = None
user = self.context['request'].user
url = validated_data.get('url')
game_record_fi... | the_stack_v2_python_sparse | src/gomoku_file_app/api/serializers.py | adam-harmasz/gomoku_v_0_2 | train | 0 |
ca1ec382ef5b4d9b5d14cece87aa3612a3e39ab9 | [
"m = defaultdict(list)\nfor i, v in enumerate(nums):\n m[v].append(i)\nfor v in nums:\n try:\n x = m[v].pop()\n y = m[target - v].pop()\n return sorted([x, y])\n except:\n pass",
"lookup = {}\nfor i, num in enumerate(nums):\n if target - num in lookup:\n return [look... | <|body_start_0|>
m = defaultdict(list)
for i, v in enumerate(nums):
m[v].append(i)
for v in nums:
try:
x = m[v].pop()
y = m[target - v].pop()
return sorted([x, y])
except:
pass
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_005483 | 806 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
m = defaultdict(list)
for i, v in enumerate(nums):
m[v].append(i)
for v in nums:
try:
x = m[v].pop()
y = m[target ... | the_stack_v2_python_sparse | two-sum/solution.py | uxlsl/leetcode_practice | train | 0 | |
33b9cdb7c8a8d0a9f5cd248d4b7582b140825625 | [
"num_heads, head_size = (2, 2)\nfrom_seq_length = 4\nbatch_size = 3\ninit_decode_length = 0\ncache = _create_cache(batch_size, init_decode_length, num_heads, head_size)\nlayer = attention.CachedAttention(num_heads=num_heads, key_dim=head_size)\nfrom_data = tf.zeros((batch_size, from_seq_length, 8), dtype=np.float32... | <|body_start_0|>
num_heads, head_size = (2, 2)
from_seq_length = 4
batch_size = 3
init_decode_length = 0
cache = _create_cache(batch_size, init_decode_length, num_heads, head_size)
layer = attention.CachedAttention(num_heads=num_heads, key_dim=head_size)
from_data... | CachedAttentionTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedAttentionTest:
def test_masked_attention(self):
"""Test with a mask tensor."""
<|body_0|>
def test_padded_decode(self):
"""Test with a mask tensor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num_heads, head_size = (2, 2)
from_seq_... | stack_v2_sparse_classes_10k_train_005484 | 3,761 | permissive | [
{
"docstring": "Test with a mask tensor.",
"name": "test_masked_attention",
"signature": "def test_masked_attention(self)"
},
{
"docstring": "Test with a mask tensor.",
"name": "test_padded_decode",
"signature": "def test_padded_decode(self)"
}
] | 2 | null | Implement the Python class `CachedAttentionTest` described below.
Class description:
Implement the CachedAttentionTest class.
Method signatures and docstrings:
- def test_masked_attention(self): Test with a mask tensor.
- def test_padded_decode(self): Test with a mask tensor. | Implement the Python class `CachedAttentionTest` described below.
Class description:
Implement the CachedAttentionTest class.
Method signatures and docstrings:
- def test_masked_attention(self): Test with a mask tensor.
- def test_padded_decode(self): Test with a mask tensor.
<|skeleton|>
class CachedAttentionTest:
... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class CachedAttentionTest:
def test_masked_attention(self):
"""Test with a mask tensor."""
<|body_0|>
def test_padded_decode(self):
"""Test with a mask tensor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CachedAttentionTest:
def test_masked_attention(self):
"""Test with a mask tensor."""
num_heads, head_size = (2, 2)
from_seq_length = 4
batch_size = 3
init_decode_length = 0
cache = _create_cache(batch_size, init_decode_length, num_heads, head_size)
layer... | the_stack_v2_python_sparse | models/official/nlp/modeling/layers/attention_test.py | aboerzel/German_License_Plate_Recognition | train | 34 | |
19254201cbd0e978e06f94ee7994df89238e69f3 | [
"index_m = m - 1\nindex_n = n - 1\nwhile index_m >= 0 and index_n >= 0:\n if nums1[index_m] >= nums2[index_n]:\n nums1[index_m + index_n + 1] = nums1[index_m]\n index_m -= 1\n else:\n nums1[index_m + index_n + 1] = nums2[index_n]\n index_n -= 1\nwhile index_n >= 0:\n nums1[index... | <|body_start_0|>
index_m = m - 1
index_n = n - 1
while index_m >= 0 and index_n >= 0:
if nums1[index_m] >= nums2[index_n]:
nums1[index_m + index_n + 1] = nums1[index_m]
index_m -= 1
else:
nums1[index_m + index_n + 1] = nums2... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge_v2(self, nums1, m, nums2, n):
""":type nums1: List[in... | stack_v2_sparse_classes_10k_train_005485 | 2,568 | no_license | [
{
"docstring": ":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature": "def merge(self, nums1, m, nums2, n)"
},
{
"docstring": ":type nums1: List[int] :type m: int :type nums2: Li... | 2 | stack_v2_sparse_classes_30k_train_004884 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.
-... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge_v2(self, nums1, m, nums2, n):
""":type nums1: List[in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead."""
index_m = m - 1
index_n = n - 1
while index_m >= 0 and index_n >= 0:
if n... | the_stack_v2_python_sparse | src/lt_88.py | oxhead/CodingYourWay | train | 0 | |
6ca7afc0b45203b1b5fd53ad4a0b91c1e7cf6886 | [
"EasyFrame.__init__(self, title='Canvas Demo 2')\nself.colors = ('blue', 'green', 'red', 'yellow')\nself.shapes = list()\nself.canvas = self.addCanvas(row=0, column=0, columnspan=2, width=300, height=150, background='gray')\nself.addButton(text='Draw oval', row=1, column=0, command=self.drawOval)\nself.addButton(te... | <|body_start_0|>
EasyFrame.__init__(self, title='Canvas Demo 2')
self.colors = ('blue', 'green', 'red', 'yellow')
self.shapes = list()
self.canvas = self.addCanvas(row=0, column=0, columnspan=2, width=300, height=150, background='gray')
self.addButton(text='Draw oval', row=1, col... | Draws filled ovals on a canvas, and allows the user to erase them all. | CanvasDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanvasDemo:
"""Draws filled ovals on a canvas, and allows the user to erase them all."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def drawOval(self):
"""Draws a filled oval at a random position."""
<|body_1|>
def eraseAll(... | stack_v2_sparse_classes_10k_train_005486 | 1,550 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Draws a filled oval at a random position.",
"name": "drawOval",
"signature": "def drawOval(self)"
},
{
"docstring": "Deletes all ovals from the canvas.",
... | 3 | null | Implement the Python class `CanvasDemo` described below.
Class description:
Draws filled ovals on a canvas, and allows the user to erase them all.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def drawOval(self): Draws a filled oval at a random position.
- def eraseAll(self... | Implement the Python class `CanvasDemo` described below.
Class description:
Draws filled ovals on a canvas, and allows the user to erase them all.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def drawOval(self): Draws a filled oval at a random position.
- def eraseAll(self... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class CanvasDemo:
"""Draws filled ovals on a canvas, and allows the user to erase them all."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def drawOval(self):
"""Draws a filled oval at a random position."""
<|body_1|>
def eraseAll(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CanvasDemo:
"""Draws filled ovals on a canvas, and allows the user to erase them all."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, title='Canvas Demo 2')
self.colors = ('blue', 'green', 'red', 'yellow')
self.shapes = list()
... | the_stack_v2_python_sparse | gui/breezy/canvasdemo2.py | lforet/robomow | train | 11 |
1c43649d6b4289a21dd0ea87d266f9b83ae7fe16 | [
"url = 'os-hypervisors'\nschema = self.get_schema(self.schema_versions_info)\n_schema = schema.list_search_hypervisors\nif detail:\n url += '/detail'\n _schema = schema.list_hypervisors_detail\nif kwargs:\n url += '?%s' % urllib.urlencode(kwargs)\nresp, body = self.get(url)\nbody = json.loads(body)\nself.v... | <|body_start_0|>
url = 'os-hypervisors'
schema = self.get_schema(self.schema_versions_info)
_schema = schema.list_search_hypervisors
if detail:
url += '/detail'
_schema = schema.list_hypervisors_detail
if kwargs:
url += '?%s' % urllib.urlencode... | HypervisorClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HypervisorClient:
def list_hypervisors(self, detail=False, **kwargs):
"""List hypervisors information."""
<|body_0|>
def show_hypervisor(self, hypervisor_id, **kwargs):
"""Display the details of the specified hypervisor."""
<|body_1|>
def list_servers_on... | stack_v2_sparse_classes_10k_train_005487 | 4,358 | permissive | [
{
"docstring": "List hypervisors information.",
"name": "list_hypervisors",
"signature": "def list_hypervisors(self, detail=False, **kwargs)"
},
{
"docstring": "Display the details of the specified hypervisor.",
"name": "show_hypervisor",
"signature": "def show_hypervisor(self, hyperviso... | 6 | stack_v2_sparse_classes_30k_train_004760 | Implement the Python class `HypervisorClient` described below.
Class description:
Implement the HypervisorClient class.
Method signatures and docstrings:
- def list_hypervisors(self, detail=False, **kwargs): List hypervisors information.
- def show_hypervisor(self, hypervisor_id, **kwargs): Display the details of the... | Implement the Python class `HypervisorClient` described below.
Class description:
Implement the HypervisorClient class.
Method signatures and docstrings:
- def list_hypervisors(self, detail=False, **kwargs): List hypervisors information.
- def show_hypervisor(self, hypervisor_id, **kwargs): Display the details of the... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class HypervisorClient:
def list_hypervisors(self, detail=False, **kwargs):
"""List hypervisors information."""
<|body_0|>
def show_hypervisor(self, hypervisor_id, **kwargs):
"""Display the details of the specified hypervisor."""
<|body_1|>
def list_servers_on... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HypervisorClient:
def list_hypervisors(self, detail=False, **kwargs):
"""List hypervisors information."""
url = 'os-hypervisors'
schema = self.get_schema(self.schema_versions_info)
_schema = schema.list_search_hypervisors
if detail:
url += '/detail'
... | the_stack_v2_python_sparse | tempest/lib/services/compute/hypervisor_client.py | openstack/tempest | train | 270 | |
99e08a642eeb29c436915ae0d2d1ca3b54fc45e8 | [
"try:\n from safetlib.transport import all_transports\nexcept ImportError:\n transports = []\n try:\n from safetlib.transport_hid import HidTransport\n transports.append(HidTransport)\n except BaseException:\n pass\n try:\n from safetlib.transport_webusb import WebUsbTrans... | <|body_start_0|>
try:
from safetlib.transport import all_transports
except ImportError:
transports = []
try:
from safetlib.transport_hid import HidTransport
transports.append(HidTransport)
except BaseException:
... | SafeTTransport | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SafeTTransport:
def all_transports():
"""Reimplemented safetlib.transport.all_transports so that we can enable/disable specific transports."""
<|body_0|>
def enumerate_devices(self):
"""Just like safetlib.transport.enumerate_devices, but with exception catching, so t... | stack_v2_sparse_classes_10k_train_005488 | 3,566 | permissive | [
{
"docstring": "Reimplemented safetlib.transport.all_transports so that we can enable/disable specific transports.",
"name": "all_transports",
"signature": "def all_transports()"
},
{
"docstring": "Just like safetlib.transport.enumerate_devices, but with exception catching, so that transports ca... | 3 | null | Implement the Python class `SafeTTransport` described below.
Class description:
Implement the SafeTTransport class.
Method signatures and docstrings:
- def all_transports(): Reimplemented safetlib.transport.all_transports so that we can enable/disable specific transports.
- def enumerate_devices(self): Just like safe... | Implement the Python class `SafeTTransport` described below.
Class description:
Implement the SafeTTransport class.
Method signatures and docstrings:
- def all_transports(): Reimplemented safetlib.transport.all_transports so that we can enable/disable specific transports.
- def enumerate_devices(self): Just like safe... | a740a20fc2677d54e99fa981b7968b877a7b53a3 | <|skeleton|>
class SafeTTransport:
def all_transports():
"""Reimplemented safetlib.transport.all_transports so that we can enable/disable specific transports."""
<|body_0|>
def enumerate_devices(self):
"""Just like safetlib.transport.enumerate_devices, but with exception catching, so t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SafeTTransport:
def all_transports():
"""Reimplemented safetlib.transport.all_transports so that we can enable/disable specific transports."""
try:
from safetlib.transport import all_transports
except ImportError:
transports = []
try:
... | the_stack_v2_python_sparse | electrum/plugins/safe_t/transport.py | spesmilo/electrum | train | 7,132 | |
551470ff6322f7f78a8271513236fca9aa7ef26f | [
"if not root:\n return ''\nqueue = [(1, root)]\nseq_val_tuples = []\nwhile queue:\n seq, node = queue.pop(0)\n seq_val_tuples.append(f'{seq}_{node.val}')\n if node.left:\n queue.append((seq * 2, node.left))\n if node.right:\n queue.append((seq * 2 + 1, node.right))\nreturn ','.join(seq_... | <|body_start_0|>
if not root:
return ''
queue = [(1, root)]
seq_val_tuples = []
while queue:
seq, node = queue.pop(0)
seq_val_tuples.append(f'{seq}_{node.val}')
if node.left:
queue.append((seq * 2, node.left))
if... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_005489 | 1,855 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_000073 | 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:... | 1a773bb02871d418def9629f608c68c4b0e8fe4e | <|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_10k | 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 = [(1, root)]
seq_val_tuples = []
while queue:
seq, node = queue.pop(0)
seq_val_tuples.append(f'{... | the_stack_v2_python_sparse | archive-dhkim/leetcode/ch14_tree/prob47_serialize_and_deserialize_binary_tree.py | LenKIM/implements | train | 3 | |
c9b0b92f98ed1ac2144e9a76fc40dd338b2f5284 | [
"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!')"
] | <|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... | Proto file describing the Shared Criterion service. Service to manage shared criteria. | SharedCriterionServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedCriterionServiceServicer:
"""Proto file describing the Shared Criterion service. Service to manage shared criteria."""
def GetSharedCriterion(self, request, context):
"""Returns the requested shared criterion in full detail."""
<|body_0|>
def MutateSharedCriteria(s... | stack_v2_sparse_classes_10k_train_005490 | 3,500 | permissive | [
{
"docstring": "Returns the requested shared criterion in full detail.",
"name": "GetSharedCriterion",
"signature": "def GetSharedCriterion(self, request, context)"
},
{
"docstring": "Creates or removes shared criteria. Operation statuses are returned.",
"name": "MutateSharedCriteria",
"... | 2 | stack_v2_sparse_classes_30k_train_001991 | Implement the Python class `SharedCriterionServiceServicer` described below.
Class description:
Proto file describing the Shared Criterion service. Service to manage shared criteria.
Method signatures and docstrings:
- def GetSharedCriterion(self, request, context): Returns the requested shared criterion in full deta... | Implement the Python class `SharedCriterionServiceServicer` described below.
Class description:
Proto file describing the Shared Criterion service. Service to manage shared criteria.
Method signatures and docstrings:
- def GetSharedCriterion(self, request, context): Returns the requested shared criterion in full deta... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class SharedCriterionServiceServicer:
"""Proto file describing the Shared Criterion service. Service to manage shared criteria."""
def GetSharedCriterion(self, request, context):
"""Returns the requested shared criterion in full detail."""
<|body_0|>
def MutateSharedCriteria(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SharedCriterionServiceServicer:
"""Proto file describing the Shared Criterion service. Service to manage shared criteria."""
def GetSharedCriterion(self, request, context):
"""Returns the requested shared criterion in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | google/ads/google_ads/v2/proto/services/shared_criterion_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
bb8e704eca90eb49930b6fb10bf9bd4924c87959 | [
"self.serial_devname = serial_devname\nproxy_prompt = '{}>'.format(serial_devname)\nsuper(PlinkSerial, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, expected_prompt=proxy_prompt, target_newline=target_newline, runner=runner)\nself.ret_required = False\nself._python_shell_exit_sen... | <|body_start_0|>
self.serial_devname = serial_devname
proxy_prompt = '{}>'.format(serial_devname)
super(PlinkSerial, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, expected_prompt=proxy_prompt, target_newline=target_newline, runner=runner)
self.ret_requ... | PlinkSerial | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlinkSerial:
def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, tty... | stack_v2_sparse_classes_10k_train_005491 | 3,590 | permissive | [
{
"docstring": ":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, ttyS4). :param prompt: prompt where we start from :param newline_chars: Characters to split local lines - list. :param target_newline: Charact... | 4 | null | Implement the Python class `PlinkSerial` described below.
Class description:
Implement the PlinkSerial class.
Method signatures and docstrings:
- def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None): :param connection: Moler connection to device, terminal w... | Implement the Python class `PlinkSerial` described below.
Class description:
Implement the PlinkSerial class.
Method signatures and docstrings:
- def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None): :param connection: Moler connection to device, terminal w... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class PlinkSerial:
def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, tty... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PlinkSerial:
def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, ttyS4). :param pr... | the_stack_v2_python_sparse | moler/cmd/at/plink_serial.py | nokia/moler | train | 60 | |
5719de02c8b56e9c1a4c5b8efa338146b0461852 | [
"super(Upsample, self).__init__()\nself.apply_dropout = apply_dropout\ninitializer = tf.random_normal_initializer(0, 0.02)\nself.conv1 = tf.keras.layers.Conv2DTranspose(filters=filters, kernel_size=(size, size), strides=(2, 2), padding='same', kernel_initializer=initializer, use_bias=False)\nself.batch_normal = tf.... | <|body_start_0|>
super(Upsample, self).__init__()
self.apply_dropout = apply_dropout
initializer = tf.random_normal_initializer(0, 0.02)
self.conv1 = tf.keras.layers.Conv2DTranspose(filters=filters, kernel_size=(size, size), strides=(2, 2), padding='same', kernel_initializer=initializer,... | Use convolution layer to upsample. | Upsample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upsample:
"""Use convolution layer to upsample."""
def __init__(self, filters, size, apply_dropout=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_005492 | 20,044 | no_license | [
{
"docstring": "The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:",
"name": "__init__",
"signature": "def __init__(self, filters, size, apply_dropout=True)"
},
{
"docstring": "Calls the model on n... | 2 | stack_v2_sparse_classes_30k_train_000980 | Implement the Python class `Upsample` described below.
Class description:
Use convolution layer to upsample.
Method signatures and docstrings:
- def __init__(self, filters, size, apply_dropout=True): The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchn... | Implement the Python class `Upsample` described below.
Class description:
Use convolution layer to upsample.
Method signatures and docstrings:
- def __init__(self, filters, size, apply_dropout=True): The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchn... | d1b70b2a954f4665b628ba252b03c1a74b95559f | <|skeleton|>
class Upsample:
"""Use convolution layer to upsample."""
def __init__(self, filters, size, apply_dropout=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Upsample:
"""Use convolution layer to upsample."""
def __init__(self, filters, size, apply_dropout=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
super(Upsample, self).__ini... | the_stack_v2_python_sparse | NeuralNetworks-tensorflow/generation_network_model/GAN/pix2pix.py | zhaocc1106/machine_learn | train | 15 |
871b5b2bffed62833fad996690a901b3b05fd133 | [
"objc = ctypes.cdll.LoadLibrary(find_library('objc'))\nobjc.objc_getClass.restype = ctypes.c_void_p\nobjc.sel_registerName.restype = ctypes.c_void_p\nobjc.objc_msgSend.restype = ctypes.c_void_p\nobjc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]\nreturn objc",
"objc = self.objc\nENBridge = objc.objc_... | <|body_start_0|>
objc = ctypes.cdll.LoadLibrary(find_library('objc'))
objc.objc_getClass.restype = ctypes.c_void_p
objc.sel_registerName.restype = ctypes.c_void_p
objc.objc_msgSend.restype = ctypes.c_void_p
objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
r... | Access ENBridge.m using ctypes. Based on: https://stackoverflow.com/questions/1490039/ calling-objective-c-functions-from-python#1490644 | ENBridge | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ENBridge:
"""Access ENBridge.m using ctypes. Based on: https://stackoverflow.com/questions/1490039/ calling-objective-c-functions-from-python#1490644"""
def _default_objc(self):
"""Load the objc library using ctypes."""
<|body_0|>
def _default_bridge(self):
"""Ge... | stack_v2_sparse_classes_10k_train_005493 | 6,257 | permissive | [
{
"docstring": "Load the objc library using ctypes.",
"name": "_default_objc",
"signature": "def _default_objc(self)"
},
{
"docstring": "Get an instance of the ENBridge object using ctypes.",
"name": "_default_bridge",
"signature": "def _default_bridge(self)"
},
{
"docstring": "S... | 3 | stack_v2_sparse_classes_30k_train_004789 | Implement the Python class `ENBridge` described below.
Class description:
Access ENBridge.m using ctypes. Based on: https://stackoverflow.com/questions/1490039/ calling-objective-c-functions-from-python#1490644
Method signatures and docstrings:
- def _default_objc(self): Load the objc library using ctypes.
- def _def... | Implement the Python class `ENBridge` described below.
Class description:
Access ENBridge.m using ctypes. Based on: https://stackoverflow.com/questions/1490039/ calling-objective-c-functions-from-python#1490644
Method signatures and docstrings:
- def _default_objc(self): Load the objc library using ctypes.
- def _def... | 04c3a015bcd649f374c5ecd98fcddba5e4fbdbdc | <|skeleton|>
class ENBridge:
"""Access ENBridge.m using ctypes. Based on: https://stackoverflow.com/questions/1490039/ calling-objective-c-functions-from-python#1490644"""
def _default_objc(self):
"""Load the objc library using ctypes."""
<|body_0|>
def _default_bridge(self):
"""Ge... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ENBridge:
"""Access ENBridge.m using ctypes. Based on: https://stackoverflow.com/questions/1490039/ calling-objective-c-functions-from-python#1490644"""
def _default_objc(self):
"""Load the objc library using ctypes."""
objc = ctypes.cdll.LoadLibrary(find_library('objc'))
objc.obj... | the_stack_v2_python_sparse | src/enamlnative/ios/app.py | mfkiwl/enaml-native | train | 0 |
6ccf18ebf2598d6546c289edf100209f458c6335 | [
"settings_file = current_app.config.get('GAME_SETTINGS_FILE')\nif not settings_file:\n raise RuntimeError('GAME_SETTINGS_FILE is not set')\nsettings_file = os.path.join(os.path.dirname(current_app.instance_path), 'kingdom_api', settings_file)\nif not os.path.isfile(settings_file):\n raise RuntimeError(f'Confi... | <|body_start_0|>
settings_file = current_app.config.get('GAME_SETTINGS_FILE')
if not settings_file:
raise RuntimeError('GAME_SETTINGS_FILE is not set')
settings_file = os.path.join(os.path.dirname(current_app.instance_path), 'kingdom_api', settings_file)
if not os.path.isfile... | Basic Settings logic. | SettingsService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SettingsService:
"""Basic Settings logic."""
def load_game_conf(cls) -> dict:
"""Load game configuration. :return: dict of settings"""
<|body_0|>
def initialize(cls, settings: Settings) -> Settings:
"""Init settings at the start from configuration. :param setting... | stack_v2_sparse_classes_10k_train_005494 | 2,351 | no_license | [
{
"docstring": "Load game configuration. :return: dict of settings",
"name": "load_game_conf",
"signature": "def load_game_conf(cls) -> dict"
},
{
"docstring": "Init settings at the start from configuration. :param settings: Settings model :return: Settings model - filled with data",
"name":... | 2 | stack_v2_sparse_classes_30k_train_002261 | Implement the Python class `SettingsService` described below.
Class description:
Basic Settings logic.
Method signatures and docstrings:
- def load_game_conf(cls) -> dict: Load game configuration. :return: dict of settings
- def initialize(cls, settings: Settings) -> Settings: Init settings at the start from configur... | Implement the Python class `SettingsService` described below.
Class description:
Basic Settings logic.
Method signatures and docstrings:
- def load_game_conf(cls) -> dict: Load game configuration. :return: dict of settings
- def initialize(cls, settings: Settings) -> Settings: Init settings at the start from configur... | 48408f43cbbeed035ed30c29c8c8f13c8886e949 | <|skeleton|>
class SettingsService:
"""Basic Settings logic."""
def load_game_conf(cls) -> dict:
"""Load game configuration. :return: dict of settings"""
<|body_0|>
def initialize(cls, settings: Settings) -> Settings:
"""Init settings at the start from configuration. :param setting... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SettingsService:
"""Basic Settings logic."""
def load_game_conf(cls) -> dict:
"""Load game configuration. :return: dict of settings"""
settings_file = current_app.config.get('GAME_SETTINGS_FILE')
if not settings_file:
raise RuntimeError('GAME_SETTINGS_FILE is not set')... | the_stack_v2_python_sparse | kingdom_api/services/settings.py | AlexKupreev/kingdom-api | train | 0 |
a59456d188ef7fd86aa0bc5546658f0fd306d697 | [
"if not isinstance(course_location, Location):\n course_location = Location(course_location)\ncourse = {}\ndescriptor = get_modulestore(course_location).get_item(course_location)\nfor field in descriptor.fields + descriptor.lms.fields:\n if field.scope != Scope.settings:\n continue\n if field.name n... | <|body_start_0|>
if not isinstance(course_location, Location):
course_location = Location(course_location)
course = {}
descriptor = get_modulestore(course_location).get_item(course_location)
for field in descriptor.fields + descriptor.lms.fields:
if field.scope !=... | For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata. | CourseMetadata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseMetadata:
"""For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata."""
def fetch(cls, course_location):
"""Fetch... | stack_v2_sparse_classes_10k_train_005495 | 3,895 | no_license | [
{
"docstring": "Fetch the key:value editable course details for the given course from persistence and return a CourseMetadata model.",
"name": "fetch",
"signature": "def fetch(cls, course_location)"
},
{
"docstring": "Decode the json into CourseMetadata and save any changed attrs to the db. Ensu... | 3 | null | Implement the Python class `CourseMetadata` described below.
Class description:
For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata.
Method signatures... | Implement the Python class `CourseMetadata` described below.
Class description:
For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata.
Method signatures... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class CourseMetadata:
"""For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata."""
def fetch(cls, course_location):
"""Fetch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CourseMetadata:
"""For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata."""
def fetch(cls, course_location):
"""Fetch the key:valu... | the_stack_v2_python_sparse | ExtractFeatures/Data/pratik98/course_metadata.py | vivekaxl/LexisNexis | train | 9 |
be7e8eeda076146c6a5952c7daa30333c9f7290c | [
"self.paths = paths\nself.interval = interval\nself.default = default",
"if step % self.interval == 0:\n for path in self.paths:\n retrieve(last_results, path, default=self.default)"
] | <|body_start_0|>
self.paths = paths
self.interval = interval
self.default = default
<|end_body_0|>
<|body_start_1|>
if step % self.interval == 0:
for path in self.paths:
retrieve(last_results, path, default=self.default)
<|end_body_1|>
| Retrieve paths. | ExpandHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpandHook:
"""Retrieve paths."""
def __init__(self, paths, interval, default=None):
"""Parameters ---------- paths : list of keypaths to expand. interval : int The interval in which expansion is performed."""
<|body_0|>
def after_step(self, step, last_results):
... | stack_v2_sparse_classes_10k_train_005496 | 4,225 | permissive | [
{
"docstring": "Parameters ---------- paths : list of keypaths to expand. interval : int The interval in which expansion is performed.",
"name": "__init__",
"signature": "def __init__(self, paths, interval, default=None)"
},
{
"docstring": "Called after each step.",
"name": "after_step",
... | 2 | stack_v2_sparse_classes_30k_train_000123 | Implement the Python class `ExpandHook` described below.
Class description:
Retrieve paths.
Method signatures and docstrings:
- def __init__(self, paths, interval, default=None): Parameters ---------- paths : list of keypaths to expand. interval : int The interval in which expansion is performed.
- def after_step(sel... | Implement the Python class `ExpandHook` described below.
Class description:
Retrieve paths.
Method signatures and docstrings:
- def __init__(self, paths, interval, default=None): Parameters ---------- paths : list of keypaths to expand. interval : int The interval in which expansion is performed.
- def after_step(sel... | 317cb1b61bf810a68004788d08418a5352653264 | <|skeleton|>
class ExpandHook:
"""Retrieve paths."""
def __init__(self, paths, interval, default=None):
"""Parameters ---------- paths : list of keypaths to expand. interval : int The interval in which expansion is performed."""
<|body_0|>
def after_step(self, step, last_results):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExpandHook:
"""Retrieve paths."""
def __init__(self, paths, interval, default=None):
"""Parameters ---------- paths : list of keypaths to expand. interval : int The interval in which expansion is performed."""
self.paths = paths
self.interval = interval
self.default = defa... | the_stack_v2_python_sparse | edflow/hooks/util_hooks.py | pesser/edflow | train | 27 |
1b6fc78f538268ebf731cebc48ca5c2304f56234 | [
"if not root:\n return\nlst = []\nself.dfs_traverse(root, lst)\nlst = lst[1:]\nroot.left = None\ncur = root\nfor node in lst:\n node.left = None\n node.right = None\n cur.right = node\n cur = cur.right",
"if not root:\n return\nlst.append(root)\nself.dfs_traverse(root.left, lst)\nself.dfs_traver... | <|body_start_0|>
if not root:
return
lst = []
self.dfs_traverse(root, lst)
lst = lst[1:]
root.left = None
cur = root
for node in lst:
node.left = None
node.right = None
cur.right = node
cur = cur.right
<|... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten_data_structure(self, root):
""":param root: TreeNode :return: nothing, do it in place"""
<|body_0|>
def dfs_traverse(self, root, lst):
"""pre_order traverse"""
<|body_1|>
def flatten(self, root):
"""pre-order should be easy ... | stack_v2_sparse_classes_10k_train_005497 | 2,826 | permissive | [
{
"docstring": ":param root: TreeNode :return: nothing, do it in place",
"name": "flatten_data_structure",
"signature": "def flatten_data_structure(self, root)"
},
{
"docstring": "pre_order traverse",
"name": "dfs_traverse",
"signature": "def dfs_traverse(self, root, lst)"
},
{
"... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_data_structure(self, root): :param root: TreeNode :return: nothing, do it in place
- def dfs_traverse(self, root, lst): pre_order traverse
- def flatten(self, root): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_data_structure(self, root): :param root: TreeNode :return: nothing, do it in place
- def dfs_traverse(self, root, lst): pre_order traverse
- def flatten(self, root): ... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def flatten_data_structure(self, root):
""":param root: TreeNode :return: nothing, do it in place"""
<|body_0|>
def dfs_traverse(self, root, lst):
"""pre_order traverse"""
<|body_1|>
def flatten(self, root):
"""pre-order should be easy ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten_data_structure(self, root):
""":param root: TreeNode :return: nothing, do it in place"""
if not root:
return
lst = []
self.dfs_traverse(root, lst)
lst = lst[1:]
root.left = None
cur = root
for node in lst:
... | the_stack_v2_python_sparse | 114 Flatten Binary Tree to Linked List.py | Aminaba123/LeetCode | train | 1 | |
8612404256c03cd630f18a889fc7058743d91e82 | [
"self.get_args()\nself.check_for_python()\nself.compile()\nsystem('%s .%srelax --test-suite' % (self.path, sep))",
"print('\\n' * 2)\nprint('#' * 27)\nprint('# Compiling the C modules #')\nprint('#' * 27)\nprint('\\n' * 2)\ninclude = PATH_PREFIX + sep + 'include' + sep + self.python\nnumpy_core = PATH_PREFIX + se... | <|body_start_0|>
self.get_args()
self.check_for_python()
self.compile()
system('%s .%srelax --test-suite' % (self.path, sep))
<|end_body_0|>
<|body_start_1|>
print('\n' * 2)
print('#' * 27)
print('# Compiling the C modules #')
print('#' * 27)
prin... | Main | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Main:
def __init__(self):
"""Setup, build and run."""
<|body_0|>
def compile(self):
"""Compile the C modules."""
<|body_1|>
def check_for_python(self):
"""Check for the Python binary."""
<|body_2|>
def get_args(self):
"""Test... | stack_v2_sparse_classes_10k_train_005498 | 2,929 | no_license | [
{
"docstring": "Setup, build and run.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compile the C modules.",
"name": "compile",
"signature": "def compile(self)"
},
{
"docstring": "Check for the Python binary.",
"name": "check_for_python",
"sig... | 4 | stack_v2_sparse_classes_30k_test_000046 | Implement the Python class `Main` described below.
Class description:
Implement the Main class.
Method signatures and docstrings:
- def __init__(self): Setup, build and run.
- def compile(self): Compile the C modules.
- def check_for_python(self): Check for the Python binary.
- def get_args(self): Test and return the... | Implement the Python class `Main` described below.
Class description:
Implement the Main class.
Method signatures and docstrings:
- def __init__(self): Setup, build and run.
- def compile(self): Compile the C modules.
- def check_for_python(self): Check for the Python binary.
- def get_args(self): Test and return the... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Main:
def __init__(self):
"""Setup, build and run."""
<|body_0|>
def compile(self):
"""Compile the C modules."""
<|body_1|>
def check_for_python(self):
"""Check for the Python binary."""
<|body_2|>
def get_args(self):
"""Test... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Main:
def __init__(self):
"""Setup, build and run."""
self.get_args()
self.check_for_python()
self.compile()
system('%s .%srelax --test-suite' % (self.path, sep))
def compile(self):
"""Compile the C modules."""
print('\n' * 2)
print('#' * 27... | the_stack_v2_python_sparse | devel_scripts/test_python_versions.py | jlec/relax | train | 4 | |
6c2ca81f10b03dab9a20586a6bca92323d023fb3 | [
"self._count = slave_count + 1\nself._coordinator: DataUpdateCoordinator[list[int] | None] | None = None\nself._result: list[int] = []\nsuper().__init__(hub, entry)",
"name = self._attr_name if self._attr_name else 'modbus_sensor'\nself._coordinator = DataUpdateCoordinator(hass, _LOGGER, name=name)\nslaves: list[... | <|body_start_0|>
self._count = slave_count + 1
self._coordinator: DataUpdateCoordinator[list[int] | None] | None = None
self._result: list[int] = []
super().__init__(hub, entry)
<|end_body_0|>
<|body_start_1|>
name = self._attr_name if self._attr_name else 'modbus_sensor'
... | Modbus binary sensor. | ModbusBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModbusBinarySensor:
"""Modbus binary sensor."""
def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None:
"""Initialize the Modbus binary sensor."""
<|body_0|>
async def async_setup_slaves(self, hass: HomeAssistant, slave_count: int, entry: dic... | stack_v2_sparse_classes_10k_train_005499 | 5,764 | permissive | [
{
"docstring": "Initialize the Modbus binary sensor.",
"name": "__init__",
"signature": "def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None"
},
{
"docstring": "Add slaves as needed (1 read for multiple sensors).",
"name": "async_setup_slaves",
"signature"... | 4 | stack_v2_sparse_classes_30k_train_005184 | Implement the Python class `ModbusBinarySensor` described below.
Class description:
Modbus binary sensor.
Method signatures and docstrings:
- def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None: Initialize the Modbus binary sensor.
- async def async_setup_slaves(self, hass: HomeAssista... | Implement the Python class `ModbusBinarySensor` described below.
Class description:
Modbus binary sensor.
Method signatures and docstrings:
- def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None: Initialize the Modbus binary sensor.
- async def async_setup_slaves(self, hass: HomeAssista... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ModbusBinarySensor:
"""Modbus binary sensor."""
def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None:
"""Initialize the Modbus binary sensor."""
<|body_0|>
async def async_setup_slaves(self, hass: HomeAssistant, slave_count: int, entry: dic... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModbusBinarySensor:
"""Modbus binary sensor."""
def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None:
"""Initialize the Modbus binary sensor."""
self._count = slave_count + 1
self._coordinator: DataUpdateCoordinator[list[int] | None] | None = None
... | the_stack_v2_python_sparse | homeassistant/components/modbus/binary_sensor.py | home-assistant/core | train | 35,501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.