blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
acef95790abc00f2825b98deaddd1e465af01c47 | [
"tools.validate_int(setting_type, min=0, max=127, name='Setting type')\nif data is not None:\n if not isinstance(data, bytes):\n raise ValueError('data must be a valid bytes object')\nreturn Request(service=cls, subfunction=setting_type, data=data)",
"if response.data is None:\n raise InvalidResponse... | <|body_start_0|>
tools.validate_int(setting_type, min=0, max=127, name='Setting type')
if data is not None:
if not isinstance(data, bytes):
raise ValueError('data must be a valid bytes object')
return Request(service=cls, subfunction=setting_type, data=data)
<|end_bod... | ControlDTCSetting | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlDTCSetting:
def make_request(cls, setting_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for ControlDTCSetting :param setting_type: Service subfunction. Allowed values are from 0 to 0x7F :type setting_type: int :param data: Optional additional data sent ... | stack_v2_sparse_classes_75kplus_train_072700 | 3,301 | permissive | [
{
"docstring": "Generates a request for ControlDTCSetting :param setting_type: Service subfunction. Allowed values are from 0 to 0x7F :type setting_type: int :param data: Optional additional data sent with the request called `DTCSettingControlOptionRecord` :type data: bytes :raises ValueError: If parameters are... | 2 | null | Implement the Python class `ControlDTCSetting` described below.
Class description:
Implement the ControlDTCSetting class.
Method signatures and docstrings:
- def make_request(cls, setting_type: int, data: Optional[bytes]=None) -> Request: Generates a request for ControlDTCSetting :param setting_type: Service subfunct... | Implement the Python class `ControlDTCSetting` described below.
Class description:
Implement the ControlDTCSetting class.
Method signatures and docstrings:
- def make_request(cls, setting_type: int, data: Optional[bytes]=None) -> Request: Generates a request for ControlDTCSetting :param setting_type: Service subfunct... | 1b93cc3cd0e09a21d48881ba53aed257f841bb89 | <|skeleton|>
class ControlDTCSetting:
def make_request(cls, setting_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for ControlDTCSetting :param setting_type: Service subfunction. Allowed values are from 0 to 0x7F :type setting_type: int :param data: Optional additional data sent ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControlDTCSetting:
def make_request(cls, setting_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for ControlDTCSetting :param setting_type: Service subfunction. Allowed values are from 0 to 0x7F :type setting_type: int :param data: Optional additional data sent with the reque... | the_stack_v2_python_sparse | udsoncan/services/ControlDTCSetting.py | pylessard/python-udsoncan | train | 477 | |
5fd0796eb7d9c272870d5eceedb9458ac91c5ba7 | [
"self.bandwidth_bytes_per_second = bandwidth_bytes_per_second\nself.cassandra_backup_job_params = cassandra_backup_job_params\nself.compaction_job_interval_secs = compaction_job_interval_secs\nself.concurrency = concurrency\nself.couchbase_backup_job_params = couchbase_backup_job_params\nself.gc_job_interval_secs =... | <|body_start_0|>
self.bandwidth_bytes_per_second = bandwidth_bytes_per_second
self.cassandra_backup_job_params = cassandra_backup_job_params
self.compaction_job_interval_secs = compaction_job_interval_secs
self.concurrency = concurrency
self.couchbase_backup_job_params = couchbas... | Implementation of the 'NoSqlBackupJobParams' model. Contains backup params at the job level applicable for nosql environment. Attributes: bandwidth_bytes_per_second (int): Net bandwidth bytes per second. cassandra_backup_job_params (CassandraBackupJobParams): Params specific to cassandra backup job. compaction_job_inte... | NoSqlBackupJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoSqlBackupJobParams:
"""Implementation of the 'NoSqlBackupJobParams' model. Contains backup params at the job level applicable for nosql environment. Attributes: bandwidth_bytes_per_second (int): Net bandwidth bytes per second. cassandra_backup_job_params (CassandraBackupJobParams): Params speci... | stack_v2_sparse_classes_75kplus_train_072701 | 7,871 | permissive | [
{
"docstring": "Constructor for the NoSqlBackupJobParams class",
"name": "__init__",
"signature": "def __init__(self, bandwidth_bytes_per_second=None, cassandra_backup_job_params=None, compaction_job_interval_secs=None, concurrency=None, couchbase_backup_job_params=None, gc_job_interval_secs=None, gc_re... | 2 | stack_v2_sparse_classes_30k_train_030339 | Implement the Python class `NoSqlBackupJobParams` described below.
Class description:
Implementation of the 'NoSqlBackupJobParams' model. Contains backup params at the job level applicable for nosql environment. Attributes: bandwidth_bytes_per_second (int): Net bandwidth bytes per second. cassandra_backup_job_params (... | Implement the Python class `NoSqlBackupJobParams` described below.
Class description:
Implementation of the 'NoSqlBackupJobParams' model. Contains backup params at the job level applicable for nosql environment. Attributes: bandwidth_bytes_per_second (int): Net bandwidth bytes per second. cassandra_backup_job_params (... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class NoSqlBackupJobParams:
"""Implementation of the 'NoSqlBackupJobParams' model. Contains backup params at the job level applicable for nosql environment. Attributes: bandwidth_bytes_per_second (int): Net bandwidth bytes per second. cassandra_backup_job_params (CassandraBackupJobParams): Params speci... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoSqlBackupJobParams:
"""Implementation of the 'NoSqlBackupJobParams' model. Contains backup params at the job level applicable for nosql environment. Attributes: bandwidth_bytes_per_second (int): Net bandwidth bytes per second. cassandra_backup_job_params (CassandraBackupJobParams): Params specific to cassan... | the_stack_v2_python_sparse | cohesity_management_sdk/models/no_sql_backup_job_params.py | hsantoyo2/management-sdk-python | train | 0 |
c43098e360efe030c96e00170f5b328229875bdf | [
"self.cookie = json.loads(cookies)\nself.url_list = url_list\nself.session = requests.Session()\nself.ckjar = requests.cookies.RequestsCookieJar()\nself.result = []\nself.headers = headers\nfor i in self.cookie:\n self.ckjar.set(i['name'], i['value'])\nself.session.cookies.update(self.ckjar)",
"for url in self... | <|body_start_0|>
self.cookie = json.loads(cookies)
self.url_list = url_list
self.session = requests.Session()
self.ckjar = requests.cookies.RequestsCookieJar()
self.result = []
self.headers = headers
for i in self.cookie:
self.ckjar.set(i['name'], i['v... | 带cookie访问查询结果 | CookieRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CookieRequest:
"""带cookie访问查询结果"""
def __init__(self, cookies, url_list=None, headers=None):
"""设置requests中的session的cookie"""
<|body_0|>
def cookie_requests(self):
"""带cookie依次访问各个查询结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.cookie ... | stack_v2_sparse_classes_75kplus_train_072702 | 26,194 | no_license | [
{
"docstring": "设置requests中的session的cookie",
"name": "__init__",
"signature": "def __init__(self, cookies, url_list=None, headers=None)"
},
{
"docstring": "带cookie依次访问各个查询结果",
"name": "cookie_requests",
"signature": "def cookie_requests(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005754 | Implement the Python class `CookieRequest` described below.
Class description:
带cookie访问查询结果
Method signatures and docstrings:
- def __init__(self, cookies, url_list=None, headers=None): 设置requests中的session的cookie
- def cookie_requests(self): 带cookie依次访问各个查询结果 | Implement the Python class `CookieRequest` described below.
Class description:
带cookie访问查询结果
Method signatures and docstrings:
- def __init__(self, cookies, url_list=None, headers=None): 设置requests中的session的cookie
- def cookie_requests(self): 带cookie依次访问各个查询结果
<|skeleton|>
class CookieRequest:
"""带cookie访问查询结果""... | dc9dbbb5bf5e3d29cd664219826ca334916b953f | <|skeleton|>
class CookieRequest:
"""带cookie访问查询结果"""
def __init__(self, cookies, url_list=None, headers=None):
"""设置requests中的session的cookie"""
<|body_0|>
def cookie_requests(self):
"""带cookie依次访问各个查询结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CookieRequest:
"""带cookie访问查询结果"""
def __init__(self, cookies, url_list=None, headers=None):
"""设置requests中的session的cookie"""
self.cookie = json.loads(cookies)
self.url_list = url_list
self.session = requests.Session()
self.ckjar = requests.cookies.RequestsCookieJa... | the_stack_v2_python_sparse | skill/crawler_gov.py | mj3428/python_for_practice | train | 1 |
abda7df16aac0107186148ee700dd5646f81096c | [
"if not nums or len(nums) < 3:\n return 0\nelse:\n nums = sorted(nums, reverse=True)\n return max(nums[-1] * nums[-2] * nums[1], nums[0] * nums[1] * nums[2])",
"max1, max2, max3, min1, min2 = (-1000, -1000, -1000, 1000, 1000)\nfor num in nums:\n if num <= min1:\n min2 = min1\n min1 = num... | <|body_start_0|>
if not nums or len(nums) < 3:
return 0
else:
nums = sorted(nums, reverse=True)
return max(nums[-1] * nums[-2] * nums[1], nums[0] * nums[1] * nums[2])
<|end_body_0|>
<|body_start_1|>
max1, max2, max3, min1, min2 = (-1000, -1000, -1000, 1000, 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumProduct(self, nums: [int]) -> int:
"""降序排序后结果只可能是前三个数乘积或者第一个正数和最后两个负数乘积 :param nums: :return:"""
<|body_0|>
def maximumProduct1(self, nums: [int]) -> int:
"""寻找三个最大数和两个最小数,比较三个最大数乘积和两个最小数和一个最大数乘积。 :param nums: :return:"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_072703 | 1,381 | no_license | [
{
"docstring": "降序排序后结果只可能是前三个数乘积或者第一个正数和最后两个负数乘积 :param nums: :return:",
"name": "maximumProduct",
"signature": "def maximumProduct(self, nums: [int]) -> int"
},
{
"docstring": "寻找三个最大数和两个最小数,比较三个最大数乘积和两个最小数和一个最大数乘积。 :param nums: :return:",
"name": "maximumProduct1",
"signature": "def m... | 2 | stack_v2_sparse_classes_30k_train_012193 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumProduct(self, nums: [int]) -> int: 降序排序后结果只可能是前三个数乘积或者第一个正数和最后两个负数乘积 :param nums: :return:
- def maximumProduct1(self, nums: [int]) -> int: 寻找三个最大数和两个最小数,比较三个最大数乘积和两个最... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumProduct(self, nums: [int]) -> int: 降序排序后结果只可能是前三个数乘积或者第一个正数和最后两个负数乘积 :param nums: :return:
- def maximumProduct1(self, nums: [int]) -> int: 寻找三个最大数和两个最小数,比较三个最大数乘积和两个最... | 4328382a65ac612aa4dc397f475c1d7db25c7723 | <|skeleton|>
class Solution:
def maximumProduct(self, nums: [int]) -> int:
"""降序排序后结果只可能是前三个数乘积或者第一个正数和最后两个负数乘积 :param nums: :return:"""
<|body_0|>
def maximumProduct1(self, nums: [int]) -> int:
"""寻找三个最大数和两个最小数,比较三个最大数乘积和两个最小数和一个最大数乘积。 :param nums: :return:"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximumProduct(self, nums: [int]) -> int:
"""降序排序后结果只可能是前三个数乘积或者第一个正数和最后两个负数乘积 :param nums: :return:"""
if not nums or len(nums) < 3:
return 0
else:
nums = sorted(nums, reverse=True)
return max(nums[-1] * nums[-2] * nums[1], nums[0] * n... | the_stack_v2_python_sparse | thor/array/ac_628.py | duangduangda/Thor | train | 0 | |
c5f85ce297c35ccd23fe69f194da780e9c307667 | [
"mid_intervall = self.intervall_duration\nb_r0x, b_r0y, b_v0x, b_v0y = b.get_Anfangsbedingungen(t, mid_intervall)\nx = b_r0x(delta_t) + delta_t * b_v0x(delta_t)\ny = b_r0y(delta_t) + delta_t * b_v0y(delta_t) - 0.5 * g * delta_t ** 2\nself.t.extend(t + delta_t)\nself.x.extend(x)\nself.y.extend(y)",
"self.intervall... | <|body_start_0|>
mid_intervall = self.intervall_duration
b_r0x, b_r0y, b_v0x, b_v0y = b.get_Anfangsbedingungen(t, mid_intervall)
x = b_r0x(delta_t) + delta_t * b_v0x(delta_t)
y = b_r0y(delta_t) + delta_t * b_v0y(delta_t) - 0.5 * g * delta_t ** 2
self.t.extend(t + delta_t)
... | Satellit1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Satellit1:
def calculate_pos_in_near_future(self, t, delta_t):
"""Der Satellit nutzt diese Methode, um seine Position zu berechnen. Er verlangt nach Anfangswerten und rechnet danan die Position für die delta_t aus. Die Resultate werden in den Klassenmembern gespeichert."""
<|body... | stack_v2_sparse_classes_75kplus_train_072704 | 5,554 | no_license | [
{
"docstring": "Der Satellit nutzt diese Methode, um seine Position zu berechnen. Er verlangt nach Anfangswerten und rechnet danan die Position für die delta_t aus. Die Resultate werden in den Klassenmembern gespeichert.",
"name": "calculate_pos_in_near_future",
"signature": "def calculate_pos_in_near_f... | 2 | stack_v2_sparse_classes_30k_train_036677 | Implement the Python class `Satellit1` described below.
Class description:
Implement the Satellit1 class.
Method signatures and docstrings:
- def calculate_pos_in_near_future(self, t, delta_t): Der Satellit nutzt diese Methode, um seine Position zu berechnen. Er verlangt nach Anfangswerten und rechnet danan die Posit... | Implement the Python class `Satellit1` described below.
Class description:
Implement the Satellit1 class.
Method signatures and docstrings:
- def calculate_pos_in_near_future(self, t, delta_t): Der Satellit nutzt diese Methode, um seine Position zu berechnen. Er verlangt nach Anfangswerten und rechnet danan die Posit... | 7b77b3e6dff78d3e904943665f55b5173431a83b | <|skeleton|>
class Satellit1:
def calculate_pos_in_near_future(self, t, delta_t):
"""Der Satellit nutzt diese Methode, um seine Position zu berechnen. Er verlangt nach Anfangswerten und rechnet danan die Position für die delta_t aus. Die Resultate werden in den Klassenmembern gespeichert."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Satellit1:
def calculate_pos_in_near_future(self, t, delta_t):
"""Der Satellit nutzt diese Methode, um seine Position zu berechnen. Er verlangt nach Anfangswerten und rechnet danan die Position für die delta_t aus. Die Resultate werden in den Klassenmembern gespeichert."""
mid_intervall = self... | the_stack_v2_python_sparse | buch/papers/perturbation/code/Ansatz2_Ordnung1.py | AndreasFMueller/SeminarNumerik | train | 1 | |
deee2715b6e8d21bf72c1aeb381d88b84c8f81ed | [
"super(ObservationWrapper, self).__init__(env)\nobs_sample = self.flatten(self.env.observation_space.sample())\nsize = len(obs_sample)\nself.observation_space = spaces.Box(low=-np.inf * np.ones(size), high=np.inf * np.ones(size))",
"if name in ['observation_space', 'step', 'env', 'flatten', 'reset']:\n object.... | <|body_start_0|>
super(ObservationWrapper, self).__init__(env)
obs_sample = self.flatten(self.env.observation_space.sample())
size = len(obs_sample)
self.observation_space = spaces.Box(low=-np.inf * np.ones(size), high=np.inf * np.ones(size))
<|end_body_0|>
<|body_start_1|>
if n... | Wrapper covert observations spaces to spaces.Box for convenience. Currently only supports Dict -> Box | ObservationWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservationWrapper:
"""Wrapper covert observations spaces to spaces.Box for convenience. Currently only supports Dict -> Box"""
def __init__(self, env):
"""Initialize wrapper. Parameters ---------- env : gym.Env Environment to wrap compute_optimal : function Function to compute optim... | stack_v2_sparse_classes_75kplus_train_072705 | 2,894 | permissive | [
{
"docstring": "Initialize wrapper. Parameters ---------- env : gym.Env Environment to wrap compute_optimal : function Function to compute optimal policy",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": "Set attribute in wrapper if available and in env if not. Param... | 6 | stack_v2_sparse_classes_30k_train_018661 | Implement the Python class `ObservationWrapper` described below.
Class description:
Wrapper covert observations spaces to spaces.Box for convenience. Currently only supports Dict -> Box
Method signatures and docstrings:
- def __init__(self, env): Initialize wrapper. Parameters ---------- env : gym.Env Environment to ... | Implement the Python class `ObservationWrapper` described below.
Class description:
Wrapper covert observations spaces to spaces.Box for convenience. Currently only supports Dict -> Box
Method signatures and docstrings:
- def __init__(self, env): Initialize wrapper. Parameters ---------- env : gym.Env Environment to ... | d99b21ec844a46d6e18e729ab299f8e9051a68e8 | <|skeleton|>
class ObservationWrapper:
"""Wrapper covert observations spaces to spaces.Box for convenience. Currently only supports Dict -> Box"""
def __init__(self, env):
"""Initialize wrapper. Parameters ---------- env : gym.Env Environment to wrap compute_optimal : function Function to compute optim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObservationWrapper:
"""Wrapper covert observations spaces to spaces.Box for convenience. Currently only supports Dict -> Box"""
def __init__(self, env):
"""Initialize wrapper. Parameters ---------- env : gym.Env Environment to wrap compute_optimal : function Function to compute optimal policy"""
... | the_stack_v2_python_sparse | dacbench/wrappers/observation_wrapper.py | automl/DACBench | train | 19 |
4c14060c4a6cb6550d0316825932ed6b8c9e8a88 | [
"if not caseId:\n return JsonResponse(code=status.HTTP_404_NOT_FOUND, data={'res': 'caseId not found'}, msg='fail')\nif not seqId:\n return JsonResponse(code=status.HTTP_404_NOT_FOUND, data={'res': 'seqId not found'}, msg='fail')\nres = get_apiinfo_data(caseId, seqId)\nreturn res",
"caseId_res = check_caseI... | <|body_start_0|>
if not caseId:
return JsonResponse(code=status.HTTP_404_NOT_FOUND, data={'res': 'caseId not found'}, msg='fail')
if not seqId:
return JsonResponse(code=status.HTTP_404_NOT_FOUND, data={'res': 'seqId not found'}, msg='fail')
res = get_apiinfo_data(caseId, ... | OpertionApiInfoView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpertionApiInfoView:
def get(self, request, caseId, seqId):
"""获取单个用例接口数据 :param request: :param caseId: :param seqId: :return:"""
<|body_0|>
def delete(self, request, caseId, seqId):
"""删除用例的接口 :param request: :param caseId: :param seqId: :return:"""
<|body_... | stack_v2_sparse_classes_75kplus_train_072706 | 10,415 | no_license | [
{
"docstring": "获取单个用例接口数据 :param request: :param caseId: :param seqId: :return:",
"name": "get",
"signature": "def get(self, request, caseId, seqId)"
},
{
"docstring": "删除用例的接口 :param request: :param caseId: :param seqId: :return:",
"name": "delete",
"signature": "def delete(self, reque... | 5 | stack_v2_sparse_classes_30k_train_007850 | Implement the Python class `OpertionApiInfoView` described below.
Class description:
Implement the OpertionApiInfoView class.
Method signatures and docstrings:
- def get(self, request, caseId, seqId): 获取单个用例接口数据 :param request: :param caseId: :param seqId: :return:
- def delete(self, request, caseId, seqId): 删除用例的接口 ... | Implement the Python class `OpertionApiInfoView` described below.
Class description:
Implement the OpertionApiInfoView class.
Method signatures and docstrings:
- def get(self, request, caseId, seqId): 获取单个用例接口数据 :param request: :param caseId: :param seqId: :return:
- def delete(self, request, caseId, seqId): 删除用例的接口 ... | 694e608a20e2774f94589a3c00de4b6a6b3dfdc5 | <|skeleton|>
class OpertionApiInfoView:
def get(self, request, caseId, seqId):
"""获取单个用例接口数据 :param request: :param caseId: :param seqId: :return:"""
<|body_0|>
def delete(self, request, caseId, seqId):
"""删除用例的接口 :param request: :param caseId: :param seqId: :return:"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpertionApiInfoView:
def get(self, request, caseId, seqId):
"""获取单个用例接口数据 :param request: :param caseId: :param seqId: :return:"""
if not caseId:
return JsonResponse(code=status.HTTP_404_NOT_FOUND, data={'res': 'caseId not found'}, msg='fail')
if not seqId:
retu... | the_stack_v2_python_sparse | webkeyword/api/v1/interface/api_info.py | LiuXiangQi/supper | train | 0 | |
48e1b3b75283f9f66b74e06cceb41729c76788a4 | [
"node_class = self.specs.get('node_type')\nsecondary_class = self.specs.get('secondary_type')\nnew_node = self.create_node_by_type(node_class, secondary_class)\nMaxPlus.MaterialManager.PutMtlToMtlEditor(new_node, 0)\nreturn new_node",
"class_ = ConversionManager.get_class_by_name(secondary_class_name)\nclass_id =... | <|body_start_0|>
node_class = self.specs.get('node_type')
secondary_class = self.specs.get('secondary_type')
new_node = self.create_node_by_type(node_class, secondary_class)
MaxPlus.MaterialManager.PutMtlToMtlEditor(new_node, 0)
return new_node
<|end_body_0|>
<|body_start_1|>
... | Creates nodes according to the given specs | NodeCreator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeCreator:
"""Creates nodes according to the given specs"""
def create(self):
"""creates the node"""
<|body_0|>
def create_node_by_type(cls, node_class, secondary_class_name):
"""Creates nodes by type name :param node_class: The MaxPlus class object (ex: MaxPlu... | stack_v2_sparse_classes_75kplus_train_072707 | 43,397 | permissive | [
{
"docstring": "creates the node",
"name": "create",
"signature": "def create(self)"
},
{
"docstring": "Creates nodes by type name :param node_class: The MaxPlus class object (ex: MaxPlus.MtlBase) :param str secondary_class_name: A string for the node type name :return:",
"name": "create_nod... | 2 | null | Implement the Python class `NodeCreator` described below.
Class description:
Creates nodes according to the given specs
Method signatures and docstrings:
- def create(self): creates the node
- def create_node_by_type(cls, node_class, secondary_class_name): Creates nodes by type name :param node_class: The MaxPlus cla... | Implement the Python class `NodeCreator` described below.
Class description:
Creates nodes according to the given specs
Method signatures and docstrings:
- def create(self): creates the node
- def create_node_by_type(cls, node_class, secondary_class_name): Creates nodes by type name :param node_class: The MaxPlus cla... | 7b4cf60cb17f00435ecc3e03d573a9e2d0b44fe0 | <|skeleton|>
class NodeCreator:
"""Creates nodes according to the given specs"""
def create(self):
"""creates the node"""
<|body_0|>
def create_node_by_type(cls, node_class, secondary_class_name):
"""Creates nodes by type name :param node_class: The MaxPlus class object (ex: MaxPlu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodeCreator:
"""Creates nodes according to the given specs"""
def create(self):
"""creates the node"""
node_class = self.specs.get('node_type')
secondary_class = self.specs.get('secondary_type')
new_node = self.create_node_by_type(node_class, secondary_class)
MaxPl... | the_stack_v2_python_sparse | anima/dcc/max/vray2rs.py | eoyilmaz/anima | train | 113 |
b8065de0ffe07d73db33591794e655511845ca85 | [
"abort_if_dialogue_not_found(dialogue_id)\nsession = db_session.create_session()\ndialogue = session.query(Dialogue).get(dialogue_id)\nreturn jsonify({'dialogue': dialogue.to_dict(only=['id', 'name', 'members'])})",
"abort_if_dialogue_not_found(dialogue_id)\nsession = db_session.create_session()\ndialogue = sessi... | <|body_start_0|>
abort_if_dialogue_not_found(dialogue_id)
session = db_session.create_session()
dialogue = session.query(Dialogue).get(dialogue_id)
return jsonify({'dialogue': dialogue.to_dict(only=['id', 'name', 'members'])})
<|end_body_0|>
<|body_start_1|>
abort_if_dialogue_no... | Ресурс Диалога | DialoguesResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialoguesResource:
"""Ресурс Диалога"""
def get(self, dialogue_id):
"""Получить один диалог"""
<|body_0|>
def delete(self, dialogue_id):
"""Удалить диалог"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
abort_if_dialogue_not_found(dialogue_id)
... | stack_v2_sparse_classes_75kplus_train_072708 | 4,442 | no_license | [
{
"docstring": "Получить один диалог",
"name": "get",
"signature": "def get(self, dialogue_id)"
},
{
"docstring": "Удалить диалог",
"name": "delete",
"signature": "def delete(self, dialogue_id)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000262 | Implement the Python class `DialoguesResource` described below.
Class description:
Ресурс Диалога
Method signatures and docstrings:
- def get(self, dialogue_id): Получить один диалог
- def delete(self, dialogue_id): Удалить диалог | Implement the Python class `DialoguesResource` described below.
Class description:
Ресурс Диалога
Method signatures and docstrings:
- def get(self, dialogue_id): Получить один диалог
- def delete(self, dialogue_id): Удалить диалог
<|skeleton|>
class DialoguesResource:
"""Ресурс Диалога"""
def get(self, dial... | 4cd7c6dd0b7cd871694565e6f8a16688639b3e8f | <|skeleton|>
class DialoguesResource:
"""Ресурс Диалога"""
def get(self, dialogue_id):
"""Получить один диалог"""
<|body_0|>
def delete(self, dialogue_id):
"""Удалить диалог"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DialoguesResource:
"""Ресурс Диалога"""
def get(self, dialogue_id):
"""Получить один диалог"""
abort_if_dialogue_not_found(dialogue_id)
session = db_session.create_session()
dialogue = session.query(Dialogue).get(dialogue_id)
return jsonify({'dialogue': dialogue.to... | the_stack_v2_python_sparse | resources/dialogues_resource.py | plov-cyber/SimpleMessenger | train | 0 |
3a14029ec4b6b63ca761985e8e6950028285728d | [
"if target == 0:\n res.append(tem_res)\n return\nif index >= len(candidates) or target < candidates[index]:\n return\nfor i in range(index, len(candidates)):\n if i > index and candidates[i] == candidates[i - 1]:\n continue\n if target < candidates[i]:\n break\n self.curSum(self, can... | <|body_start_0|>
if target == 0:
res.append(tem_res)
return
if index >= len(candidates) or target < candidates[index]:
return
for i in range(index, len(candidates)):
if i > index and candidates[i] == candidates[i - 1]:
continue
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def curSum(self, candidates, index, target, tem_res, res):
""":param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: ... | stack_v2_sparse_classes_75kplus_train_072709 | 1,196 | no_license | [
{
"docstring": ":param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果",
"name": "curSum",
"signature": "def curSum(self, candidates, index, target, tem_res, res)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]] :组合相加",
... | 2 | stack_v2_sparse_classes_30k_train_031217 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def curSum(self, candidates, index, target, tem_res, res): :param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果
- def combinationSum(self, ca... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def curSum(self, candidates, index, target, tem_res, res): :param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果
- def combinationSum(self, ca... | 45fafcc5dd8f3a9dd26984dc6e82441cc2e8f8d7 | <|skeleton|>
class Solution:
def curSum(self, candidates, index, target, tem_res, res):
""":param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def curSum(self, candidates, index, target, tem_res, res):
""":param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果"""
if target == 0:
res.append(tem_res)
return
if index >= len(candidates) or target < candidates[ind... | the_stack_v2_python_sparse | T40.py | zhanggyang/leedcode | train | 0 | |
7022f401f606060688cbdd97661fca41a80384a4 | [
"parsed_content = parse_tibiacom_content(content)\nform = parsed_content.find('form')\ntables = cls._parse_tables(parsed_content)\nif form is None or 'Highscores' not in tables:\n if 'Error' in tables and \"The world doesn't exist!\" in tables['Error'].text:\n return None\n raise InvalidContent('conten... | <|body_start_0|>
parsed_content = parse_tibiacom_content(content)
form = parsed_content.find('form')
tables = cls._parse_tables(parsed_content)
if form is None or 'Highscores' not in tables:
if 'Error' in tables and "The world doesn't exist!" in tables['Error'].text:
... | Represents the highscores of a world. | HighscoresParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighscoresParser:
"""Represents the highscores of a world."""
def from_content(cls, content: str) -> Optional[Highscores]:
"""Create an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 50 entries per page, so in order to obtain ... | stack_v2_sparse_classes_75kplus_train_072710 | 6,505 | permissive | [
{
"docstring": "Create an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 50 entries per page, so in order to obtain the full highscores, all pages must be obtained individually and merged into one. Parameters ---------- content: The HTML content of the p... | 5 | null | Implement the Python class `HighscoresParser` described below.
Class description:
Represents the highscores of a world.
Method signatures and docstrings:
- def from_content(cls, content: str) -> Optional[Highscores]: Create an instance of the class from the html content of a highscores page. Notes ----- Tibia.com onl... | Implement the Python class `HighscoresParser` described below.
Class description:
Represents the highscores of a world.
Method signatures and docstrings:
- def from_content(cls, content: str) -> Optional[Highscores]: Create an instance of the class from the html content of a highscores page. Notes ----- Tibia.com onl... | f8c145dd597c558398bac50e035711e34863b571 | <|skeleton|>
class HighscoresParser:
"""Represents the highscores of a world."""
def from_content(cls, content: str) -> Optional[Highscores]:
"""Create an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 50 entries per page, so in order to obtain ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HighscoresParser:
"""Represents the highscores of a world."""
def from_content(cls, content: str) -> Optional[Highscores]:
"""Create an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 50 entries per page, so in order to obtain the full high... | the_stack_v2_python_sparse | tibiapy/parsers/highscores.py | Galarzaa90/tibia.py | train | 30 |
2eb41f58fc206d51ecec280726d9ef71e020907a | [
"context = super(DeleteView, self).get_context_data(**kwargs)\ncontext['user_type'] = get_user_type(self.request.user)\nreturn context",
"self.object = self.get_object()\nif request.POST.get('goback'):\n url = '/updateAppointment/' + str(self.get_object().id)\n return HttpResponseRedirect(url)\nelse:\n i... | <|body_start_0|>
context = super(DeleteView, self).get_context_data(**kwargs)
context['user_type'] = get_user_type(self.request.user)
return context
<|end_body_0|>
<|body_start_1|>
self.object = self.get_object()
if request.POST.get('goback'):
url = '/updateAppointme... | Deletes the Appointment | DeleteAppointment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteAppointment:
"""Deletes the Appointment"""
def get_context_data(self, **kwargs):
"""Sends info to the template :param kwargs: kwarguments :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Validates info :param request: :param args: arrgume... | stack_v2_sparse_classes_75kplus_train_072711 | 14,106 | no_license | [
{
"docstring": "Sends info to the template :param kwargs: kwarguments :return:",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Validates info :param request: :param args: arrguments :param kwargs: kwarguments :return:",
"name": "post",
... | 2 | stack_v2_sparse_classes_30k_train_026895 | Implement the Python class `DeleteAppointment` described below.
Class description:
Deletes the Appointment
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Sends info to the template :param kwargs: kwarguments :return:
- def post(self, request, *args, **kwargs): Validates info :param request:... | Implement the Python class `DeleteAppointment` described below.
Class description:
Deletes the Appointment
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Sends info to the template :param kwargs: kwarguments :return:
- def post(self, request, *args, **kwargs): Validates info :param request:... | 20b446da14ee3b44f9e184c4be48e23805fb5f10 | <|skeleton|>
class DeleteAppointment:
"""Deletes the Appointment"""
def get_context_data(self, **kwargs):
"""Sends info to the template :param kwargs: kwarguments :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Validates info :param request: :param args: arrgume... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteAppointment:
"""Deletes the Appointment"""
def get_context_data(self, **kwargs):
"""Sends info to the template :param kwargs: kwarguments :return:"""
context = super(DeleteView, self).get_context_data(**kwargs)
context['user_type'] = get_user_type(self.request.user)
... | the_stack_v2_python_sparse | HealthApps/views/appointment.py | KevKode/HealthNet | train | 0 |
1b347eeca875b9f23267b7e75ac82238e49b9c2c | [
"super(Inception, self).__init__()\nbranch1_list = [{'type': ConvBNLayer, 'num_channels': num_channels, 'num_filters': ch1x1, 'filter_size': 1, 'stride': 1, 'padding': 0, 'act': 'relu'}]\nself.branch1 = LinConPoo(branch1_list)\nbranch2_list = [{'type': ConvBNLayer, 'num_channels': num_channels, 'num_filters': ch3x3... | <|body_start_0|>
super(Inception, self).__init__()
branch1_list = [{'type': ConvBNLayer, 'num_channels': num_channels, 'num_filters': ch1x1, 'filter_size': 1, 'stride': 1, 'padding': 0, 'act': 'relu'}]
self.branch1 = LinConPoo(branch1_list)
branch2_list = [{'type': ConvBNLayer, 'num_chan... | Inception | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inception:
def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers... | stack_v2_sparse_classes_75kplus_train_072712 | 22,436 | permissive | [
{
"docstring": "@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of 1x1 conv before 3x3 conv ch3x3 : output channel numbers of 3x3 conv doublech3x3reduced : channel numbers of 1x1 conv before the double 3x3 co... | 2 | stack_v2_sparse_classes_30k_train_013624 | Implement the Python class `Inception` described below.
Class description:
Implement the Inception class.
Method signatures and docstrings:
- def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj): @Brief `Inception` @Parameters num_channels : channel... | Implement the Python class `Inception` described below.
Class description:
Implement the Inception class.
Method signatures and docstrings:
- def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj): @Brief `Inception` @Parameters num_channels : channel... | 78ff3c3ab3906012a0f4a612251347632aa493a7 | <|skeleton|>
class Inception:
def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Inception:
def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of 1x1 conv b... | the_stack_v2_python_sparse | ECO/paddle1.8/model/ECO.py | thinkall/Contrib | train | 1 | |
bc265ad8f156dce7bf7f872247f712207046be6c | [
"super(ConvGRUUnit, self).__init__()\npadding = kernel_size // 2\nself.hidden_channels = hidden_channels\nself.reset_gate = nn.Conv2d(in_channels + hidden_channels, hidden_channels, kernel_size, padding=padding)\nself.update_gate = nn.Conv2d(in_channels + hidden_channels, hidden_channels, kernel_size, padding=paddi... | <|body_start_0|>
super(ConvGRUUnit, self).__init__()
padding = kernel_size // 2
self.hidden_channels = hidden_channels
self.reset_gate = nn.Conv2d(in_channels + hidden_channels, hidden_channels, kernel_size, padding=padding)
self.update_gate = nn.Conv2d(in_channels + hidden_chann... | ConvGRUUnit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvGRUUnit:
def __init__(self, in_channels, hidden_channels, kernel_size):
"""Args: in_channels : int (i_c), number of input channels hidden_channels : int (h_c), number of hidden channels kernel_size : kernel size"""
<|body_0|>
def forward(self, x, prev_state):
"""... | stack_v2_sparse_classes_75kplus_train_072713 | 9,902 | permissive | [
{
"docstring": "Args: in_channels : int (i_c), number of input channels hidden_channels : int (h_c), number of hidden channels kernel_size : kernel size",
"name": "__init__",
"signature": "def __init__(self, in_channels, hidden_channels, kernel_size)"
},
{
"docstring": "Args: x : tensor (b, c, w... | 2 | null | Implement the Python class `ConvGRUUnit` described below.
Class description:
Implement the ConvGRUUnit class.
Method signatures and docstrings:
- def __init__(self, in_channels, hidden_channels, kernel_size): Args: in_channels : int (i_c), number of input channels hidden_channels : int (h_c), number of hidden channel... | Implement the Python class `ConvGRUUnit` described below.
Class description:
Implement the ConvGRUUnit class.
Method signatures and docstrings:
- def __init__(self, in_channels, hidden_channels, kernel_size): Args: in_channels : int (i_c), number of input channels hidden_channels : int (h_c), number of hidden channel... | caf71c8446e185bc6f44f6e29c029883550ef9d9 | <|skeleton|>
class ConvGRUUnit:
def __init__(self, in_channels, hidden_channels, kernel_size):
"""Args: in_channels : int (i_c), number of input channels hidden_channels : int (h_c), number of hidden channels kernel_size : kernel size"""
<|body_0|>
def forward(self, x, prev_state):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvGRUUnit:
def __init__(self, in_channels, hidden_channels, kernel_size):
"""Args: in_channels : int (i_c), number of input channels hidden_channels : int (h_c), number of hidden channels kernel_size : kernel size"""
super(ConvGRUUnit, self).__init__()
padding = kernel_size // 2
... | the_stack_v2_python_sparse | src/DeepNetworks/MISRGRU.py | hehongjie/MISR-GRU | train | 0 | |
b7ee30e20dd94b72b4bd91ff473e65af16ad16e5 | [
"self.name = name\nself.network_ids = network_ids\nself.enrollment_string = enrollment_string",
"if dictionary is None:\n return None\nname = dictionary.get('name')\nnetwork_ids = dictionary.get('networkIds')\nenrollment_string = dictionary.get('enrollmentString')\nreturn cls(name, network_ids, enrollment_stri... | <|body_start_0|>
self.name = name
self.network_ids = network_ids
self.enrollment_string = enrollment_string
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
name = dictionary.get('name')
network_ids = dictionary.get('networkIds')
enr... | Implementation of the 'combineOrganizationNetworks' model. TODO: type model description here. Attributes: name (string): The name of the combined network network_ids (list of string): A list of the network IDs that will be combined. If an ID of a combined network is included in this list, the other networks in the list... | CombineOrganizationNetworksModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CombineOrganizationNetworksModel:
"""Implementation of the 'combineOrganizationNetworks' model. TODO: type model description here. Attributes: name (string): The name of the combined network network_ids (list of string): A list of the network IDs that will be combined. If an ID of a combined netw... | stack_v2_sparse_classes_75kplus_train_072714 | 2,629 | permissive | [
{
"docstring": "Constructor for the CombineOrganizationNetworksModel class",
"name": "__init__",
"signature": "def __init__(self, name=None, network_ids=None, enrollment_string=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictiona... | 2 | stack_v2_sparse_classes_30k_train_049319 | Implement the Python class `CombineOrganizationNetworksModel` described below.
Class description:
Implementation of the 'combineOrganizationNetworks' model. TODO: type model description here. Attributes: name (string): The name of the combined network network_ids (list of string): A list of the network IDs that will b... | Implement the Python class `CombineOrganizationNetworksModel` described below.
Class description:
Implementation of the 'combineOrganizationNetworks' model. TODO: type model description here. Attributes: name (string): The name of the combined network network_ids (list of string): A list of the network IDs that will b... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class CombineOrganizationNetworksModel:
"""Implementation of the 'combineOrganizationNetworks' model. TODO: type model description here. Attributes: name (string): The name of the combined network network_ids (list of string): A list of the network IDs that will be combined. If an ID of a combined netw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CombineOrganizationNetworksModel:
"""Implementation of the 'combineOrganizationNetworks' model. TODO: type model description here. Attributes: name (string): The name of the combined network network_ids (list of string): A list of the network IDs that will be combined. If an ID of a combined network is includ... | the_stack_v2_python_sparse | meraki_sdk/models/combine_organization_networks_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
43fa82815467c2f39774d26dbf1a3b30bb8768a2 | [
"self.sample_for_constraint = self._make_sample_for_constraint(generator, session)\nself.map_to_solution = self._make_map_to_solution(generator, session)\nself.constraint_optimiser = self._make_constraint_optimiser(generator, session)\nself.satisfaction_probability = self._make_satisfaction_probability(generator, s... | <|body_start_0|>
self.sample_for_constraint = self._make_sample_for_constraint(generator, session)
self.map_to_solution = self._make_map_to_solution(generator, session)
self.constraint_optimiser = self._make_constraint_optimiser(generator, session)
self.satisfaction_probability = self._m... | ExportedParametricGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportedParametricGenerator:
def __init__(self, generator, session):
"""ParametricGenerator -> tf.Session -> ExportedParametricGenerator Export a parametric generator that has been trained for easy querying in typical use cases."""
<|body_0|>
def _make_sample_for_constraint(... | stack_v2_sparse_classes_75kplus_train_072715 | 9,339 | no_license | [
{
"docstring": "ParametricGenerator -> tf.Session -> ExportedParametricGenerator Export a parametric generator that has been trained for easy querying in typical use cases.",
"name": "__init__",
"signature": "def __init__(self, generator, session)"
},
{
"docstring": "ParametricGenerator -> tf.Se... | 5 | stack_v2_sparse_classes_30k_train_000191 | Implement the Python class `ExportedParametricGenerator` described below.
Class description:
Implement the ExportedParametricGenerator class.
Method signatures and docstrings:
- def __init__(self, generator, session): ParametricGenerator -> tf.Session -> ExportedParametricGenerator Export a parametric generator that ... | Implement the Python class `ExportedParametricGenerator` described below.
Class description:
Implement the ExportedParametricGenerator class.
Method signatures and docstrings:
- def __init__(self, generator, session): ParametricGenerator -> tf.Session -> ExportedParametricGenerator Export a parametric generator that ... | 9ce7da4be08001d2f658ae8e9e9a49b7df243103 | <|skeleton|>
class ExportedParametricGenerator:
def __init__(self, generator, session):
"""ParametricGenerator -> tf.Session -> ExportedParametricGenerator Export a parametric generator that has been trained for easy querying in typical use cases."""
<|body_0|>
def _make_sample_for_constraint(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExportedParametricGenerator:
def __init__(self, generator, session):
"""ParametricGenerator -> tf.Session -> ExportedParametricGenerator Export a parametric generator that has been trained for easy querying in typical use cases."""
self.sample_for_constraint = self._make_sample_for_constraint(... | the_stack_v2_python_sparse | modules/parametric/export.py | aatack/IP | train | 0 | |
f5d43fcd8d8a7e9c4a510d3b2dc4b049758070b6 | [
"session: Session = schema.new_session()\nhas_role: bool\ntry:\n if isinstance(role, str):\n role = Role[role]\n has_role = bool(UserRoles.find_role(session, username, role) is not None)\nexcept KeyError:\n has_role = False\nexcept UserNotFoundError:\n has_role = False\nschema.remove_session()\nr... | <|body_start_0|>
session: Session = schema.new_session()
has_role: bool
try:
if isinstance(role, str):
role = Role[role]
has_role = bool(UserRoles.find_role(session, username, role) is not None)
except KeyError:
has_role = False
... | Monostate class that provides high-level services to handle role-related use cases. | RoleServices | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleServices:
"""Monostate class that provides high-level services to handle role-related use cases."""
def has_role(username: str, role: Union[Role, str], schema: Schema) -> bool:
"""Determines whether a user has a certain role or not. Args: - username (str): The username of the use... | stack_v2_sparse_classes_75kplus_train_072716 | 3,911 | no_license | [
{
"docstring": "Determines whether a user has a certain role or not. Args: - username (str): The username of the user to test. - role (Union[Role, str]): The role to be tested. - schema (Schema): A database handler where users and roles are mapped into. Returns: - bool: `True` if the user has the given role. `F... | 4 | stack_v2_sparse_classes_30k_train_043911 | Implement the Python class `RoleServices` described below.
Class description:
Monostate class that provides high-level services to handle role-related use cases.
Method signatures and docstrings:
- def has_role(username: str, role: Union[Role, str], schema: Schema) -> bool: Determines whether a user has a certain rol... | Implement the Python class `RoleServices` described below.
Class description:
Monostate class that provides high-level services to handle role-related use cases.
Method signatures and docstrings:
- def has_role(username: str, role: Union[Role, str], schema: Schema) -> bool: Determines whether a user has a certain rol... | d7d50f84e93914d388ccd084b3bee7e02c9e717b | <|skeleton|>
class RoleServices:
"""Monostate class that provides high-level services to handle role-related use cases."""
def has_role(username: str, role: Union[Role, str], schema: Schema) -> bool:
"""Determines whether a user has a certain role or not. Args: - username (str): The username of the use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoleServices:
"""Monostate class that provides high-level services to handle role-related use cases."""
def has_role(username: str, role: Union[Role, str], schema: Schema) -> bool:
"""Determines whether a user has a certain role or not. Args: - username (str): The username of the user to test. - ... | the_stack_v2_python_sparse | components/dms2122auth/dms2122auth/service/roleservices.py | Kencho/practica-dms-2021-2022 | train | 0 |
bc04c695a5d736ea33cb4d4dd5ab497c4f46238f | [
"if [v for v in pattern if v > 10]:\n raise Exception('Maximum 10 views per ddoc allowed')\nif len(pattern) > 10:\n raise Exception('Maximum 10 design documents allowed')\nddocs = dict()\nfor number_of_views in pattern:\n ddoc_name = next(self.ddocs)\n ddocs[ddoc_name] = {'views': {}}\n for index_of_... | <|body_start_0|>
if [v for v in pattern if v > 10]:
raise Exception('Maximum 10 views per ddoc allowed')
if len(pattern) > 10:
raise Exception('Maximum 10 design documents allowed')
ddocs = dict()
for number_of_views in pattern:
ddoc_name = next(self.d... | ViewGen | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewGen:
def generate_ddocs(self, pattern=None, options=None):
"""Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 ... | stack_v2_sparse_classes_75kplus_train_072717 | 6,494 | permissive | [
{
"docstring": "Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 view per ddoc)",
"name": "generate_ddocs",
"signature": "def gener... | 3 | stack_v2_sparse_classes_30k_train_001257 | Implement the Python class `ViewGen` described below.
Class description:
Implement the ViewGen class.
Method signatures and docstrings:
- def generate_ddocs(self, pattern=None, options=None): Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, ... | Implement the Python class `ViewGen` described below.
Class description:
Implement the ViewGen class.
Method signatures and docstrings:
- def generate_ddocs(self, pattern=None, options=None): Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, ... | 9d8220a0925327bddf0e10887e22b57c5d6adb37 | <|skeleton|>
class ViewGen:
def generate_ddocs(self, pattern=None, options=None):
"""Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ViewGen:
def generate_ddocs(self, pattern=None, options=None):
"""Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 view per ddoc)... | the_stack_v2_python_sparse | pytests/performance/viewgen.py | couchbase/testrunner | train | 18 | |
b836af9b43d73ee20aa339a8e1f9ae4cbf6eef1d | [
"n = len(T)\nans, nxt, big = ([0] * n, dict(), 10 ** 9)\nfor i in range(n - 1, -1, -1):\n warmer_index = min((nxt.get(t, big) for t in range(T[i] + 1, 102)))\n if warmer_index != big:\n ans[i] = warmer_index - i\n nxt[T[i]] = i\nreturn ans",
"length = len(T)\nans = [0] * length\nstack = []\nfor i ... | <|body_start_0|>
n = len(T)
ans, nxt, big = ([0] * n, dict(), 10 ** 9)
for i in range(n - 1, -1, -1):
warmer_index = min((nxt.get(t, big) for t in range(T[i] + 1, 102)))
if warmer_index != big:
ans[i] = warmer_index - i
nxt[T[i]] = i
re... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures_1(self, T: List[int]) -> List[int]:
"""方法一:暴力法 时间复杂度:O(nm) 空间复杂度:O(m) :param T: :return:"""
<|body_0|>
def dailyTemperatures_2(self, T: List[int]) -> List[int]:
"""方法二:单调栈 时间复杂度:O(n),其中 n 是温度列表的长度。正向遍历温度列表一遍,对于温度列表中的每个下标,最多有一次进栈和出栈的操作。... | stack_v2_sparse_classes_75kplus_train_072718 | 2,120 | permissive | [
{
"docstring": "方法一:暴力法 时间复杂度:O(nm) 空间复杂度:O(m) :param T: :return:",
"name": "dailyTemperatures_1",
"signature": "def dailyTemperatures_1(self, T: List[int]) -> List[int]"
},
{
"docstring": "方法二:单调栈 时间复杂度:O(n),其中 n 是温度列表的长度。正向遍历温度列表一遍,对于温度列表中的每个下标,最多有一次进栈和出栈的操作。 空间复杂度:O(n),其中 n 是温度列表的长度。需要维护一个单调栈... | 2 | stack_v2_sparse_classes_30k_train_045406 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures_1(self, T: List[int]) -> List[int]: 方法一:暴力法 时间复杂度:O(nm) 空间复杂度:O(m) :param T: :return:
- def dailyTemperatures_2(self, T: List[int]) -> List[int]: 方法二:单调栈 时间... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures_1(self, T: List[int]) -> List[int]: 方法一:暴力法 时间复杂度:O(nm) 空间复杂度:O(m) :param T: :return:
- def dailyTemperatures_2(self, T: List[int]) -> List[int]: 方法二:单调栈 时间... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def dailyTemperatures_1(self, T: List[int]) -> List[int]:
"""方法一:暴力法 时间复杂度:O(nm) 空间复杂度:O(m) :param T: :return:"""
<|body_0|>
def dailyTemperatures_2(self, T: List[int]) -> List[int]:
"""方法二:单调栈 时间复杂度:O(n),其中 n 是温度列表的长度。正向遍历温度列表一遍,对于温度列表中的每个下标,最多有一次进栈和出栈的操作。... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dailyTemperatures_1(self, T: List[int]) -> List[int]:
"""方法一:暴力法 时间复杂度:O(nm) 空间复杂度:O(m) :param T: :return:"""
n = len(T)
ans, nxt, big = ([0] * n, dict(), 10 ** 9)
for i in range(n - 1, -1, -1):
warmer_index = min((nxt.get(t, big) for t in range(T[i] +... | the_stack_v2_python_sparse | LeetCode 热题 HOT 100/dailyTemperatures.py | MaoningGuan/LeetCode | train | 3 | |
cc11cd0c4f1b8bb29201a24986bfe4e51b4696ec | [
"torch.nn.Module.__init__(self)\nself.features = torchvision.models.vgg16(pretrained=False).features\nself.features = torch.nn.Sequential(*list(self.features.children())[:-1])",
"N = X.size()[0]\nX = self.features(X)\nX = X.view(N, 512, 7 ** 2)\nX = torch.bmm(X, torch.transpose(X, 1, 2)) / 7 ** 2\nX = X.view(N, 5... | <|body_start_0|>
torch.nn.Module.__init__(self)
self.features = torchvision.models.vgg16(pretrained=False).features
self.features = torch.nn.Sequential(*list(self.features.children())[:-1])
<|end_body_0|>
<|body_start_1|>
N = X.size()[0]
X = self.features(X)
X = X.view(N... | B-CNN for CUB200. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> bilinear pooling -> sqrt-normalize -> L2-normalize -> fc (200). The network accepts a 3*448*448 input, and the pool5 activation has shape 5... | BCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BCNN:
"""B-CNN for CUB200. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> bilinear pooling -> sqrt-normalize -> L2-normalize -> fc (200). The network accepts a 3*448*448 input, and ... | stack_v2_sparse_classes_75kplus_train_072719 | 4,135 | no_license | [
{
"docstring": "Declare all needed layers.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Forward pass of the network. Args: X, torch.autograd.Variable of shape N*3*448*448. Returns: Score, torch.autograd.Variable of shape N*200.",
"name": "forward",
"signatur... | 2 | null | Implement the Python class `BCNN` described below.
Class description:
B-CNN for CUB200. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> bilinear pooling -> sqrt-normalize -> L2-normalize -> fc (200). The ... | Implement the Python class `BCNN` described below.
Class description:
B-CNN for CUB200. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> bilinear pooling -> sqrt-normalize -> L2-normalize -> fc (200). The ... | 4f19661b5f0fa897b8d9cd065491ef80c0e5b918 | <|skeleton|>
class BCNN:
"""B-CNN for CUB200. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> bilinear pooling -> sqrt-normalize -> L2-normalize -> fc (200). The network accepts a 3*448*448 input, and ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BCNN:
"""B-CNN for CUB200. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> bilinear pooling -> sqrt-normalize -> L2-normalize -> fc (200). The network accepts a 3*448*448 input, and the pool5 act... | the_stack_v2_python_sparse | RM_cls/rmclas/modeling/backbones/BiCNN.py | rikichou/wheel_cls | train | 0 |
f05588d78e471e6fad4dd5098e61af8732c76b6c | [
"theta = np.linspace(0, 2 * np.pi, 1000)\nx = r * np.cos(theta)\ny = r * np.sin(theta)\nreturn (x, y)",
"k = (y1 - y2) / (x1 - x2)\nb = y2 - k * x2\nreturn (k, b)",
"D = math.sqrt(abs(r * r * (k * k + 1) - b * b))\nx1 = (-1 * k * b - D) / (1 + k * k)\nx2 = (-1 * k * b + D) / (1 + k * k)\nreturn (x1, x2)"
] | <|body_start_0|>
theta = np.linspace(0, 2 * np.pi, 1000)
x = r * np.cos(theta)
y = r * np.sin(theta)
return (x, y)
<|end_body_0|>
<|body_start_1|>
k = (y1 - y2) / (x1 - x2)
b = y2 - k * x2
return (k, b)
<|end_body_1|>
<|body_start_2|>
D = math.sqrt(abs(r... | Класс для вычисления различных математических формул | MathHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MathHelper:
"""Класс для вычисления различных математических формул"""
def get_circle_coordinates(r):
"""Метод расчёта координат дуг углов Parameters ---------- :param r: float Радиус дуги :returns списки координат двух дуг"""
<|body_0|>
def get_koef(x1, x2, y1, y2):
... | stack_v2_sparse_classes_75kplus_train_072720 | 1,890 | no_license | [
{
"docstring": "Метод расчёта координат дуг углов Parameters ---------- :param r: float Радиус дуги :returns списки координат двух дуг",
"name": "get_circle_coordinates",
"signature": "def get_circle_coordinates(r)"
},
{
"docstring": "Метод расчёта коэффициента в уравнении прямой Parameters ----... | 3 | null | Implement the Python class `MathHelper` described below.
Class description:
Класс для вычисления различных математических формул
Method signatures and docstrings:
- def get_circle_coordinates(r): Метод расчёта координат дуг углов Parameters ---------- :param r: float Радиус дуги :returns списки координат двух дуг
- d... | Implement the Python class `MathHelper` described below.
Class description:
Класс для вычисления различных математических формул
Method signatures and docstrings:
- def get_circle_coordinates(r): Метод расчёта координат дуг углов Parameters ---------- :param r: float Радиус дуги :returns списки координат двух дуг
- d... | cb71be2cae5618f7f58979b639633dfd0f20efa5 | <|skeleton|>
class MathHelper:
"""Класс для вычисления различных математических формул"""
def get_circle_coordinates(r):
"""Метод расчёта координат дуг углов Parameters ---------- :param r: float Радиус дуги :returns списки координат двух дуг"""
<|body_0|>
def get_koef(x1, x2, y1, y2):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MathHelper:
"""Класс для вычисления различных математических формул"""
def get_circle_coordinates(r):
"""Метод расчёта координат дуг углов Parameters ---------- :param r: float Радиус дуги :returns списки координат двух дуг"""
theta = np.linspace(0, 2 * np.pi, 1000)
x = r * np.cos... | the_stack_v2_python_sparse | util/MathHelper.py | Korgutlova/lib_optics | train | 4 |
95d7cc0d06c6b9e7e6552d56d9e0d68d1f7c423a | [
"super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\nself.redshift_conn_id = redshift_conn_id\nself.aws_credentials_id = aws_credentials_id\nself.table = table\nself.s3_bucket = s3_bucket\nself.s3_key = s3_key\nself.region = region\nself.file_type = file_type\nself.json_format_file = json_format_file\ns... | <|body_start_0|>
super(StageToRedshiftOperator, self).__init__(*args, **kwargs)
self.redshift_conn_id = redshift_conn_id
self.aws_credentials_id = aws_credentials_id
self.table = table
self.s3_bucket = s3_bucket
self.s3_key = s3_key
self.region = region
se... | An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions. | StageToRedshiftOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StageToRedshiftOperator:
"""An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions."""
def __init__(self, red... | stack_v2_sparse_classes_75kplus_train_072721 | 5,277 | no_license | [
{
"docstring": "StageToRedshiftOperator Constructor to inialize the object. Parameters ---------- redshift_conn_id : str redshift connection id used by the Postgresql hook. aws_credentials_id : str AWS credential id used by Aws hooks. table : str The table to which we want to stage the data to. s3_bucket : str ... | 2 | stack_v2_sparse_classes_30k_train_003133 | Implement the Python class `StageToRedshiftOperator` described below.
Class description:
An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and ... | Implement the Python class `StageToRedshiftOperator` described below.
Class description:
An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and ... | c061dbede550e18111de346e58dfb5f258e4c63f | <|skeleton|>
class StageToRedshiftOperator:
"""An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions."""
def __init__(self, red... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StageToRedshiftOperator:
"""An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions."""
def __init__(self, redshift_conn_id... | the_stack_v2_python_sparse | Projects/project5-Data Pipelines with Airflow/plugins/operators/stage_redshift.py | MyDataDevOps/DataEngineeringNanoDegree | train | 0 |
600b474162e535fa590fe388601d73e476261085 | [
"super().__init__()\nself.norm1 = nn.LayerNorm(embed_size)\nself.msa = _MSA(embed_size, num_heads)\nself.norm2 = nn.LayerNorm(embed_size)\nself.mlp = _MLP(in_feats=embed_size, out_feats=num_heads)",
"y = self.norm1(x)\ny = self.msa(y)\nx = x + y\ny = self.norm2(x)\ny = self.mlp(y)\nx = x + y\nreturn x"
] | <|body_start_0|>
super().__init__()
self.norm1 = nn.LayerNorm(embed_size)
self.msa = _MSA(embed_size, num_heads)
self.norm2 = nn.LayerNorm(embed_size)
self.mlp = _MLP(in_feats=embed_size, out_feats=num_heads)
<|end_body_0|>
<|body_start_1|>
y = self.norm1(x)
y = ... | _TransformerLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TransformerLayer:
def __init__(self, embed_size, num_heads):
"""A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_072722 | 24,719 | permissive | [
{
"docstring": "A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module.",
"name": "__init__",
"signature": "def __init__(self, embed_size, num_heads)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_053744 | Implement the Python class `_TransformerLayer` described below.
Class description:
Implement the _TransformerLayer class.
Method signatures and docstrings:
- def __init__(self, embed_size, num_heads): A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_he... | Implement the Python class `_TransformerLayer` described below.
Class description:
Implement the _TransformerLayer class.
Method signatures and docstrings:
- def __init__(self, embed_size, num_heads): A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_he... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class _TransformerLayer:
def __init__(self, embed_size, num_heads):
"""A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _TransformerLayer:
def __init__(self, embed_size, num_heads):
"""A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module."""
super().__init__()
sel... | the_stack_v2_python_sparse | GANDLF/models/unetr.py | mlcommons/GaNDLF | train | 45 | |
9a2bd83083d5cfc67bdf0c7d68b5ddfb72f468c6 | [
"if 'odd' == 'even':\n testdatasize = 320\nif 'odd' == 'odd':\n testdatasize = 319\nxdata = list(itertools.islice(itertools.cycle(range(256)), testdatasize))\nself.data = bytearray(xdata)\nself.datam = bytearray(xdata)\nself.dataout = bytearray([0] * len(self.data))\nself.expected = [255 - x for x in self.dat... | <|body_start_0|>
if 'odd' == 'even':
testdatasize = 320
if 'odd' == 'odd':
testdatasize = 319
xdata = list(itertools.islice(itertools.cycle(range(256)), testdatasize))
self.data = bytearray(xdata)
self.datam = bytearray(xdata)
self.dataout = bytear... | Test for basic general tests. test_template_invert | invert_general_odd_arraysize_nosimd_simd_bytearray | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class invert_general_odd_arraysize_nosimd_simd_bytearray:
"""Test for basic general tests. test_template_invert"""
def setUp(self):
"""Initialise."""
<|body_0|>
def test_invert_inplace(self):
"""Test invert in place - Sequence type bytearray."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_072723 | 38,834 | permissive | [
{
"docstring": "Initialise.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test invert in place - Sequence type bytearray.",
"name": "test_invert_inplace",
"signature": "def test_invert_inplace(self)"
},
{
"docstring": "Test invert in place with array maxlen... | 5 | stack_v2_sparse_classes_30k_train_000835 | Implement the Python class `invert_general_odd_arraysize_nosimd_simd_bytearray` described below.
Class description:
Test for basic general tests. test_template_invert
Method signatures and docstrings:
- def setUp(self): Initialise.
- def test_invert_inplace(self): Test invert in place - Sequence type bytearray.
- def... | Implement the Python class `invert_general_odd_arraysize_nosimd_simd_bytearray` described below.
Class description:
Test for basic general tests. test_template_invert
Method signatures and docstrings:
- def setUp(self): Initialise.
- def test_invert_inplace(self): Test invert in place - Sequence type bytearray.
- def... | 28fe0705fc59b0646a4d44e539c919173e8e8b99 | <|skeleton|>
class invert_general_odd_arraysize_nosimd_simd_bytearray:
"""Test for basic general tests. test_template_invert"""
def setUp(self):
"""Initialise."""
<|body_0|>
def test_invert_inplace(self):
"""Test invert in place - Sequence type bytearray."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class invert_general_odd_arraysize_nosimd_simd_bytearray:
"""Test for basic general tests. test_template_invert"""
def setUp(self):
"""Initialise."""
if 'odd' == 'even':
testdatasize = 320
if 'odd' == 'odd':
testdatasize = 319
xdata = list(itertools.islic... | the_stack_v2_python_sparse | unittest/test_invert.py | m1griffin/bytesfunc | train | 2 |
21b5ca12c811872e34248dc43f74403446b30991 | [
"date_by_year = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}\nyear, month, date = [int(x) for x in date.split('-')]\ndates = 0\nif self.is_leap(year):\n date_by_year[2] += 1\nfor key in range(1, month):\n dates += date_by_year[key]\nreturn dates + date",
"if year %... | <|body_start_0|>
date_by_year = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
year, month, date = [int(x) for x in date.split('-')]
dates = 0
if self.is_leap(year):
date_by_year[2] += 1
for key in range(1, month):
... | Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year."""
def dayOfYear(self, date):
"""Given a string date representing a Gregorian calendar date ... | stack_v2_sparse_classes_75kplus_train_072724 | 1,914 | no_license | [
{
"docstring": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. Example 1: Input: date = \"2019-01-09\" Output: 9 Explanation: Given date is the 9th day of the year in 2019. Example 2: Input: date = \"2019-02-10\" Output: 41 Example 3: Input... | 2 | stack_v2_sparse_classes_30k_train_019735 | Implement the Python class `Solution` described below.
Class description:
Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year.
Method signatures and docstrings:
- def dayOfYear(self, date): Gi... | Implement the Python class `Solution` described below.
Class description:
Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year.
Method signatures and docstrings:
- def dayOfYear(self, date): Gi... | 01fe893ba2e37c9bda79e3081c556698f0b6d2f0 | <|skeleton|>
class Solution:
"""Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year."""
def dayOfYear(self, date):
"""Given a string date representing a Gregorian calendar date ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year."""
def dayOfYear(self, date):
"""Given a string date representing a Gregorian calendar date formatted as ... | the_stack_v2_python_sparse | LeetCode/1154_day_of_the_year.py | KKosukeee/CodingQuestions | train | 1 |
16ff5689577916b7fa815c990dfc89d1d36b633f | [
"self.cleaned_data = super(DeleteWaypointForm, self).clean()\nwaypoint = Waypoint.objects.filter(pk=self.cleaned_data['id_waypoint'])\nif not waypoint:\n raise ValidationError('El punto de entrega no existe')\nreturn self.cleaned_data",
"waypoint = Waypoint.objects.get(pk=self.cleaned_data['id_waypoint'])\nway... | <|body_start_0|>
self.cleaned_data = super(DeleteWaypointForm, self).clean()
waypoint = Waypoint.objects.filter(pk=self.cleaned_data['id_waypoint'])
if not waypoint:
raise ValidationError('El punto de entrega no existe')
return self.cleaned_data
<|end_body_0|>
<|body_start_1... | Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user. | DeleteWaypointForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteWaypointForm:
"""Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user."""
def clean(self):
"""Override clean data to validate the id corresponds to a real Waypoint."""
<|body_0|>
def save(self, *args, **kwargs):
"""Overr... | stack_v2_sparse_classes_75kplus_train_072725 | 8,251 | permissive | [
{
"docstring": "Override clean data to validate the id corresponds to a real Waypoint.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Override save to soft delete the waypoint.",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032129 | Implement the Python class `DeleteWaypointForm` described below.
Class description:
Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user.
Method signatures and docstrings:
- def clean(self): Override clean data to validate the id corresponds to a real Waypoint.
- def save(self, *a... | Implement the Python class `DeleteWaypointForm` described below.
Class description:
Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user.
Method signatures and docstrings:
- def clean(self): Override clean data to validate the id corresponds to a real Waypoint.
- def save(self, *a... | 0100435c5d5a5fd12133b376b305e8fa79ddb8f0 | <|skeleton|>
class DeleteWaypointForm:
"""Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user."""
def clean(self):
"""Override clean data to validate the id corresponds to a real Waypoint."""
<|body_0|>
def save(self, *args, **kwargs):
"""Overr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteWaypointForm:
"""Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user."""
def clean(self):
"""Override clean data to validate the id corresponds to a real Waypoint."""
self.cleaned_data = super(DeleteWaypointForm, self).clean()
waypoint =... | the_stack_v2_python_sparse | waypoints/forms.py | Oswaldinho24k/geo-csv | train | 0 |
c8a995b0cf927e0931eed03fa1d90ea59fa40170 | [
"self.func = func\nself.args = args\nself.kwargs = kwargs",
"print(f'Start func: {self.func.__name__} with arguments {(self.args, self.kwargs)}')\nself.func(*self.args, **self.kwargs)\nprint(f'Done func: {self.func.__name__} with result {self.func(*self.args, **self.kwargs)}')"
] | <|body_start_0|>
self.func = func
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
print(f'Start func: {self.func.__name__} with arguments {(self.args, self.kwargs)}')
self.func(*self.args, **self.kwargs)
print(f'Done func: {self.func.__name__} with ... | Задача, которую надо выполнить. В идеале, должно быть реализовано на достаточном уровне абстракции, чтобы можно было выполнять "неоднотипные" задачи | Task | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""Задача, которую надо выполнить. В идеале, должно быть реализовано на достаточном уровне абстракции, чтобы можно было выполнять "неоднотипные" задачи"""
def __init__(self, func, *args, **kwargs):
"""Пофантазируйте, как лучше инициализировать"""
<|body_0|>
def per... | stack_v2_sparse_classes_75kplus_train_072726 | 3,404 | no_license | [
{
"docstring": "Пофантазируйте, как лучше инициализировать",
"name": "__init__",
"signature": "def __init__(self, func, *args, **kwargs)"
},
{
"docstring": "Старт выполнения задачи",
"name": "perform",
"signature": "def perform(self)"
}
] | 2 | null | Implement the Python class `Task` described below.
Class description:
Задача, которую надо выполнить. В идеале, должно быть реализовано на достаточном уровне абстракции, чтобы можно было выполнять "неоднотипные" задачи
Method signatures and docstrings:
- def __init__(self, func, *args, **kwargs): Пофантазируйте, как ... | Implement the Python class `Task` described below.
Class description:
Задача, которую надо выполнить. В идеале, должно быть реализовано на достаточном уровне абстракции, чтобы можно было выполнять "неоднотипные" задачи
Method signatures and docstrings:
- def __init__(self, func, *args, **kwargs): Пофантазируйте, как ... | 6fac424dfdc2974481712b630ccf587128c84a47 | <|skeleton|>
class Task:
"""Задача, которую надо выполнить. В идеале, должно быть реализовано на достаточном уровне абстракции, чтобы можно было выполнять "неоднотипные" задачи"""
def __init__(self, func, *args, **kwargs):
"""Пофантазируйте, как лучше инициализировать"""
<|body_0|>
def per... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Task:
"""Задача, которую надо выполнить. В идеале, должно быть реализовано на достаточном уровне абстракции, чтобы можно было выполнять "неоднотипные" задачи"""
def __init__(self, func, *args, **kwargs):
"""Пофантазируйте, как лучше инициализировать"""
self.func = func
self.args =... | the_stack_v2_python_sparse | technoatom/homework_04/hw4_process_manager.py | alipniczkij/python | train | 0 |
8ce8a2ca00e9a3a64f0357fea66d4451de94b78a | [
"total, dir_infos = self.job_manager.get_job_list(offset=offset, limit=limit)\njob_infos = [self._dir_2_info(dir_info) for dir_info in dir_infos]\nreturn (total, job_infos)",
"job = self.job_manager.get_job(train_id)\nif job is None:\n raise TrainJobNotExistError(train_id)\nreturn self._job_2_meta(job)",
"in... | <|body_start_0|>
total, dir_infos = self.job_manager.get_job_list(offset=offset, limit=limit)
job_infos = [self._dir_2_info(dir_info) for dir_info in dir_infos]
return (total, job_infos)
<|end_body_0|>
<|body_start_1|>
job = self.job_manager.get_job(train_id)
if job is None:
... | Explain job list encapsulator. | ExplainJobEncap | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExplainJobEncap:
"""Explain job list encapsulator."""
def query_explain_jobs(self, offset, limit):
"""Query explain job list. Args: offset (int): Page offset. limit (int): Maximum number of items to be returned. Returns: tuple[int, list[Dict]], total number of jobs and job list."""
... | stack_v2_sparse_classes_75kplus_train_072727 | 3,607 | permissive | [
{
"docstring": "Query explain job list. Args: offset (int): Page offset. limit (int): Maximum number of items to be returned. Returns: tuple[int, list[Dict]], total number of jobs and job list.",
"name": "query_explain_jobs",
"signature": "def query_explain_jobs(self, offset, limit)"
},
{
"docst... | 5 | stack_v2_sparse_classes_30k_train_025614 | Implement the Python class `ExplainJobEncap` described below.
Class description:
Explain job list encapsulator.
Method signatures and docstrings:
- def query_explain_jobs(self, offset, limit): Query explain job list. Args: offset (int): Page offset. limit (int): Maximum number of items to be returned. Returns: tuple[... | Implement the Python class `ExplainJobEncap` described below.
Class description:
Explain job list encapsulator.
Method signatures and docstrings:
- def query_explain_jobs(self, offset, limit): Query explain job list. Args: offset (int): Page offset. limit (int): Maximum number of items to be returned. Returns: tuple[... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class ExplainJobEncap:
"""Explain job list encapsulator."""
def query_explain_jobs(self, offset, limit):
"""Query explain job list. Args: offset (int): Page offset. limit (int): Maximum number of items to be returned. Returns: tuple[int, list[Dict]], total number of jobs and job list."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExplainJobEncap:
"""Explain job list encapsulator."""
def query_explain_jobs(self, offset, limit):
"""Query explain job list. Args: offset (int): Page offset. limit (int): Maximum number of items to be returned. Returns: tuple[int, list[Dict]], total number of jobs and job list."""
total,... | the_stack_v2_python_sparse | mindinsight/explainer/encapsulator/explain_job_encap.py | mindspore-ai/mindinsight | train | 224 |
178931caa70bb5309ca3a6125cd5b47c13caae99 | [
"func_list = {}\nif entity not in func_list.keys():\n self.results = None\n return None\nres = []\nmore = dict()\nmore_gen = False\nfor x in func_list[entity]:\n res2 = x().query(query, page_size, offset)\n if len(res2) == page_size:\n more[x.__name__] = (True, offset + 1)\n more_gen = Tru... | <|body_start_0|>
func_list = {}
if entity not in func_list.keys():
self.results = None
return None
res = []
more = dict()
more_gen = False
for x in func_list[entity]:
res2 = x().query(query, page_size, offset)
if len(res2) =... | A class for collecting all the custom autocomplete functions for one entity. Attributes: - self.entity: (string) entity types - self.more: (boolean) if more results can be fetched (pagination) - self.page_size: (integer) page size - self.results: (list) results - self.query: (string) query string Methods: - self.more()... | CustomEntityAutocompletes | [
"MIT",
"CC-BY-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomEntityAutocompletes:
"""A class for collecting all the custom autocomplete functions for one entity. Attributes: - self.entity: (string) entity types - self.more: (boolean) if more results can be fetched (pagination) - self.page_size: (integer) page size - self.results: (list) results - sel... | stack_v2_sparse_classes_75kplus_train_072728 | 17,368 | permissive | [
{
"docstring": ":param entity: (string) entity type to fetch additional autocompletes for",
"name": "__init__",
"signature": "def __init__(self, entity, query, page_size=20, offset=0, *args, **kwargs)"
},
{
"docstring": "Function to retrieve more results.",
"name": "get_more",
"signature... | 2 | null | Implement the Python class `CustomEntityAutocompletes` described below.
Class description:
A class for collecting all the custom autocomplete functions for one entity. Attributes: - self.entity: (string) entity types - self.more: (boolean) if more results can be fetched (pagination) - self.page_size: (integer) page si... | Implement the Python class `CustomEntityAutocompletes` described below.
Class description:
A class for collecting all the custom autocomplete functions for one entity. Attributes: - self.entity: (string) entity types - self.more: (boolean) if more results can be fetched (pagination) - self.page_size: (integer) page si... | 508545fa5119e1895801cc02c33b62ee33518183 | <|skeleton|>
class CustomEntityAutocompletes:
"""A class for collecting all the custom autocomplete functions for one entity. Attributes: - self.entity: (string) entity types - self.more: (boolean) if more results can be fetched (pagination) - self.page_size: (integer) page size - self.results: (list) results - sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomEntityAutocompletes:
"""A class for collecting all the custom autocomplete functions for one entity. Attributes: - self.entity: (string) entity types - self.more: (boolean) if more results can be fetched (pagination) - self.page_size: (integer) page size - self.results: (list) results - self.query: (str... | the_stack_v2_python_sparse | apis_core/apis_entities/autocomplete3.py | acdh-oeaw/apis-core | train | 14 |
df2b2fb2f62b8780a8721d7042e3dc495d97928b | [
"result = super(SaleOrder, self).default_get(fields)\nif 'warehouse_id' in result:\n warehouse_obj = self.env['stock.warehouse']\n result['location_id'] = warehouse_obj.browse(result['warehouse_id']).lot_stock_id.id\nreturn result",
"location_obj = self.env['stock.location']\nlocation_id = self.warehouse_id... | <|body_start_0|>
result = super(SaleOrder, self).default_get(fields)
if 'warehouse_id' in result:
warehouse_obj = self.env['stock.warehouse']
result['location_id'] = warehouse_obj.browse(result['warehouse_id']).lot_stock_id.id
return result
<|end_body_0|>
<|body_start_1|... | SaleOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleOrder:
def default_get(self, fields):
"""set default value for location based on selected warehouse"""
<|body_0|>
def _onchange_warehouse_location_domain(self):
"""in case wharehouse change then we need to change location to default location of new selected whare... | stack_v2_sparse_classes_75kplus_train_072729 | 10,362 | no_license | [
{
"docstring": "set default value for location based on selected warehouse",
"name": "default_get",
"signature": "def default_get(self, fields)"
},
{
"docstring": "in case wharehouse change then we need to change location to default location of new selected wharehouse also set domain for child o... | 4 | stack_v2_sparse_classes_30k_train_048270 | Implement the Python class `SaleOrder` described below.
Class description:
Implement the SaleOrder class.
Method signatures and docstrings:
- def default_get(self, fields): set default value for location based on selected warehouse
- def _onchange_warehouse_location_domain(self): in case wharehouse change then we nee... | Implement the Python class `SaleOrder` described below.
Class description:
Implement the SaleOrder class.
Method signatures and docstrings:
- def default_get(self, fields): set default value for location based on selected warehouse
- def _onchange_warehouse_location_domain(self): in case wharehouse change then we nee... | 08cf67899ec54e49b2c131092324c291d8728a2d | <|skeleton|>
class SaleOrder:
def default_get(self, fields):
"""set default value for location based on selected warehouse"""
<|body_0|>
def _onchange_warehouse_location_domain(self):
"""in case wharehouse change then we need to change location to default location of new selected whare... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaleOrder:
def default_get(self, fields):
"""set default value for location based on selected warehouse"""
result = super(SaleOrder, self).default_get(fields)
if 'warehouse_id' in result:
warehouse_obj = self.env['stock.warehouse']
result['location_id'] = wareho... | the_stack_v2_python_sparse | almanna_custom/models/sale.py | mudathirdev/almanna-erp-project | train | 0 | |
063ad27c1ade72729125fd9bedb9778f9c6f89de | [
"try:\n connection = lcu.connect(os.path.expanduser(settings.riot_client_config))\nexcept IndexError:\n raise RiotConnectionException\nif connection == 'Ensure the client is running and that you supplied the correct path':\n raise RiotConnectionException\nself.kwargs = {'verify': False, 'auth': ('riot', co... | <|body_start_0|>
try:
connection = lcu.connect(os.path.expanduser(settings.riot_client_config))
except IndexError:
raise RiotConnectionException
if connection == 'Ensure the client is running and that you supplied the correct path':
raise RiotConnectionExcepti... | Connects to riot client and communicates with it | RiotConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiotConnection:
"""Connects to riot client and communicates with it"""
def get_connection(self, settings):
"""Parses connection url and port from lockfile"""
<|body_0|>
def get_connection_ft(self, settings):
"""Parses connection url and port from lockfile fault t... | stack_v2_sparse_classes_75kplus_train_072730 | 1,749 | permissive | [
{
"docstring": "Parses connection url and port from lockfile",
"name": "get_connection",
"signature": "def get_connection(self, settings)"
},
{
"docstring": "Parses connection url and port from lockfile fault tolerant version",
"name": "get_connection_ft",
"signature": "def get_connectio... | 2 | stack_v2_sparse_classes_30k_test_003001 | Implement the Python class `RiotConnection` described below.
Class description:
Connects to riot client and communicates with it
Method signatures and docstrings:
- def get_connection(self, settings): Parses connection url and port from lockfile
- def get_connection_ft(self, settings): Parses connection url and port ... | Implement the Python class `RiotConnection` described below.
Class description:
Connects to riot client and communicates with it
Method signatures and docstrings:
- def get_connection(self, settings): Parses connection url and port from lockfile
- def get_connection_ft(self, settings): Parses connection url and port ... | 61a96e4a4bfd19ab686a9706e74931fe71291330 | <|skeleton|>
class RiotConnection:
"""Connects to riot client and communicates with it"""
def get_connection(self, settings):
"""Parses connection url and port from lockfile"""
<|body_0|>
def get_connection_ft(self, settings):
"""Parses connection url and port from lockfile fault t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RiotConnection:
"""Connects to riot client and communicates with it"""
def get_connection(self, settings):
"""Parses connection url and port from lockfile"""
try:
connection = lcu.connect(os.path.expanduser(settings.riot_client_config))
except IndexError:
r... | the_stack_v2_python_sparse | connection/riot.py | LegendaryZone/auto_disenchanter | train | 1 |
c09aee19c9e8e313639202811ec33376407ee5e9 | [
"page = request.args.get('page', 1, type=int)\nactorsPagination = actor_service.get_actors(page, ACTORS_PER_PAGE)\nactors = actorsPagination.items\nformatted_actors = [actor.format() for actor in actors]\nif not len(actors):\n raise NotFound({'status': 404, 'description': 'No actors were found on page ' + str(pa... | <|body_start_0|>
page = request.args.get('page', 1, type=int)
actorsPagination = actor_service.get_actors(page, ACTORS_PER_PAGE)
actors = actorsPagination.items
formatted_actors = [actor.format() for actor in actors]
if not len(actors):
raise NotFound({'status': 404, ... | ActorList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActorList:
def get(payload, self):
"""get_actors: fetches actors Args: page (data type: int) Returns: returns an array of actors"""
<|body_0|>
def post(payload, self):
"""create_actor: creates a new actor Args: name (data type: str) age (data type: int) gender (data ... | stack_v2_sparse_classes_75kplus_train_072731 | 6,074 | no_license | [
{
"docstring": "get_actors: fetches actors Args: page (data type: int) Returns: returns an array of actors",
"name": "get",
"signature": "def get(payload, self)"
},
{
"docstring": "create_actor: creates a new actor Args: name (data type: str) age (data type: int) gender (data type: str) Returns:... | 2 | stack_v2_sparse_classes_30k_train_031795 | Implement the Python class `ActorList` described below.
Class description:
Implement the ActorList class.
Method signatures and docstrings:
- def get(payload, self): get_actors: fetches actors Args: page (data type: int) Returns: returns an array of actors
- def post(payload, self): create_actor: creates a new actor ... | Implement the Python class `ActorList` described below.
Class description:
Implement the ActorList class.
Method signatures and docstrings:
- def get(payload, self): get_actors: fetches actors Args: page (data type: int) Returns: returns an array of actors
- def post(payload, self): create_actor: creates a new actor ... | 74d74cef23dec296b342eb8b63471d8dc63a3ced | <|skeleton|>
class ActorList:
def get(payload, self):
"""get_actors: fetches actors Args: page (data type: int) Returns: returns an array of actors"""
<|body_0|>
def post(payload, self):
"""create_actor: creates a new actor Args: name (data type: str) age (data type: int) gender (data ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActorList:
def get(payload, self):
"""get_actors: fetches actors Args: page (data type: int) Returns: returns an array of actors"""
page = request.args.get('page', 1, type=int)
actorsPagination = actor_service.get_actors(page, ACTORS_PER_PAGE)
actors = actorsPagination.items
... | the_stack_v2_python_sparse | app/main/controller/actor_controller.py | fremfi/casting-agency-api-python-flask | train | 0 | |
bf8d87fcf4e2108e86661e1ceb4ecffadae9845d | [
"for page in range(1, self.settings.get('MAX_PAGE') + 1):\n url = self.base_url + str(page)\n yield Request(url=url, callback=self.parse, dont_filter=True)",
"item = CsdnMasterItem()\nitemlist = response.xpath(\".//div[@class='course_dl_list']\")\nfor items in itemlist:\n item['url'] = items.xpath('.//a/... | <|body_start_0|>
for page in range(1, self.settings.get('MAX_PAGE') + 1):
url = self.base_url + str(page)
yield Request(url=url, callback=self.parse, dont_filter=True)
<|end_body_0|>
<|body_start_1|>
item = CsdnMasterItem()
itemlist = response.xpath(".//div[@class='cours... | 此类继承CrawlSpider,负责主要的爬取功能 | MasterSpider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MasterSpider:
"""此类继承CrawlSpider,负责主要的爬取功能"""
def start_requests(self):
"""爬虫开始方法,通过对页数参数读取, 在for循环,再通过yield来创建一个Request并访问parse方法"""
<|body_0|>
def parse(self, response):
"""对具体爬取数据的操作"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for page in... | stack_v2_sparse_classes_75kplus_train_072732 | 1,293 | permissive | [
{
"docstring": "爬虫开始方法,通过对页数参数读取, 在for循环,再通过yield来创建一个Request并访问parse方法",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "对具体爬取数据的操作",
"name": "parse",
"signature": "def parse(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039834 | Implement the Python class `MasterSpider` described below.
Class description:
此类继承CrawlSpider,负责主要的爬取功能
Method signatures and docstrings:
- def start_requests(self): 爬虫开始方法,通过对页数参数读取, 在for循环,再通过yield来创建一个Request并访问parse方法
- def parse(self, response): 对具体爬取数据的操作 | Implement the Python class `MasterSpider` described below.
Class description:
此类继承CrawlSpider,负责主要的爬取功能
Method signatures and docstrings:
- def start_requests(self): 爬虫开始方法,通过对页数参数读取, 在for循环,再通过yield来创建一个Request并访问parse方法
- def parse(self, response): 对具体爬取数据的操作
<|skeleton|>
class MasterSpider:
"""此类继承CrawlSpider... | e851524917b60e7308172bc235597b7c578882cc | <|skeleton|>
class MasterSpider:
"""此类继承CrawlSpider,负责主要的爬取功能"""
def start_requests(self):
"""爬虫开始方法,通过对页数参数读取, 在for循环,再通过yield来创建一个Request并访问parse方法"""
<|body_0|>
def parse(self, response):
"""对具体爬取数据的操作"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MasterSpider:
"""此类继承CrawlSpider,负责主要的爬取功能"""
def start_requests(self):
"""爬虫开始方法,通过对页数参数读取, 在for循环,再通过yield来创建一个Request并访问parse方法"""
for page in range(1, self.settings.get('MAX_PAGE') + 1):
url = self.base_url + str(page)
yield Request(url=url, callback=self.parse... | the_stack_v2_python_sparse | 10th_week/homework/作业2/csdnMaster/csdnMaster/spiders/master.py | luhuadong/Python_Learning | train | 1 |
2cc4ec6e437fabb3f36f18555f2184c1dd3460ba | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | MsgTransferServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MsgTransferServicer:
"""Missing associated documentation comment in .proto file."""
def image_processor(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_server_utilization(self, request, context):
"""Missi... | stack_v2_sparse_classes_75kplus_train_072733 | 8,456 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "image_processor",
"signature": "def image_processor(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "get_server_utilization",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_train_038219 | Implement the Python class `MsgTransferServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def image_processor(self, request, context): Missing associated documentation comment in .proto file.
- def get_server_utilization(self, req... | Implement the Python class `MsgTransferServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def image_processor(self, request, context): Missing associated documentation comment in .proto file.
- def get_server_utilization(self, req... | 40b38190aeff5d5b970c8cbf43e8781634b38028 | <|skeleton|>
class MsgTransferServicer:
"""Missing associated documentation comment in .proto file."""
def image_processor(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_server_utilization(self, request, context):
"""Missi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MsgTransferServicer:
"""Missing associated documentation comment in .proto file."""
def image_processor(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implement... | the_stack_v2_python_sparse | backend_server/grpc_config/msg_transfer_pb2_grpc.py | AaspiralMoon/SmartEye | train | 0 |
4054cc7bb6b26dd8ee148fdd4f6089390f14e197 | [
"self.id = lot_id\nself.city = city\nself.streets = []\nself.parcels = []\nself.sides_of_street = []\nself.house_numbers = []\nself.building = None\nself.landmark = None\nself.positions_in_parcel = []\nself.neighboring_lots = set()\nself.house_number = None\nself.address = None\nself.street_address_is_on = None\nse... | <|body_start_0|>
self.id = lot_id
self.city = city
self.streets = []
self.parcels = []
self.sides_of_street = []
self.house_numbers = []
self.building = None
self.landmark = None
self.positions_in_parcel = []
self.neighboring_lots = set()
... | A lot on a block in a city, upon which buildings and houses get erected. | Lot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
<|body_0|>
def population(self):
"""Return the number of people living/working on the lot."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_072734 | 29,613 | no_license | [
{
"docstring": "Initialize a Lot object.",
"name": "__init__",
"signature": "def __init__(self, lot_id, city)"
},
{
"docstring": "Return the number of people living/working on the lot.",
"name": "population",
"signature": "def population(self)"
},
{
"docstring": "Attribute to thi... | 5 | stack_v2_sparse_classes_30k_train_026302 | Implement the Python class `Lot` described below.
Class description:
A lot on a block in a city, upon which buildings and houses get erected.
Method signatures and docstrings:
- def __init__(self, lot_id, city): Initialize a Lot object.
- def population(self): Return the number of people living/working on the lot.
- ... | Implement the Python class `Lot` described below.
Class description:
A lot on a block in a city, upon which buildings and houses get erected.
Method signatures and docstrings:
- def __init__(self, lot_id, city): Initialize a Lot object.
- def population(self): Return the number of people living/working on the lot.
- ... | 78a9df3ff66d4956f817397c82be0b4e4176e73d | <|skeleton|>
class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
<|body_0|>
def population(self):
"""Return the number of people living/working on the lot."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
self.id = lot_id
self.city = city
self.streets = []
self.parcels = []
self.sides_of_street = []
self... | the_stack_v2_python_sparse | places/city_planning.py | hanok2/national_pastime | train | 1 |
77bc4d1516e5f1126ec1d7323d8cf15d289fce7d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ClientUserAgent()",
"from .client_platform import ClientPlatform\nfrom .product_family import ProductFamily\nfrom .user_agent import UserAgent\nfrom .client_platform import ClientPlatform\nfrom .product_family import ProductFamily\nfro... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ClientUserAgent()
<|end_body_0|>
<|body_start_1|>
from .client_platform import ClientPlatform
from .product_family import ProductFamily
from .user_agent import UserAgent
... | ClientUserAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientUserAgent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClientUserAgent:
"""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 Ret... | stack_v2_sparse_classes_75kplus_train_072735 | 3,279 | 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: ClientUserAgent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_048354 | Implement the Python class `ClientUserAgent` described below.
Class description:
Implement the ClientUserAgent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClientUserAgent: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `ClientUserAgent` described below.
Class description:
Implement the ClientUserAgent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClientUserAgent: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ClientUserAgent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClientUserAgent:
"""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 Ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClientUserAgent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClientUserAgent:
"""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: ClientUs... | the_stack_v2_python_sparse | msgraph/generated/models/call_records/client_user_agent.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
976402db022bf67f63dfed5157ba4f203c6a85e9 | [
"super().__init__(netatmo_device.data_handler)\nself.entity_description = description\nself._module = netatmo_device.device\nself._id = self._module.entity_id\nself._publishers.extend([{'name': HOME, 'home_id': netatmo_device.device.home.entity_id, SIGNAL_NAME: netatmo_device.signal_name}])\nself._attr_name = f'{se... | <|body_start_0|>
super().__init__(netatmo_device.data_handler)
self.entity_description = description
self._module = netatmo_device.device
self._id = self._module.entity_id
self._publishers.extend([{'name': HOME, 'home_id': netatmo_device.device.home.entity_id, SIGNAL_NAME: netatm... | Implementation of a Netatmo sensor. | NetatmoSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetatmoSensor:
"""Implementation of a Netatmo sensor."""
def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def async_update_callback(self) -> None:
"""Update the entity'... | stack_v2_sparse_classes_75kplus_train_072736 | 25,750 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None"
},
{
"docstring": "Update the entity's state.",
"name": "async_update_callback",
"signature": "def async_upda... | 2 | stack_v2_sparse_classes_30k_train_001044 | Implement the Python class `NetatmoSensor` described below.
Class description:
Implementation of a Netatmo sensor.
Method signatures and docstrings:
- def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None: Initialize the sensor.
- def async_update_callback(self) -> Non... | Implement the Python class `NetatmoSensor` described below.
Class description:
Implementation of a Netatmo sensor.
Method signatures and docstrings:
- def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None: Initialize the sensor.
- def async_update_callback(self) -> Non... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class NetatmoSensor:
"""Implementation of a Netatmo sensor."""
def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def async_update_callback(self) -> None:
"""Update the entity'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetatmoSensor:
"""Implementation of a Netatmo sensor."""
def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None:
"""Initialize the sensor."""
super().__init__(netatmo_device.data_handler)
self.entity_description = description
... | the_stack_v2_python_sparse | homeassistant/components/netatmo/sensor.py | home-assistant/core | train | 35,501 |
e0c3d7ae4f53489584f7a75333680534438cc5c1 | [
"self.grid_r = r - 1\nself.grid_c = c - 1\nself.stop_cells = set(stop_cells)",
"path = [(0, 0)]\nwent_right: set = set()\nwent_down: set = set()\nr = 0\nc = 0\nwhile (r, c) != (self.grid_r, self.grid_c):\n if c < self.grid_c and (r, c) not in went_right and ((r, c + 1) not in self.stop_cells):\n went_ri... | <|body_start_0|>
self.grid_r = r - 1
self.grid_c = c - 1
self.stop_cells = set(stop_cells)
<|end_body_0|>
<|body_start_1|>
path = [(0, 0)]
went_right: set = set()
went_down: set = set()
r = 0
c = 0
while (r, c) != (self.grid_r, self.grid_c):
... | 8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom... | RobotInAGrid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RobotInAGrid:
"""8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for t... | stack_v2_sparse_classes_75kplus_train_072737 | 1,849 | no_license | [
{
"docstring": ":param r: rows in a grid :param c: cells in a grid",
"name": "__init__",
"signature": "def __init__(self, stop_cells, r, c)"
},
{
"docstring": "Algorithm to find a path for the robot from the top left to the bottom right. Algo: step right, if not possible, step left, if not possi... | 2 | stack_v2_sparse_classes_30k_test_002060 | Implement the Python class `RobotInAGrid` described below.
Class description:
8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. D... | Implement the Python class `RobotInAGrid` described below.
Class description:
8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. D... | 8ae84f276cd07ffdb9b742569a5e32809ecc6b29 | <|skeleton|>
class RobotInAGrid:
"""8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RobotInAGrid:
"""8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from... | the_stack_v2_python_sparse | pyquiz/ctci/dynamic/RobotInAGrid.py | DmitryPukhov/pyquiz | train | 0 |
f7a9f8b375a2cd5f90f1426b3804e6db584cc494 | [
"self._handover_dict = handover_dict\nself._handover_cond = handover_cond\nself._wait_timeout = 10.0",
"with self._handover_cond:\n while len(self._handover_dict) > 0:\n self._handover_cond.wait(self._wait_timeout)\n self._handover_dict['headers'] = None\n self._handover_dict['message'] = None\n ... | <|body_start_0|>
self._handover_dict = handover_dict
self._handover_cond = handover_cond
self._wait_timeout = 10.0
<|end_body_0|>
<|body_start_1|>
with self._handover_cond:
while len(self._handover_dict) > 0:
self._handover_cond.wait(self._wait_timeout)
... | A notification listener class for use by the Python `stomp` package. This is an internal class that does not need to be accessed or created by the user. An object of this class is automatically created by the :class:`~zhmcclient.NotificationReceiver` class, for its notification topic. Note: In the stomp examples, this ... | _NotificationListener | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _NotificationListener:
"""A notification listener class for use by the Python `stomp` package. This is an internal class that does not need to be accessed or created by the user. An object of this class is automatically created by the :class:`~zhmcclient.NotificationReceiver` class, for its notif... | stack_v2_sparse_classes_75kplus_train_072738 | 18,861 | permissive | [
{
"docstring": "Parameters: handover_dict (dict): Dictionary for handing over the notification header and message from this listener thread to the receiver thread. Must initially be an empty dictionary. handover_cond (threading.Condition): Condition object for handing over the notification from this listener th... | 4 | null | Implement the Python class `_NotificationListener` described below.
Class description:
A notification listener class for use by the Python `stomp` package. This is an internal class that does not need to be accessed or created by the user. An object of this class is automatically created by the :class:`~zhmcclient.Not... | Implement the Python class `_NotificationListener` described below.
Class description:
A notification listener class for use by the Python `stomp` package. This is an internal class that does not need to be accessed or created by the user. An object of this class is automatically created by the :class:`~zhmcclient.Not... | d6b22c08dc31c5c269af4c98d24b2a2529cf97dd | <|skeleton|>
class _NotificationListener:
"""A notification listener class for use by the Python `stomp` package. This is an internal class that does not need to be accessed or created by the user. An object of this class is automatically created by the :class:`~zhmcclient.NotificationReceiver` class, for its notif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _NotificationListener:
"""A notification listener class for use by the Python `stomp` package. This is an internal class that does not need to be accessed or created by the user. An object of this class is automatically created by the :class:`~zhmcclient.NotificationReceiver` class, for its notification topic... | the_stack_v2_python_sparse | zhmcclient/_notification.py | zhmcclient/python-zhmcclient | train | 41 |
27dad69a1eaa2ad8ccec04a293294ab7f135d9b1 | [
"if type(data) != np.ndarray or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = np.mean(data, axis=1).reshape(data.shape[0], 1)\nself.cov = np.matmul(data - self.mean, (data - self.mean)... | <|body_start_0|>
if type(data) != np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
self.mean = np.mean(data, axis=1).reshape(data.shape[0], 1)
se... | [summary] | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""[summary]"""
def __init__(self, data):
"""[summary] Args: data ([type]): [description] Raises: TypeError: [description] ValueError: [description]"""
<|body_0|>
def pdf(self, x):
"""[summary] Args: x ([type]): [description] Raises: TypeError: [desc... | stack_v2_sparse_classes_75kplus_train_072739 | 1,983 | no_license | [
{
"docstring": "[summary] Args: data ([type]): [description] Raises: TypeError: [description] ValueError: [description]",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "[summary] Args: x ([type]): [description] Raises: TypeError: [description] ValueError: [descrip... | 2 | stack_v2_sparse_classes_30k_train_011322 | Implement the Python class `MultiNormal` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, data): [summary] Args: data ([type]): [description] Raises: TypeError: [description] ValueError: [description]
- def pdf(self, x): [summary] Args: x ([type]): [description] Rai... | Implement the Python class `MultiNormal` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, data): [summary] Args: data ([type]): [description] Raises: TypeError: [description] ValueError: [description]
- def pdf(self, x): [summary] Args: x ([type]): [description] Rai... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class MultiNormal:
"""[summary]"""
def __init__(self, data):
"""[summary] Args: data ([type]): [description] Raises: TypeError: [description] ValueError: [description]"""
<|body_0|>
def pdf(self, x):
"""[summary] Args: x ([type]): [description] Raises: TypeError: [desc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNormal:
"""[summary]"""
def __init__(self, data):
"""[summary] Args: data ([type]): [description] Raises: TypeError: [description] ValueError: [description]"""
if type(data) != np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
73da9af6de3b7808e39dda6a46ebc24823c43e5a | [
"if n < 0:\n return None\ntmp = [0, 1]\nfor i in range(2, n + 1):\n tmp[i % 2] = tmp[0] + tmp[1]\nreturn tmp[n % 2] % 1000000007",
"if n <= 0:\n return 0\nif n == 1:\n return 1\nif n > 1:\n return self.fib1(n - 1) + self.fib1(n - 2)"
] | <|body_start_0|>
if n < 0:
return None
tmp = [0, 1]
for i in range(2, n + 1):
tmp[i % 2] = tmp[0] + tmp[1]
return tmp[n % 2] % 1000000007
<|end_body_0|>
<|body_start_1|>
if n <= 0:
return 0
if n == 1:
return 1
if n ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fib(self, n):
"""" 从下网上计算,保存中间项。时间复杂度是O(n)"""
<|body_0|>
def fib1(self, n):
"""" 递归法,时间复杂度是n的指数次方"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 0:
return None
tmp = [0, 1]
for i in range(2, n + 1):
... | stack_v2_sparse_classes_75kplus_train_072740 | 1,091 | no_license | [
{
"docstring": "\" 从下网上计算,保存中间项。时间复杂度是O(n)",
"name": "fib",
"signature": "def fib(self, n)"
},
{
"docstring": "\" 递归法,时间复杂度是n的指数次方",
"name": "fib1",
"signature": "def fib1(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042899 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, n): " 从下网上计算,保存中间项。时间复杂度是O(n)
- def fib1(self, n): " 递归法,时间复杂度是n的指数次方 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, n): " 从下网上计算,保存中间项。时间复杂度是O(n)
- def fib1(self, n): " 递归法,时间复杂度是n的指数次方
<|skeleton|>
class Solution:
def fib(self, n):
"""" 从下网上计算,保存中间项。时间复杂度是O(n)"""
... | 746d77e9bfbcb3877fefae9a915004b3bfbcc612 | <|skeleton|>
class Solution:
def fib(self, n):
"""" 从下网上计算,保存中间项。时间复杂度是O(n)"""
<|body_0|>
def fib1(self, n):
"""" 递归法,时间复杂度是n的指数次方"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def fib(self, n):
"""" 从下网上计算,保存中间项。时间复杂度是O(n)"""
if n < 0:
return None
tmp = [0, 1]
for i in range(2, n + 1):
tmp[i % 2] = tmp[0] + tmp[1]
return tmp[n % 2] % 1000000007
def fib1(self, n):
"""" 递归法,时间复杂度是n的指数次方"""
... | the_stack_v2_python_sparse | 剑指offer/第五遍/10-1.斐波那契数列.py | leilalu/algorithm | train | 0 | |
3b9223d319264e97597521239ae3efe167e2069e | [
"self.system = system\nself.devices = []\nself.group = {}",
"if dev_name not in self.devices:\n self.devices.append(dev_name)\ngroup_name = self.system.__dict__[dev_name]._group\nif group_name not in self.group.keys():\n self.group[group_name] = {}",
"if dev_name not in self.devices:\n self.system.Log.... | <|body_start_0|>
self.system = system
self.devices = []
self.group = {}
<|end_body_0|>
<|body_start_1|>
if dev_name not in self.devices:
self.devices.append(dev_name)
group_name = self.system.__dict__[dev_name]._group
if group_name not in self.group.keys():
... | Device Manager class. Maintains the loaded model list, groups and categories | DevMan | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DevMan:
"""Device Manager class. Maintains the loaded model list, groups and categories"""
def __init__(self, system=None):
"""constructor for DevMan class"""
<|body_0|>
def register_device(self, dev_name):
"""register a device to the device list"""
<|bod... | stack_v2_sparse_classes_75kplus_train_072741 | 1,921 | permissive | [
{
"docstring": "constructor for DevMan class",
"name": "__init__",
"signature": "def __init__(self, system=None)"
},
{
"docstring": "register a device to the device list",
"name": "register_device",
"signature": "def register_device(self, dev_name)"
},
{
"docstring": "register a ... | 4 | stack_v2_sparse_classes_30k_train_040723 | Implement the Python class `DevMan` described below.
Class description:
Device Manager class. Maintains the loaded model list, groups and categories
Method signatures and docstrings:
- def __init__(self, system=None): constructor for DevMan class
- def register_device(self, dev_name): register a device to the device ... | Implement the Python class `DevMan` described below.
Class description:
Device Manager class. Maintains the loaded model list, groups and categories
Method signatures and docstrings:
- def __init__(self, system=None): constructor for DevMan class
- def register_device(self, dev_name): register a device to the device ... | 769afa0ad85daf7a41d1434d44a47a72397e3627 | <|skeleton|>
class DevMan:
"""Device Manager class. Maintains the loaded model list, groups and categories"""
def __init__(self, system=None):
"""constructor for DevMan class"""
<|body_0|>
def register_device(self, dev_name):
"""register a device to the device list"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DevMan:
"""Device Manager class. Maintains the loaded model list, groups and categories"""
def __init__(self, system=None):
"""constructor for DevMan class"""
self.system = system
self.devices = []
self.group = {}
def register_device(self, dev_name):
"""regist... | the_stack_v2_python_sparse | andes/variables/devman.py | buaaqq/andes | train | 1 |
318a8baedc90511cd6ef2e621a549fed81cca1ae | [
"self.method = method\nself.batch_size = batch_size\nself.distance_metric = distance",
"if 'rand' in self.method.lower():\n self.experiments = rand(obj, self.batch_size, seed=seed)\nelif self.method.lower() == 'pam' or 'medoids' in self.method.lower():\n self.experiments = PAM(obj, self.batch_size, distance... | <|body_start_0|>
self.method = method
self.batch_size = batch_size
self.distance_metric = distance
<|end_body_0|>
<|body_start_1|>
if 'rand' in self.method.lower():
self.experiments = rand(obj, self.batch_size, seed=seed)
elif self.method.lower() == 'pam' or 'medoids... | Class represents different initialization schemes. Methods for selecting initial points on a user defined grid. | Init | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Init:
"""Class represents different initialization schemes. Methods for selecting initial points on a user defined grid."""
def __init__(self, method, batch_size, distance='gower'):
"""Parameters ---------- method : str Sampling method. Opions include: 'random', 'PAM', 'k-means', and... | stack_v2_sparse_classes_75kplus_train_072742 | 11,651 | permissive | [
{
"docstring": "Parameters ---------- method : str Sampling method. Opions include: 'random', 'PAM', 'k-means', and 'external'. batch_size : int Number of points to select. distance_metric : str Distance metric to be used with PAM. Options include: 'gower', 'euclidean', and 'euclidean_square'.",
"name": "__... | 3 | stack_v2_sparse_classes_30k_train_037002 | Implement the Python class `Init` described below.
Class description:
Class represents different initialization schemes. Methods for selecting initial points on a user defined grid.
Method signatures and docstrings:
- def __init__(self, method, batch_size, distance='gower'): Parameters ---------- method : str Samplin... | Implement the Python class `Init` described below.
Class description:
Class represents different initialization schemes. Methods for selecting initial points on a user defined grid.
Method signatures and docstrings:
- def __init__(self, method, batch_size, distance='gower'): Parameters ---------- method : str Samplin... | 1b51e4e5042afc03a9d1413b9d6eca3002a74dba | <|skeleton|>
class Init:
"""Class represents different initialization schemes. Methods for selecting initial points on a user defined grid."""
def __init__(self, method, batch_size, distance='gower'):
"""Parameters ---------- method : str Sampling method. Opions include: 'random', 'PAM', 'k-means', and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Init:
"""Class represents different initialization schemes. Methods for selecting initial points on a user defined grid."""
def __init__(self, method, batch_size, distance='gower'):
"""Parameters ---------- method : str Sampling method. Opions include: 'random', 'PAM', 'k-means', and 'external'. ... | the_stack_v2_python_sparse | edbo/init_scheme.py | beef-broccoli/edbo | train | 0 |
96f8ea0287950dde7f64d10e9acb3f6b736884ad | [
"self._attr_unique_id = uid\nif entry is not None:\n self._attr_device_class = try_parse_enum(SensorDeviceClass, entry.original_device_class)\n self._attr_entity_category = entry.entity_category\n self._attr_name = entry.name\n self._attr_native_unit_of_measurement = entry.unit_of_measurement\nelse:\n ... | <|body_start_0|>
self._attr_unique_id = uid
if entry is not None:
self._attr_device_class = try_parse_enum(SensorDeviceClass, entry.original_device_class)
self._attr_entity_category = entry.entity_category
self._attr_name = entry.name
self._attr_native_uni... | Representation of a ONVIF sensor event. | ONVIFSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ONVIFSensor:
"""Representation of a ONVIF sensor event."""
def __init__(self, uid, device: ONVIFDevice, entry: er.RegistryEntry | None=None) -> None:
"""Initialize the ONVIF binary sensor."""
<|body_0|>
def native_value(self) -> StateType | date | datetime | Decimal:
... | stack_v2_sparse_classes_75kplus_train_072743 | 3,938 | permissive | [
{
"docstring": "Initialize the ONVIF binary sensor.",
"name": "__init__",
"signature": "def __init__(self, uid, device: ONVIFDevice, entry: er.RegistryEntry | None=None) -> None"
},
{
"docstring": "Return the value reported by the sensor.",
"name": "native_value",
"signature": "def nativ... | 3 | null | Implement the Python class `ONVIFSensor` described below.
Class description:
Representation of a ONVIF sensor event.
Method signatures and docstrings:
- def __init__(self, uid, device: ONVIFDevice, entry: er.RegistryEntry | None=None) -> None: Initialize the ONVIF binary sensor.
- def native_value(self) -> StateType ... | Implement the Python class `ONVIFSensor` described below.
Class description:
Representation of a ONVIF sensor event.
Method signatures and docstrings:
- def __init__(self, uid, device: ONVIFDevice, entry: er.RegistryEntry | None=None) -> None: Initialize the ONVIF binary sensor.
- def native_value(self) -> StateType ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ONVIFSensor:
"""Representation of a ONVIF sensor event."""
def __init__(self, uid, device: ONVIFDevice, entry: er.RegistryEntry | None=None) -> None:
"""Initialize the ONVIF binary sensor."""
<|body_0|>
def native_value(self) -> StateType | date | datetime | Decimal:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ONVIFSensor:
"""Representation of a ONVIF sensor event."""
def __init__(self, uid, device: ONVIFDevice, entry: er.RegistryEntry | None=None) -> None:
"""Initialize the ONVIF binary sensor."""
self._attr_unique_id = uid
if entry is not None:
self._attr_device_class = tr... | the_stack_v2_python_sparse | homeassistant/components/onvif/sensor.py | home-assistant/core | train | 35,501 |
c00017e73066951e375922061dc60b06c02e7fde | [
"odm = app.odm()\npermission_name = 'org-admin-%s' % organisation.username\ndescription = 'Admin permissions for %s organisation' % organisation.username\nresource = 'organisation:%s' % organisation.username\npermission_policy = {'resource': resource, 'action': ['read', 'create', 'update', 'delete']}\ngroup = sessi... | <|body_start_0|>
odm = app.odm()
permission_name = 'org-admin-%s' % organisation.username
description = 'Admin permissions for %s organisation' % organisation.username
resource = 'organisation:%s' % organisation.username
permission_policy = {'resource': resource, 'action': ['read... | _Organisation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Organisation:
def create(app, session, organisation):
"""Called when a new organisation is being added to the database. Implementation creates a group and permission for administrators of the organisation. It also makes the creator of the organisation an administrator. :param session: S... | stack_v2_sparse_classes_75kplus_train_072744 | 4,802 | no_license | [
{
"docstring": "Called when a new organisation is being added to the database. Implementation creates a group and permission for administrators of the organisation. It also makes the creator of the organisation an administrator. :param session: SQLAlchemy session :param organisation: User model instance",
"... | 2 | stack_v2_sparse_classes_30k_train_009034 | Implement the Python class `_Organisation` described below.
Class description:
Implement the _Organisation class.
Method signatures and docstrings:
- def create(app, session, organisation): Called when a new organisation is being added to the database. Implementation creates a group and permission for administrators ... | Implement the Python class `_Organisation` described below.
Class description:
Implement the _Organisation class.
Method signatures and docstrings:
- def create(app, session, organisation): Called when a new organisation is being added to the database. Implementation creates a group and permission for administrators ... | 2ac09e31ebe54dbecd46935818b089a4b8428354 | <|skeleton|>
class _Organisation:
def create(app, session, organisation):
"""Called when a new organisation is being added to the database. Implementation creates a group and permission for administrators of the organisation. It also makes the creator of the organisation an administrator. :param session: S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Organisation:
def create(app, session, organisation):
"""Called when a new organisation is being added to the database. Implementation creates a group and permission for administrators of the organisation. It also makes the creator of the organisation an administrator. :param session: SQLAlchemy sess... | the_stack_v2_python_sparse | venv/Lib/site-packages/lux/extensions/organisations/events.py | Sarveshr49/ProInternSML | train | 0 | |
07d26e6082d73417add3b0feaf68f9e190f3f778 | [
"stack = []\ndummy = Node(0, None, None, None)\ndummy.next = head\ncur = head\nwhile cur:\n if cur.child:\n stack.append(cur.next)\n cur.next = cur.child\n cur.child.prev = cur\n cur.child = None\n if not cur.next and stack:\n connect = stack.pop()\n cur.next = connec... | <|body_start_0|>
stack = []
dummy = Node(0, None, None, None)
dummy.next = head
cur = head
while cur:
if cur.child:
stack.append(cur.next)
cur.next = cur.child
cur.child.prev = cur
cur.child = None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, head):
""":type head: Node :rtype: Node 864MS"""
<|body_0|>
def flatten_1(self, head):
""":type head: Node :rtype: Node 848MS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = []
dummy = Node(0, None, None, ... | stack_v2_sparse_classes_75kplus_train_072745 | 2,365 | no_license | [
{
"docstring": ":type head: Node :rtype: Node 864MS",
"name": "flatten",
"signature": "def flatten(self, head)"
},
{
"docstring": ":type head: Node :rtype: Node 848MS",
"name": "flatten_1",
"signature": "def flatten_1(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052550 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, head): :type head: Node :rtype: Node 864MS
- def flatten_1(self, head): :type head: Node :rtype: Node 848MS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, head): :type head: Node :rtype: Node 864MS
- def flatten_1(self, head): :type head: Node :rtype: Node 848MS
<|skeleton|>
class Solution:
def flatten(self,... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def flatten(self, head):
""":type head: Node :rtype: Node 864MS"""
<|body_0|>
def flatten_1(self, head):
""":type head: Node :rtype: Node 848MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def flatten(self, head):
""":type head: Node :rtype: Node 864MS"""
stack = []
dummy = Node(0, None, None, None)
dummy.next = head
cur = head
while cur:
if cur.child:
stack.append(cur.next)
cur.next = cur.chil... | the_stack_v2_python_sparse | FlattenAMultilevelDoublyLinkedList_MID_430.py | 953250587/leetcode-python | train | 2 | |
5b31d4610f2d6930732c32e4a0ad13f831a8f5e9 | [
"try:\n with open(fname, 'r') as f:\n data = json.load(f)\n self.db = data\nexcept IOError:\n raise FileStorageError('Could not open {0!s} for reading'.format(fname))\nexcept json.errors.JSONDecodeError as e:\n print(e)\n raise\nreturn self.db",
"try:\n if data is None:\n data = se... | <|body_start_0|>
try:
with open(fname, 'r') as f:
data = json.load(f)
self.db = data
except IOError:
raise FileStorageError('Could not open {0!s} for reading'.format(fname))
except json.errors.JSONDecodeError as e:
print(e)
... | FileJson | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileJson:
def read(self, fname):
"""Reads a Json file in: file name out: length of file, dictionary"""
<|body_0|>
def write(self, fname, data=None):
"""Writes a Json file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
with open(fna... | stack_v2_sparse_classes_75kplus_train_072746 | 5,142 | permissive | [
{
"docstring": "Reads a Json file in: file name out: length of file, dictionary",
"name": "read",
"signature": "def read(self, fname)"
},
{
"docstring": "Writes a Json file",
"name": "write",
"signature": "def write(self, fname, data=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006019 | Implement the Python class `FileJson` described below.
Class description:
Implement the FileJson class.
Method signatures and docstrings:
- def read(self, fname): Reads a Json file in: file name out: length of file, dictionary
- def write(self, fname, data=None): Writes a Json file | Implement the Python class `FileJson` described below.
Class description:
Implement the FileJson class.
Method signatures and docstrings:
- def read(self, fname): Reads a Json file in: file name out: length of file, dictionary
- def write(self, fname, data=None): Writes a Json file
<|skeleton|>
class FileJson:
... | a809593a894d8e591e992455a01aa73d8f7b7981 | <|skeleton|>
class FileJson:
def read(self, fname):
"""Reads a Json file in: file name out: length of file, dictionary"""
<|body_0|>
def write(self, fname, data=None):
"""Writes a Json file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileJson:
def read(self, fname):
"""Reads a Json file in: file name out: length of file, dictionary"""
try:
with open(fname, 'r') as f:
data = json.load(f)
self.db = data
except IOError:
raise FileStorageError('Could not open {0!s} fo... | the_stack_v2_python_sparse | pygecko/file_storage.py | gecko-robotics/pygecko | train | 3 | |
53a00faa8cd3ac237bac05083898745097c53dc6 | [
"self.a = a\nself.t = t\nself.l = l\nself.r = r\nself.k = k\nself.lazy = [0] * len(self.t)\nself.Node(self.l, self.r, self.k)",
"if l == r:\n self.t[k] = self.a[l]\n return t[k]\nelse:\n m = l + r >> 1\n lmax = self.Node(l, m, k << 1)\n rmax = self.Node(m + 1, r, k << 1 | 1)\n self.t[k] = max(lm... | <|body_start_0|>
self.a = a
self.t = t
self.l = l
self.r = r
self.k = k
self.lazy = [0] * len(self.t)
self.Node(self.l, self.r, self.k)
<|end_body_0|>
<|body_start_1|>
if l == r:
self.t[k] = self.a[l]
return t[k]
else:
... | segment_tree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class segment_tree:
def __init__(self, k, l, r, a, t):
"""l,r是所有节点的区间,k是线段树root下标(1 层次遍历),a是真实结点,t是线段树(记录每个区间的最大值)"""
<|body_0|>
def Node(self, l, r, k):
"""k是线段树root下标 线段树中的叶子节点都是真实结点 非叶子节点都是虚拟节点 l,r是所有结点区间"""
<|body_1|>
def update_plot(self, p, v, l, r, k):
... | stack_v2_sparse_classes_75kplus_train_072747 | 5,141 | no_license | [
{
"docstring": "l,r是所有节点的区间,k是线段树root下标(1 层次遍历),a是真实结点,t是线段树(记录每个区间的最大值)",
"name": "__init__",
"signature": "def __init__(self, k, l, r, a, t)"
},
{
"docstring": "k是线段树root下标 线段树中的叶子节点都是真实结点 非叶子节点都是虚拟节点 l,r是所有结点区间",
"name": "Node",
"signature": "def Node(self, l, r, k)"
},
{
"doc... | 6 | null | Implement the Python class `segment_tree` described below.
Class description:
Implement the segment_tree class.
Method signatures and docstrings:
- def __init__(self, k, l, r, a, t): l,r是所有节点的区间,k是线段树root下标(1 层次遍历),a是真实结点,t是线段树(记录每个区间的最大值)
- def Node(self, l, r, k): k是线段树root下标 线段树中的叶子节点都是真实结点 非叶子节点都是虚拟节点 l,r是所有结点区间
... | Implement the Python class `segment_tree` described below.
Class description:
Implement the segment_tree class.
Method signatures and docstrings:
- def __init__(self, k, l, r, a, t): l,r是所有节点的区间,k是线段树root下标(1 层次遍历),a是真实结点,t是线段树(记录每个区间的最大值)
- def Node(self, l, r, k): k是线段树root下标 线段树中的叶子节点都是真实结点 非叶子节点都是虚拟节点 l,r是所有结点区间
... | 49ede1adb863075c925e90b93808e7ced317dbca | <|skeleton|>
class segment_tree:
def __init__(self, k, l, r, a, t):
"""l,r是所有节点的区间,k是线段树root下标(1 层次遍历),a是真实结点,t是线段树(记录每个区间的最大值)"""
<|body_0|>
def Node(self, l, r, k):
"""k是线段树root下标 线段树中的叶子节点都是真实结点 非叶子节点都是虚拟节点 l,r是所有结点区间"""
<|body_1|>
def update_plot(self, p, v, l, r, k):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class segment_tree:
def __init__(self, k, l, r, a, t):
"""l,r是所有节点的区间,k是线段树root下标(1 层次遍历),a是真实结点,t是线段树(记录每个区间的最大值)"""
self.a = a
self.t = t
self.l = l
self.r = r
self.k = k
self.lazy = [0] * len(self.t)
self.Node(self.l, self.r, self.k)
def Node(s... | the_stack_v2_python_sparse | lh_algorithm/lh_algorithm_segment_tree.py | kiddliao/lh_CODE | train | 1 | |
4eaf959e6e238a9044869b45cd495ded070f94fa | [
"if r >= N or r < 0 or c < 0 or (c >= N):\n return 0\nif K == 0:\n return 1\nelse:\n explore = [[-2, -1], [-1, -2], [-2, 1], [-1, 2], [2, -1], [1, -2], [2, 1], [1, 2]]\n tot_prob = 0\n for xd, yd in explore:\n v = self.knightProbability(N, K - 1, r + xd, c + yd)\n tot_prob += v\n ret... | <|body_start_0|>
if r >= N or r < 0 or c < 0 or (c >= N):
return 0
if K == 0:
return 1
else:
explore = [[-2, -1], [-1, -2], [-2, 1], [-1, 2], [2, -1], [1, -2], [2, 1], [1, 2]]
tot_prob = 0
for xd, yd in explore:
v = self... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def knightProbability_bf(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_0|>
def knightProbability(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_072748 | 1,548 | no_license | [
{
"docstring": ":type N: int :type K: int :type r: int :type c: int :rtype: float",
"name": "knightProbability_bf",
"signature": "def knightProbability_bf(self, N, K, r, c)"
},
{
"docstring": ":type N: int :type K: int :type r: int :type c: int :rtype: float",
"name": "knightProbability",
... | 2 | stack_v2_sparse_classes_30k_train_029253 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightProbability_bf(self, N, K, r, c): :type N: int :type K: int :type r: int :type c: int :rtype: float
- def knightProbability(self, N, K, r, c): :type N: int :type K: int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightProbability_bf(self, N, K, r, c): :type N: int :type K: int :type r: int :type c: int :rtype: float
- def knightProbability(self, N, K, r, c): :type N: int :type K: int... | b3a8a4db43f1d8620b70d54dd032e37b1eae7947 | <|skeleton|>
class Solution:
def knightProbability_bf(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_0|>
def knightProbability(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def knightProbability_bf(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
if r >= N or r < 0 or c < 0 or (c >= N):
return 0
if K == 0:
return 1
else:
explore = [[-2, -1], [-1, -2], [-2, 1], ... | the_stack_v2_python_sparse | Leetcode/Medium/knight_prob.py | rajaditya-m/Interview-Prep | train | 0 | |
3223746aa253a2d804635722c639005a0aedba22 | [
"super(Network, self).__init__()\nself.feature = NoisyLinear(in_dim[0], 128)\nself.noisy_layer1 = NoisyLinear(128, 128)\nself.noisy_layer2 = NoisyLinear(128, out_dim)",
"feature = F.relu(self.feature(x))\nhidden = F.relu(self.noisy_layer1(feature))\nout = self.noisy_layer2(hidden)\nreturn out",
"self.feature.re... | <|body_start_0|>
super(Network, self).__init__()
self.feature = NoisyLinear(in_dim[0], 128)
self.noisy_layer1 = NoisyLinear(128, 128)
self.noisy_layer2 = NoisyLinear(128, out_dim)
<|end_body_0|>
<|body_start_1|>
feature = F.relu(self.feature(x))
hidden = F.relu(self.nois... | Network | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
def __init__(self, in_dim: int, out_dim: int):
"""Initialization."""
<|body_0|>
def forward(self, x: torch.Tensor, dueling: bool) -> torch.Tensor:
"""Forward method implementation."""
<|body_1|>
def reset_noise(self):
"""Reset all noisy ... | stack_v2_sparse_classes_75kplus_train_072749 | 16,237 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, in_dim: int, out_dim: int)"
},
{
"docstring": "Forward method implementation.",
"name": "forward",
"signature": "def forward(self, x: torch.Tensor, dueling: bool) -> torch.Tensor"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_023507 | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, in_dim: int, out_dim: int): Initialization.
- def forward(self, x: torch.Tensor, dueling: bool) -> torch.Tensor: Forward method implementation.
- def reset_noise... | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, in_dim: int, out_dim: int): Initialization.
- def forward(self, x: torch.Tensor, dueling: bool) -> torch.Tensor: Forward method implementation.
- def reset_noise... | 027decb59ce97cc7c9d86aba3af9e21b390e4286 | <|skeleton|>
class Network:
def __init__(self, in_dim: int, out_dim: int):
"""Initialization."""
<|body_0|>
def forward(self, x: torch.Tensor, dueling: bool) -> torch.Tensor:
"""Forward method implementation."""
<|body_1|>
def reset_noise(self):
"""Reset all noisy ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Network:
def __init__(self, in_dim: int, out_dim: int):
"""Initialization."""
super(Network, self).__init__()
self.feature = NoisyLinear(in_dim[0], 128)
self.noisy_layer1 = NoisyLinear(128, 128)
self.noisy_layer2 = NoisyLinear(128, out_dim)
def forward(self, x: tor... | the_stack_v2_python_sparse | CybORG/CybORG/Agents/MyDQNAgent/nerual_network.py | yyzpiero/AutomaticCyberOperations | train | 0 | |
c418ec166e1284e0d99225df099e1d7cc6ed9c54 | [
"prefix_function = [0] * len(pattern)\nborder = 0\nfor i in range(1, len(pattern)):\n while border > 0 and pattern[i] != pattern[border]:\n border = prefix_function[border - 1]\n if pattern[i] == pattern[border]:\n border += 1\n else:\n border = 0\n prefix_function[i] = border\nretu... | <|body_start_0|>
prefix_function = [0] * len(pattern)
border = 0
for i in range(1, len(pattern)):
while border > 0 and pattern[i] != pattern[border]:
border = prefix_function[border - 1]
if pattern[i] == pattern[border]:
border += 1
... | Util | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border ... | stack_v2_sparse_classes_75kplus_train_072750 | 3,748 | no_license | [
{
"docstring": "Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border of 'ababab' 'ab' is not a border of 'ab' Definition: The... | 3 | stack_v2_sparse_classes_30k_train_006903 | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def _compute_prefix_function(pattern): Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the ... | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def _compute_prefix_function(pattern): Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the ... | 01dd6f0dadf62a520bcafafddf7bf2b79e8e2603 | <|skeleton|>
class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border of 'ababab' 'a... | the_stack_v2_python_sparse | course4-strings/assignments/assignment_003_suffix_array_matching/suffix_array_matching_with_kmp.py | dmitri-mamrukov/coursera-data-structures-and-algorithms | train | 1 | |
a811aec72e13d81328dc4a72fbd7c7f6f4d023ee | [
"if max_id:\n assert max_id == triples_factory.num_entities\nmapped_triples = triples_factory.mapped_triples\nif triples_factory.create_inverse_triples:\n mapped_triples = mapped_triples[mapped_triples[:, 1] < triples_factory.real_num_relations]\ntoken_representations, token_representations_kwargs, num_tokens... | <|body_start_0|>
if max_id:
assert max_id == triples_factory.num_entities
mapped_triples = triples_factory.mapped_triples
if triples_factory.create_inverse_triples:
mapped_triples = mapped_triples[mapped_triples[:, 1] < triples_factory.real_num_relations]
token_re... | Basic implementation of node piece decomposition [galkin2021]_. .. math :: x_e = agg(\\{T[t] \\mid t \\in tokens(e) \\}) where $T$ are token representations, $tokens$ selects a fixed number of $k$ tokens for each entity, and $agg$ is an aggregation function, which aggregates the individual token representations to a si... | NodePieceRepresentation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodePieceRepresentation:
"""Basic implementation of node piece decomposition [galkin2021]_. .. math :: x_e = agg(\\{T[t] \\mid t \\in tokens(e) \\}) where $T$ are token representations, $tokens$ selects a fixed number of $k$ tokens for each entity, and $agg$ is an aggregation function, which aggr... | stack_v2_sparse_classes_75kplus_train_072751 | 14,848 | permissive | [
{
"docstring": "Initialize the representation. :param triples_factory: the triples factory :param token_representations: the token representation specification, or pre-instantiated representation module. :param token_representations_kwargs: additional keyword-based parameters :param tokenizers: the tokenizer to... | 2 | null | Implement the Python class `NodePieceRepresentation` described below.
Class description:
Basic implementation of node piece decomposition [galkin2021]_. .. math :: x_e = agg(\\{T[t] \\mid t \\in tokens(e) \\}) where $T$ are token representations, $tokens$ selects a fixed number of $k$ tokens for each entity, and $agg$... | Implement the Python class `NodePieceRepresentation` described below.
Class description:
Basic implementation of node piece decomposition [galkin2021]_. .. math :: x_e = agg(\\{T[t] \\mid t \\in tokens(e) \\}) where $T$ are token representations, $tokens$ selects a fixed number of $k$ tokens for each entity, and $agg$... | 5ff3597b18ab9a220e34361d3c3f262060811df1 | <|skeleton|>
class NodePieceRepresentation:
"""Basic implementation of node piece decomposition [galkin2021]_. .. math :: x_e = agg(\\{T[t] \\mid t \\in tokens(e) \\}) where $T$ are token representations, $tokens$ selects a fixed number of $k$ tokens for each entity, and $agg$ is an aggregation function, which aggr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodePieceRepresentation:
"""Basic implementation of node piece decomposition [galkin2021]_. .. math :: x_e = agg(\\{T[t] \\mid t \\in tokens(e) \\}) where $T$ are token representations, $tokens$ selects a fixed number of $k$ tokens for each entity, and $agg$ is an aggregation function, which aggregates the in... | the_stack_v2_python_sparse | src/pykeen/nn/node_piece/representation.py | pykeen/pykeen | train | 1,308 |
0fac5469083a321d9b632966bd6c63b802241acb | [
"self.children = {}\nself.value = None\nself.is_terminal = False",
"if word:\n character, word = (word[0], word[1:])\n child = None\n if character in self.children:\n child = self.children[character]\n else:\n child = Trie()\n child.value = character\n if len(word) == 0:\n ... | <|body_start_0|>
self.children = {}
self.value = None
self.is_terminal = False
<|end_body_0|>
<|body_start_1|>
if word:
character, word = (word[0], word[1:])
child = None
if character in self.children:
child = self.children[character]
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: None"""
<|body_1|>
def search(self, word):
"""Returns if the word is in the trie. :ty... | stack_v2_sparse_classes_75kplus_train_072752 | 1,993 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie. :type word: str :rtype: None",
"name": "insert",
"signature": "def insert(self, word)"
},
{
"docstring": "Returns if the w... | 4 | stack_v2_sparse_classes_30k_train_015650 | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: None
- def search(self, word): Returns if the wor... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: None
- def search(self, word): Returns if the wor... | 52d71a93de7f002ac887a82c947e1e32a3e7255f | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: None"""
<|body_1|>
def search(self, word):
"""Returns if the word is in the trie. :ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trie:
def __init__(self):
"""Initialize your data structure here."""
self.children = {}
self.value = None
self.is_terminal = False
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: None"""
if word:
character, word ... | the_stack_v2_python_sparse | implement-trie-prefix-tree/solution.py | code-in-public/leetcode | train | 3 | |
1d2d1744e5a148ef9eed31379a105a8ca2fe55b9 | [
"title = item.css('.geeklist_item_title')\nfor url in title.xpath('.//a/@href').extract():\n bgg_id = extract_bgg_id(response.urljoin(url))\n if bgg_id:\n break\nelse:\n return None\nif bgg_id in self.exclude_bgg_ids:\n return None\nassert bgg_id\nldr = GameLoader(item=GameItem(bgg_id=bgg_id, **k... | <|body_start_0|>
title = item.css('.geeklist_item_title')
for url in title.xpath('.//a/@href').extract():
bgg_id = extract_bgg_id(response.urljoin(url))
if bgg_id:
break
else:
return None
if bgg_id in self.exclude_bgg_ids:
r... | BoardGameGeek GeekList spider. | BggGeekListSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BggGeekListSpider:
"""BoardGameGeek GeekList spider."""
def parse_game(self, item, response, **kwargs):
"""Parse game."""
<|body_0|>
def parse_geeklist(self, item, response, **kwargs):
"""Parse geeklist."""
<|body_1|>
def parse_item(self, item, respo... | stack_v2_sparse_classes_75kplus_train_072753 | 3,969 | permissive | [
{
"docstring": "Parse game.",
"name": "parse_game",
"signature": "def parse_game(self, item, response, **kwargs)"
},
{
"docstring": "Parse geeklist.",
"name": "parse_geeklist",
"signature": "def parse_geeklist(self, item, response, **kwargs)"
},
{
"docstring": "Decide on the item... | 4 | stack_v2_sparse_classes_30k_train_048864 | Implement the Python class `BggGeekListSpider` described below.
Class description:
BoardGameGeek GeekList spider.
Method signatures and docstrings:
- def parse_game(self, item, response, **kwargs): Parse game.
- def parse_geeklist(self, item, response, **kwargs): Parse geeklist.
- def parse_item(self, item, response,... | Implement the Python class `BggGeekListSpider` described below.
Class description:
BoardGameGeek GeekList spider.
Method signatures and docstrings:
- def parse_game(self, item, response, **kwargs): Parse game.
- def parse_geeklist(self, item, response, **kwargs): Parse geeklist.
- def parse_item(self, item, response,... | 7adb07f5133a8d7cea93c10032b49403a9ac9f8b | <|skeleton|>
class BggGeekListSpider:
"""BoardGameGeek GeekList spider."""
def parse_game(self, item, response, **kwargs):
"""Parse game."""
<|body_0|>
def parse_geeklist(self, item, response, **kwargs):
"""Parse geeklist."""
<|body_1|>
def parse_item(self, item, respo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BggGeekListSpider:
"""BoardGameGeek GeekList spider."""
def parse_game(self, item, response, **kwargs):
"""Parse game."""
title = item.css('.geeklist_item_title')
for url in title.xpath('.//a/@href').extract():
bgg_id = extract_bgg_id(response.urljoin(url))
... | the_stack_v2_python_sparse | board_game_scraper/spiders/bgg_geeklist.py | recommend-games/board-game-scraper | train | 21 |
3f7a9862b6ba9bf91123688fb916257987da567a | [
"start, end = field\naffine_sta = lambda x: max(0, stride * x - padding_size)\naffine_end = lambda x: min(observe_size, stride * x + kernel_size - 1 - padding_size)\nreturn (affine_sta(start), affine_end(end))",
"top_left, bottom_right = field\naffine_tl = lambda x: max(0, stride * x - padding_size)\ntop_left_new... | <|body_start_0|>
start, end = field
affine_sta = lambda x: max(0, stride * x - padding_size)
affine_end = lambda x: min(observe_size, stride * x + kernel_size - 1 - padding_size)
return (affine_sta(start), affine_end(end))
<|end_body_0|>
<|body_start_1|>
top_left, bottom_right =... | Deconv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deconv:
def get_observation1d(field, kernel_size, stride, padding_size, observe_size):
"""get observation field base on a given field, and some convLayer parameters :param field: Tuple, (start, end): eg: (1,5), it means a stripe from fmap[1] to fmap[5] :param: kernel_size: int :param: st... | stack_v2_sparse_classes_75kplus_train_072754 | 10,788 | no_license | [
{
"docstring": "get observation field base on a given field, and some convLayer parameters :param field: Tuple, (start, end): eg: (1,5), it means a stripe from fmap[1] to fmap[5] :param: kernel_size: int :param: stride: int :param: padding_size: int :param: observe_size: int, the input length of the convLayer. ... | 2 | stack_v2_sparse_classes_30k_train_010208 | Implement the Python class `Deconv` described below.
Class description:
Implement the Deconv class.
Method signatures and docstrings:
- def get_observation1d(field, kernel_size, stride, padding_size, observe_size): get observation field base on a given field, and some convLayer parameters :param field: Tuple, (start,... | Implement the Python class `Deconv` described below.
Class description:
Implement the Deconv class.
Method signatures and docstrings:
- def get_observation1d(field, kernel_size, stride, padding_size, observe_size): get observation field base on a given field, and some convLayer parameters :param field: Tuple, (start,... | 81c7fcc458665cdbf2d26aadf7c6104f531acce0 | <|skeleton|>
class Deconv:
def get_observation1d(field, kernel_size, stride, padding_size, observe_size):
"""get observation field base on a given field, and some convLayer parameters :param field: Tuple, (start, end): eg: (1,5), it means a stripe from fmap[1] to fmap[5] :param: kernel_size: int :param: st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Deconv:
def get_observation1d(field, kernel_size, stride, padding_size, observe_size):
"""get observation field base on a given field, and some convLayer parameters :param field: Tuple, (start, end): eg: (1,5), it means a stripe from fmap[1] to fmap[5] :param: kernel_size: int :param: stride: int :par... | the_stack_v2_python_sparse | ml_frameworks/2_keras/ii_advance/04_visualize_CNN_1d.py | Apollo1840/Machine-Learning-Tech | train | 2 | |
3b14ded7f65e758101a98e3e427501dfb928b5b4 | [
"if n == 0:\n return []\nelif n == 1:\n return [[1]]\nseen = [[False] * n for _ in range(n)]\ndr = [0, 1, 0, -1]\ndc = [1, 0, -1, 0]\nr = c = di = 0\nfor i in range(1, n * n + 1):\n seen[r][c] = i\n cr, cc = (r + dr[di], c + dc[di])\n if 0 <= cr < n and 0 <= cc < n and (not seen[cr][cc]):\n r,... | <|body_start_0|>
if n == 0:
return []
elif n == 1:
return [[1]]
seen = [[False] * n for _ in range(n)]
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
r = c = di = 0
for i in range(1, n * n + 1):
seen[r][c] = i
cr, cc = (r + d... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateMatrix(self, n):
""":type n: int :rtype: List[List[int]]"""
<|body_0|>
def generateMatrix2(self, n):
""":type n: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return []
... | stack_v2_sparse_classes_75kplus_train_072755 | 1,686 | no_license | [
{
"docstring": ":type n: int :rtype: List[List[int]]",
"name": "generateMatrix",
"signature": "def generateMatrix(self, n)"
},
{
"docstring": ":type n: int :rtype: List[List[int]]",
"name": "generateMatrix2",
"signature": "def generateMatrix2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035554 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateMatrix(self, n): :type n: int :rtype: List[List[int]]
- def generateMatrix2(self, n): :type n: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateMatrix(self, n): :type n: int :rtype: List[List[int]]
- def generateMatrix2(self, n): :type n: int :rtype: List[List[int]]
<|skeleton|>
class Solution:
def gene... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def generateMatrix(self, n):
""":type n: int :rtype: List[List[int]]"""
<|body_0|>
def generateMatrix2(self, n):
""":type n: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateMatrix(self, n):
""":type n: int :rtype: List[List[int]]"""
if n == 0:
return []
elif n == 1:
return [[1]]
seen = [[False] * n for _ in range(n)]
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
r = c = di = 0
f... | the_stack_v2_python_sparse | code/59#Spiral Matrix II.py | EachenKuang/LeetCode | train | 28 | |
f34a29071aabec3b4f322d461488c8f4bf9b805c | [
"super(AlexNet, self).__init__()\nself.class_num = class_num\nself.in_channels = 3\nself.features = self._make_layers()\nself.classifier = self._classifer_layers()",
"layers = []\nfor layer_type in self.cfg:\n if layer_type == 'M':\n layer = [nn.MaxPool3d(kernel_size=(1, self.pool_kernel_size, self.pool... | <|body_start_0|>
super(AlexNet, self).__init__()
self.class_num = class_num
self.in_channels = 3
self.features = self._make_layers()
self.classifier = self._classifer_layers()
<|end_body_0|>
<|body_start_1|>
layers = []
for layer_type in self.cfg:
if ... | AlexNet神经网络结构搭建(LRN换为BN, 前几层fc换为全局池化) | AlexNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlexNet:
"""AlexNet神经网络结构搭建(LRN换为BN, 前几层fc换为全局池化)"""
def __init__(self, class_num):
"""网络初始化 param: class_num 目标分类数"""
<|body_0|>
def _make_layers(self):
"""建立特征提取部分网络 return AlexNet_feature_net AlexNet特征提取部分"""
<|body_1|>
def _classifer_layers(self)... | stack_v2_sparse_classes_75kplus_train_072756 | 28,867 | no_license | [
{
"docstring": "网络初始化 param: class_num 目标分类数",
"name": "__init__",
"signature": "def __init__(self, class_num)"
},
{
"docstring": "建立特征提取部分网络 return AlexNet_feature_net AlexNet特征提取部分",
"name": "_make_layers",
"signature": "def _make_layers(self)"
},
{
"docstring": "建立分类部分网络 retur... | 4 | stack_v2_sparse_classes_30k_train_041934 | Implement the Python class `AlexNet` described below.
Class description:
AlexNet神经网络结构搭建(LRN换为BN, 前几层fc换为全局池化)
Method signatures and docstrings:
- def __init__(self, class_num): 网络初始化 param: class_num 目标分类数
- def _make_layers(self): 建立特征提取部分网络 return AlexNet_feature_net AlexNet特征提取部分
- def _classifer_layers(self): 建立... | Implement the Python class `AlexNet` described below.
Class description:
AlexNet神经网络结构搭建(LRN换为BN, 前几层fc换为全局池化)
Method signatures and docstrings:
- def __init__(self, class_num): 网络初始化 param: class_num 目标分类数
- def _make_layers(self): 建立特征提取部分网络 return AlexNet_feature_net AlexNet特征提取部分
- def _classifer_layers(self): 建立... | 2a68fd854bc5b1806319dfc40e36e084f9c4c5d0 | <|skeleton|>
class AlexNet:
"""AlexNet神经网络结构搭建(LRN换为BN, 前几层fc换为全局池化)"""
def __init__(self, class_num):
"""网络初始化 param: class_num 目标分类数"""
<|body_0|>
def _make_layers(self):
"""建立特征提取部分网络 return AlexNet_feature_net AlexNet特征提取部分"""
<|body_1|>
def _classifer_layers(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlexNet:
"""AlexNet神经网络结构搭建(LRN换为BN, 前几层fc换为全局池化)"""
def __init__(self, class_num):
"""网络初始化 param: class_num 目标分类数"""
super(AlexNet, self).__init__()
self.class_num = class_num
self.in_channels = 3
self.features = self._make_layers()
self.classifier = self... | the_stack_v2_python_sparse | code_keh/Pytorch_nets3d.py | ruichen9/3DCTLungDiseaseDiagnosis | train | 0 |
be2b643c7024d838c32bb2ed0961c695967bc58e | [
"current_file_path = os.path.realpath(__file__)\ndir_name = os.path.dirname(current_file_path)\ndir_name = os.path.dirname(dir_name)\nreturn dir_name + '\\\\'",
"real_file_path = self.get_project_path() + file_path\nconfig = configparser.ConfigParser()\nconfig.read(real_file_path)\nvalue = config.get('env', key)\... | <|body_start_0|>
current_file_path = os.path.realpath(__file__)
dir_name = os.path.dirname(current_file_path)
dir_name = os.path.dirname(dir_name)
return dir_name + '\\'
<|end_body_0|>
<|body_start_1|>
real_file_path = self.get_project_path() + file_path
config = configp... | DataRead | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataRead:
def get_project_path(self):
"""获取当前工程路径 :return:"""
<|body_0|>
def read_ini(self, file_path, key):
"""读取ini文件,返回key对应的value :param file_path: 文件路径 :param key: key :return: key对应的value"""
<|body_1|>
def read_yaml(self, file_path):
"""读取y... | stack_v2_sparse_classes_75kplus_train_072757 | 1,755 | no_license | [
{
"docstring": "获取当前工程路径 :return:",
"name": "get_project_path",
"signature": "def get_project_path(self)"
},
{
"docstring": "读取ini文件,返回key对应的value :param file_path: 文件路径 :param key: key :return: key对应的value",
"name": "read_ini",
"signature": "def read_ini(self, file_path, key)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_054559 | Implement the Python class `DataRead` described below.
Class description:
Implement the DataRead class.
Method signatures and docstrings:
- def get_project_path(self): 获取当前工程路径 :return:
- def read_ini(self, file_path, key): 读取ini文件,返回key对应的value :param file_path: 文件路径 :param key: key :return: key对应的value
- def read_y... | Implement the Python class `DataRead` described below.
Class description:
Implement the DataRead class.
Method signatures and docstrings:
- def get_project_path(self): 获取当前工程路径 :return:
- def read_ini(self, file_path, key): 读取ini文件,返回key对应的value :param file_path: 文件路径 :param key: key :return: key对应的value
- def read_y... | 4c0f15ae671bf2f3a9615da1b03bf8149f1ffae6 | <|skeleton|>
class DataRead:
def get_project_path(self):
"""获取当前工程路径 :return:"""
<|body_0|>
def read_ini(self, file_path, key):
"""读取ini文件,返回key对应的value :param file_path: 文件路径 :param key: key :return: key对应的value"""
<|body_1|>
def read_yaml(self, file_path):
"""读取y... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataRead:
def get_project_path(self):
"""获取当前工程路径 :return:"""
current_file_path = os.path.realpath(__file__)
dir_name = os.path.dirname(current_file_path)
dir_name = os.path.dirname(dir_name)
return dir_name + '\\'
def read_ini(self, file_path, key):
"""读取i... | the_stack_v2_python_sparse | JinRongZongHe/caw/DataRead.py | zhugg123456/zidonghua | train | 0 | |
1a3e6e4230ee3df1f45415447069243050800909 | [
"if not path.endswith('.py'):\n raise InvalidPathException(path)\nreturn Compiler().compile(path)",
"if not path.endswith('.py'):\n raise InvalidPathException(path)\nif output_path is None:\n output_path = path.replace('.py', '.nef')\nelif not output_path.endswith('.nef'):\n raise InvalidPathException... | <|body_start_0|>
if not path.endswith('.py'):
raise InvalidPathException(path)
return Compiler().compile(path)
<|end_body_0|>
<|body_start_1|>
if not path.endswith('.py'):
raise InvalidPathException(path)
if output_path is None:
output_path = path.rep... | The main class. Contains the methods that the final user have access to. | Boa3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Boa3:
"""The main class. Contains the methods that the final user have access to."""
def compile(path: str) -> bytes:
"""Load a Python file to be compiled but don't write the result into a file :param path: the path of the Python file to compile :return: the bytecode of the compiled ... | stack_v2_sparse_classes_75kplus_train_072758 | 1,460 | permissive | [
{
"docstring": "Load a Python file to be compiled but don't write the result into a file :param path: the path of the Python file to compile :return: the bytecode of the compiled .nef file",
"name": "compile",
"signature": "def compile(path: str) -> bytes"
},
{
"docstring": "Load a Python file t... | 2 | stack_v2_sparse_classes_30k_train_032540 | Implement the Python class `Boa3` described below.
Class description:
The main class. Contains the methods that the final user have access to.
Method signatures and docstrings:
- def compile(path: str) -> bytes: Load a Python file to be compiled but don't write the result into a file :param path: the path of the Pyth... | Implement the Python class `Boa3` described below.
Class description:
The main class. Contains the methods that the final user have access to.
Method signatures and docstrings:
- def compile(path: str) -> bytes: Load a Python file to be compiled but don't write the result into a file :param path: the path of the Pyth... | e4ef340744b5bd25ade26f847eac50789b97f3e9 | <|skeleton|>
class Boa3:
"""The main class. Contains the methods that the final user have access to."""
def compile(path: str) -> bytes:
"""Load a Python file to be compiled but don't write the result into a file :param path: the path of the Python file to compile :return: the bytecode of the compiled ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Boa3:
"""The main class. Contains the methods that the final user have access to."""
def compile(path: str) -> bytes:
"""Load a Python file to be compiled but don't write the result into a file :param path: the path of the Python file to compile :return: the bytecode of the compiled .nef file"""
... | the_stack_v2_python_sparse | boa3/boa3.py | DanPopa46/neo3-boa | train | 0 |
c11d4f8f3efcc03f3382be77608d2526ae21ebf9 | [
"super(RebCurrentLimits, self).__init__()\nself.rebps = rebps\nself.ts8 = ts8\nself.logger = rebps.logger\nself['DigI'] = ChannelLimits('digital.IbefLDO', 450.0, 560.0, 100.0)\nself['AnaI'] = ChannelLimits('analog.IbefLDO', 500.0, 660.0, 50.0)\nself['ClkHI'] = ChannelLimits('clockhi.IbefLDO', 80.0, 180.0, 25.0)\nse... | <|body_start_0|>
super(RebCurrentLimits, self).__init__()
self.rebps = rebps
self.ts8 = ts8
self.logger = rebps.logger
self['DigI'] = ChannelLimits('digital.IbefLDO', 450.0, 560.0, 100.0)
self['AnaI'] = ChannelLimits('analog.IbefLDO', 500.0, 660.0, 50.0)
self['Clk... | Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps. | RebCurrentLimits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RebCurrentLimits:
"""Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps."""
def __init__(self, re... | stack_v2_sparse_classes_75kplus_train_072759 | 4,646 | no_license | [
{
"docstring": "Parameters ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator.",
"name": "__init__",
"signature": "def __init__(self, rebps, ts8)"
},
{
"docstring": "C... | 3 | stack_v2_sparse_classes_30k_train_042179 | Implement the Python class `RebCurrentLimits` described below.
Class description:
Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from se... | Implement the Python class `RebCurrentLimits` described below.
Class description:
Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from se... | e6768df4b72c3b99cb9f7c3985a951b359b39c05 | <|skeleton|>
class RebCurrentLimits:
"""Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps."""
def __init__(self, re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RebCurrentLimits:
"""Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps."""
def __init__(self, rebps, ts8):
... | the_stack_v2_python_sparse | python/rebCurrentLimits.py | lsst-camera-dh/CR-jobs | train | 0 |
e5336e886b35016083020cacdfc62baca8759176 | [
"if not crvs:\n msg = 'Intrinsic mutual informations require a conditional variable.'\n raise ditException(msg)\nsuper().__init__(dist, rvs, crvs, rv_mode=rv_mode)\ntheoretical_bound_j = prod(self._shape)\nbound_j = min([bound_j, theoretical_bound_j]) if bound_j else theoretical_bound_j\nself._construct_auxva... | <|body_start_0|>
if not crvs:
msg = 'Intrinsic mutual informations require a conditional variable.'
raise ditException(msg)
super().__init__(dist, rvs, crvs, rv_mode=rv_mode)
theoretical_bound_j = prod(self._shape)
bound_j = min([bound_j, theoretical_bound_j]) if ... | Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V] | BaseTwoPartIntrinsicMutualInformation | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTwoPartIntrinsicMutualInformation:
"""Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V]"""
def __init__(self... | stack_v2_sparse_classes_75kplus_train_072760 | 25,213 | permissive | [
{
"docstring": "Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute the intrinsic mutual information of. rvs : list, None A list of lists. Each inner list specifies the indexes of the random variables used to calculate the intrinsic mutual information. If None, then i... | 3 | stack_v2_sparse_classes_30k_train_029427 | Implement the Python class `BaseTwoPartIntrinsicMutualInformation` described below.
Class description:
Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|... | Implement the Python class `BaseTwoPartIntrinsicMutualInformation` described below.
Class description:
Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|... | b13c5020a2b8524527a4a0db5a81d8549142228c | <|skeleton|>
class BaseTwoPartIntrinsicMutualInformation:
"""Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V]"""
def __init__(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseTwoPartIntrinsicMutualInformation:
"""Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V]"""
def __init__(self, dist, rvs=N... | the_stack_v2_python_sparse | dit/multivariate/secret_key_agreement/base_skar_optimizers.py | dit/dit | train | 468 |
c2e41376db9878a7231a2d01be4ef762e84374fc | [
"self.char_level = char_level\nself.hard_constraint = hard_constraint\nself.sent_delimiter = sent_delimiter\nself.max_seq_len = max_seq_len\nsuper().__init__(data, transform, cache, generate_idx)",
"filepath = get_resource(filepath)\nfor words, tags in generate_words_tags_from_tsv(filepath, lower=False):\n if ... | <|body_start_0|>
self.char_level = char_level
self.hard_constraint = hard_constraint
self.sent_delimiter = sent_delimiter
self.max_seq_len = max_seq_len
super().__init__(data, transform, cache, generate_idx)
<|end_body_0|>
<|body_start_1|>
filepath = get_resource(filepat... | TSVTaggingDataset | [
"Apache-2.0",
"CC-BY-NC-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSVTaggingDataset:
def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_level=False, hard_constraint=False, **kwargs) -> None:
"""Args: data: The local or remote path to a dataset, or ... | stack_v2_sparse_classes_75kplus_train_072761 | 3,588 | permissive | [
{
"docstring": "Args: data: The local or remote path to a dataset, or a list of samples where each sample is a dict. transform: Predefined transform(s). cache: ``True`` to enable caching, so that transforms won't be called twice. generate_idx: Create a :const:`~hanlp_common.constants.IDX` field for each sample ... | 2 | stack_v2_sparse_classes_30k_val_000203 | Implement the Python class `TSVTaggingDataset` described below.
Class description:
Implement the TSVTaggingDataset class.
Method signatures and docstrings:
- def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_lev... | Implement the Python class `TSVTaggingDataset` described below.
Class description:
Implement the TSVTaggingDataset class.
Method signatures and docstrings:
- def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_lev... | be2f04905a12990a527417bd47b79b851874a201 | <|skeleton|>
class TSVTaggingDataset:
def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_level=False, hard_constraint=False, **kwargs) -> None:
"""Args: data: The local or remote path to a dataset, or ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TSVTaggingDataset:
def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_level=False, hard_constraint=False, **kwargs) -> None:
"""Args: data: The local or remote path to a dataset, or a list of samp... | the_stack_v2_python_sparse | hanlp/datasets/ner/loaders/tsv.py | hankcs/HanLP | train | 32,454 | |
014c4ed1fce6fe6e6872928ff269442740ddb530 | [
"ans = []\nQ = queue.Queue()\nif root:\n Q.put(root)\nwhile not Q.empty():\n qSize = Q.qsize()\n curLevel = []\n for i in range(qSize):\n node = Q.get()\n curLevel.append(node.value)\n if node.left:\n Q.put(node.left)\n if node.right:\n Q.put(node.right)... | <|body_start_0|>
ans = []
Q = queue.Queue()
if root:
Q.put(root)
while not Q.empty():
qSize = Q.qsize()
curLevel = []
for i in range(qSize):
node = Q.get()
curLevel.append(node.value)
if node.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderByQueue(self, root):
"""使用优先队列 :type root: TreeNode :rtype: list[List[int]]"""
<|body_0|>
def levelOrder(self, root):
"""使用两层数组表示FIFO队列 :type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072762 | 1,560 | no_license | [
{
"docstring": "使用优先队列 :type root: TreeNode :rtype: list[List[int]]",
"name": "levelOrderByQueue",
"signature": "def levelOrderByQueue(self, root)"
},
{
"docstring": "使用两层数组表示FIFO队列 :type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, ro... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderByQueue(self, root): 使用优先队列 :type root: TreeNode :rtype: list[List[int]]
- def levelOrder(self, root): 使用两层数组表示FIFO队列 :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderByQueue(self, root): 使用优先队列 :type root: TreeNode :rtype: list[List[int]]
- def levelOrder(self, root): 使用两层数组表示FIFO队列 :type root: TreeNode :rtype: List[List[int]]
... | e69d7d892762968fc8442d75ec4535d90f731b52 | <|skeleton|>
class Solution:
def levelOrderByQueue(self, root):
"""使用优先队列 :type root: TreeNode :rtype: list[List[int]]"""
<|body_0|>
def levelOrder(self, root):
"""使用两层数组表示FIFO队列 :type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def levelOrderByQueue(self, root):
"""使用优先队列 :type root: TreeNode :rtype: list[List[int]]"""
ans = []
Q = queue.Queue()
if root:
Q.put(root)
while not Q.empty():
qSize = Q.qsize()
curLevel = []
for i in range(qSi... | the_stack_v2_python_sparse | Queue/TreeLevelOrder.py | xujackie1993/TheAlgorithms | train | 0 | |
4a6e54e727a35ae5598e56c6254082167e38e2dd | [
"if cls.case_config.need_copy_files:\n copy_necessary_files.copy_smarthome_demo_ocf_server(cls.tc.target.ip)\ncls.case_config.launch_ocf_server(cls.tc.target.ip, 'led.js')\ntime.sleep(cls.case_config.wait_launch_ocf_server)\ncls.case_config.prepare_test(cls.tc.target)\ncls.case_config.send_multi_requests(cls.tc.... | <|body_start_0|>
if cls.case_config.need_copy_files:
copy_necessary_files.copy_smarthome_demo_ocf_server(cls.tc.target.ip)
cls.case_config.launch_ocf_server(cls.tc.target.ip, 'led.js')
time.sleep(cls.case_config.wait_launch_ocf_server)
cls.case_config.prepare_test(cls.tc.targ... | RestApiOneOcfServerTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestApiOneOcfServerTest:
def setUpClass(cls):
"""Launch the OCF server on target device."""
<|body_0|>
def test_unique_ocf_device_remote(self):
"""Send REST request again and find only one OCF device."""
<|body_1|>
def test_unique_ocf_platform_remote(sel... | stack_v2_sparse_classes_75kplus_train_072763 | 2,705 | permissive | [
{
"docstring": "Launch the OCF server on target device.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Send REST request again and find only one OCF device.",
"name": "test_unique_ocf_device_remote",
"signature": "def test_unique_ocf_device_remote(self)"
... | 5 | stack_v2_sparse_classes_30k_train_004635 | Implement the Python class `RestApiOneOcfServerTest` described below.
Class description:
Implement the RestApiOneOcfServerTest class.
Method signatures and docstrings:
- def setUpClass(cls): Launch the OCF server on target device.
- def test_unique_ocf_device_remote(self): Send REST request again and find only one OC... | Implement the Python class `RestApiOneOcfServerTest` described below.
Class description:
Implement the RestApiOneOcfServerTest class.
Method signatures and docstrings:
- def setUpClass(cls): Launch the OCF server on target device.
- def test_unique_ocf_device_remote(self): Send REST request again and find only one OC... | b0bf009cdf24174deb5847ad882362a07ced3f61 | <|skeleton|>
class RestApiOneOcfServerTest:
def setUpClass(cls):
"""Launch the OCF server on target device."""
<|body_0|>
def test_unique_ocf_device_remote(self):
"""Send REST request again and find only one OCF device."""
<|body_1|>
def test_unique_ocf_platform_remote(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestApiOneOcfServerTest:
def setUpClass(cls):
"""Launch the OCF server on target device."""
if cls.case_config.need_copy_files:
copy_necessary_files.copy_smarthome_demo_ocf_server(cls.tc.target.ip)
cls.case_config.launch_ocf_server(cls.tc.target.ip, 'led.js')
time.s... | the_stack_v2_python_sparse | meta-iotqa/lib/oeqa/runtime/nodejs/restapiserver/rest_one_ocf_server_remote.py | wanghongjuan/intel-iot-refkit | train | 0 | |
5b2de20438b8f1835ceb6d563893c1643416b2d6 | [
"test = '4 5\\n75 5\\n0 100\\n150 20\\n75 1'\nd = Company(test)\nself.assertEqual(d.n, 4)\nself.assertEqual(d.d, 5)\nself.assertEqual(d.numa, [75, 0, 150, 75])\nself.assertEqual(d.numb, [5, 100, 20, 1])\nself.assertEqual(Company(test).calculate(), '100')\ntest = '5 100\\n0 7\\n11 32\\n99 10\\n46 8\\n87 54'\nself.as... | <|body_start_0|>
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
self.assertEqual(d.n, 4)
self.assertEqual(d.d, 5)
self.assertEqual(d.numa, [75, 0, 150, 75])
self.assertEqual(d.numb, [5, 100, 20, 1])
self.assertEqual(Company(test).calculate(), '100')
... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Company class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
... | stack_v2_sparse_classes_75kplus_train_072764 | 3,763 | permissive | [
{
"docstring": "Company class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023456 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Company class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Company class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Company class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class unitTests:
def test_single_test(self):
"""Company class testing"""
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
self.assertEqual(d.n, 4)
self.assertEqual(d.d, 5)
self.assertEqual(d.numa, [75, 0, 150, 75])
self.assertEqual(d.numb, [5, 100, 20... | the_stack_v2_python_sparse | codeforces/580B_company.py | snsokolov/contests | train | 1 | |
6c0030d2d918c92f6fc550fbd5240c48e19f3ba8 | [
"ds, dt = ({}, {})\nfor el in s:\n if el in ds:\n ds[el] += 1\n else:\n ds[el] = 1\nfor el in t:\n if el in dt:\n dt[el] += 1\n else:\n dt[el] = 1\nfor key in ds.keys():\n if key in ds and key in dt:\n if ds[key] != dt[key]:\n return key\n else:\n ... | <|body_start_0|>
ds, dt = ({}, {})
for el in s:
if el in ds:
ds[el] += 1
else:
ds[el] = 1
for el in t:
if el in dt:
dt[el] += 1
else:
dt[el] = 1
for key in ds.keys():
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTheDifference(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_0|>
def findTheDifferenceXOR(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ds, dt = ({}, {})
... | stack_v2_sparse_classes_75kplus_train_072765 | 1,476 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: str",
"name": "findTheDifference",
"signature": "def findTheDifference(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: str",
"name": "findTheDifferenceXOR",
"signature": "def findTheDifferenceXOR(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019671 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheDifference(self, s, t): :type s: str :type t: str :rtype: str
- def findTheDifferenceXOR(self, s, t): :type s: str :type t: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheDifference(self, s, t): :type s: str :type t: str :rtype: str
- def findTheDifferenceXOR(self, s, t): :type s: str :type t: str :rtype: str
<|skeleton|>
class Solutio... | b3a2013d1c3c7a5a16727dbc2ecbc934a01a3979 | <|skeleton|>
class Solution:
def findTheDifference(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_0|>
def findTheDifferenceXOR(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findTheDifference(self, s, t):
""":type s: str :type t: str :rtype: str"""
ds, dt = ({}, {})
for el in s:
if el in ds:
ds[el] += 1
else:
ds[el] = 1
for el in t:
if el in dt:
dt[el]... | the_stack_v2_python_sparse | LeetcodePython/FindtheDifference389.py | DianaLuca/Algorithms | train | 1 | |
3716e2e68a58b109e3d76466cc09b6755db1e053 | [
"if 'HTTP_X_FORWARDED_PROTO' in self.environ:\n return self.environ.get('HTTP_X_FORWARDED_PROTO') == 'https'\nreturn self.environ['wsgi.url_scheme'] == 'https'",
"assert 'stream' not in self.__dict__\nself.stream = _empty_stream\nlength = self.headers.get('content-length', type=int)\nreturn self.input_stream.r... | <|body_start_0|>
if 'HTTP_X_FORWARDED_PROTO' in self.environ:
return self.environ.get('HTTP_X_FORWARDED_PROTO') == 'https'
return self.environ['wsgi.url_scheme'] == 'https'
<|end_body_0|>
<|body_start_1|>
assert 'stream' not in self.__dict__
self.stream = _empty_stream
... | Request | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
def is_secure(self):
"""`True` if the request is secure."""
<|body_0|>
def data(self):
"""The string representation of the request body."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if 'HTTP_X_FORWARDED_PROTO' in self.environ:
... | stack_v2_sparse_classes_75kplus_train_072766 | 1,217 | permissive | [
{
"docstring": "`True` if the request is secure.",
"name": "is_secure",
"signature": "def is_secure(self)"
},
{
"docstring": "The string representation of the request body.",
"name": "data",
"signature": "def data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050197 | Implement the Python class `Request` described below.
Class description:
Implement the Request class.
Method signatures and docstrings:
- def is_secure(self): `True` if the request is secure.
- def data(self): The string representation of the request body. | Implement the Python class `Request` described below.
Class description:
Implement the Request class.
Method signatures and docstrings:
- def is_secure(self): `True` if the request is secure.
- def data(self): The string representation of the request body.
<|skeleton|>
class Request:
def is_secure(self):
... | 8da7f6816c95ace56f33c50f44b81b687503dca9 | <|skeleton|>
class Request:
def is_secure(self):
"""`True` if the request is secure."""
<|body_0|>
def data(self):
"""The string representation of the request body."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Request:
def is_secure(self):
"""`True` if the request is secure."""
if 'HTTP_X_FORWARDED_PROTO' in self.environ:
return self.environ.get('HTTP_X_FORWARDED_PROTO') == 'https'
return self.environ['wsgi.url_scheme'] == 'https'
def data(self):
"""The string repres... | the_stack_v2_python_sparse | yoi/dweeb.py | doptio/you-owe-it | train | 0 | |
260e8b84b1e48c39c0961a5ee70432922e837ae5 | [
"super().__init__(master, **options)\nself.pack()\nself._player_info = player_info\nself._selected_color_bgr = StringVar(self, '顏色未定')\nself._selected_color_bgr.trace('w', self._update_player_color)\nself._previous_selected_color_bgr = self._selected_color_bgr.get()\nself._setup_layout(color_list)",
"color_label ... | <|body_start_0|>
super().__init__(master, **options)
self.pack()
self._player_info = player_info
self._selected_color_bgr = StringVar(self, '顏色未定')
self._selected_color_bgr.trace('w', self._update_player_color)
self._previous_selected_color_bgr = self._selected_color_bgr.... | The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerInfo or its derived class that binds to this widget... | BasicPlayerInfoWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicPlayerInfoWidget:
"""The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerIn... | stack_v2_sparse_classes_75kplus_train_072767 | 8,055 | no_license | [
{
"docstring": "Constructor Constructor will invoke BasicPlayerInfoWidget._setup_layout() to setup its layout. @param master Specify he parent widget @param player_info Specify the target player information to be shwon @param color_list Specify he selectable color for this player. It will be a list of string re... | 5 | stack_v2_sparse_classes_30k_train_047707 | Implement the Python class `BasicPlayerInfoWidget` described below.
Class description:
The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _... | Implement the Python class `BasicPlayerInfoWidget` described below.
Class description:
The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _... | dc695322095b2eae4527fcdd33cf6304fbf39600 | <|skeleton|>
class BasicPlayerInfoWidget:
"""The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerIn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicPlayerInfoWidget:
"""The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerInfo or its der... | the_stack_v2_python_sparse | game_essential/game_widgets.py | LanKuDot/MazeArena-Console | train | 0 |
0e0ecf15342c874b2dd52461349fcb44eeeefe72 | [
"n = len(gas)\nif n < 1:\n return -1\nstart, leftGas, sum = (0, 0, 0)\nfor i in range(n):\n leftGas += gas[i] - cost[i]\n sum += gas[i] - cost[i]\n if sum < 0:\n sum = 0\n start = i + 1\nreturn -1 if leftGas < 0 else start",
"n = len(gas)\nif n < 1:\n return -1\ni, remain = (0, 0)\nfo... | <|body_start_0|>
n = len(gas)
if n < 1:
return -1
start, leftGas, sum = (0, 0, 0)
for i in range(n):
leftGas += gas[i] - cost[i]
sum += gas[i] - cost[i]
if sum < 0:
sum = 0
start = i + 1
return -1 if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_072768 | 2,441 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit2",
"signature": "def canCo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
n = len(gas)
if n < 1:
return -1
start, leftGas, sum = (0, 0, 0)
for i in range(n):
leftGas += gas[i] - cost[i]
sum += gas... | the_stack_v2_python_sparse | code134GasStation.py | cybelewang/leetcode-python | train | 0 | |
d8d60c8924f65dfd9c30068aeb5530f2b7bba38b | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)",
"attention = SelfAttention(s_prev.shape[1])\ncontext, ... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Dense(vocab)
<|end_body_0|>
<... | Class RNNDecoder to decode for machine translation | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""Class RNNDecoder to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of t... | stack_v2_sparse_classes_75kplus_train_072769 | 2,681 | no_license | [
{
"docstring": "Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of the embedding vector - units is an integer representing the number of hidden units in the RNN cell - batch is an integer representing the... | 2 | stack_v2_sparse_classes_30k_train_006026 | Implement the Python class `RNNDecoder` described below.
Class description:
Class RNNDecoder to decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - emb... | Implement the Python class `RNNDecoder` described below.
Class description:
Class RNNDecoder to decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - emb... | fc2cec306961f7ca2448965ddd3a2f656bbe10c7 | <|skeleton|>
class RNNDecoder:
"""Class RNNDecoder to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNDecoder:
"""Class RNNDecoder to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of the embedding ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | dalexach/holbertonschool-machine_learning | train | 2 |
abaa1cbcfe89f6d1110f07a5c6a5934f4217b42a | [
"try:\n import dgl\nexcept:\n raise ImportError('This class requires dgl.')\ntry:\n import dgllife\nexcept:\n raise ImportError('This class requires dgllife.')\nif mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\nsuper(MPNN, s... | <|body_start_0|>
try:
import dgl
except:
raise ImportError('This class requires dgl.')
try:
import dgllife
except:
raise ImportError('This class requires dgllife.')
if mode not in ['classification', 'regression']:
raise ... | Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations of all nodes in it, which involve... | MPNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPNN:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations o... | stack_v2_sparse_classes_75kplus_train_072770 | 12,074 | permissive | [
{
"docstring": "Parameters ---------- n_tasks: int Number of tasks. node_out_feats: int The length of the final node representation vectors. Default to 64. edge_hidden_feats: int The length of the hidden edge representation vectors. Default to 128. num_step_message_passing: int The number of rounds of message p... | 2 | stack_v2_sparse_classes_30k_train_032053 | Implement the Python class `MPNN` described below.
Class description:
Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representa... | Implement the Python class `MPNN` described below.
Class description:
Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representa... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class MPNN:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MPNN:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations of all nodes i... | the_stack_v2_python_sparse | deepchem/models/torch_models/mpnn.py | deepchem/deepchem | train | 4,876 |
f21e31153dc53523b75205a7057a973e055ac825 | [
"email = args['email']\npassword = args['password']\nuser = User.find(email=email, password=password)\nfailure = None\nif user is not None:\n status = login_user(user, remember=False)\n if status:\n log.info('Logged in User via API: {!r}'.format(user))\n create_session_oauth2_token()\n else:\... | <|body_start_0|>
email = args['email']
password = args['password']
user = User.find(email=email, password=password)
failure = None
if user is not None:
status = login_user(user, remember=False)
if status:
log.info('Logged in User via API: {... | Login with Session. | OAuth2Sessions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuth2Sessions:
"""Login with Session."""
def post(self, args):
"""Log-in via a new OAuth2 Session."""
<|body_0|>
def delete(self):
"""Log-out the active OAuth2 Session."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
email = args['email']
... | stack_v2_sparse_classes_75kplus_train_072771 | 5,850 | permissive | [
{
"docstring": "Log-in via a new OAuth2 Session.",
"name": "post",
"signature": "def post(self, args)"
},
{
"docstring": "Log-out the active OAuth2 Session.",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001610 | Implement the Python class `OAuth2Sessions` described below.
Class description:
Login with Session.
Method signatures and docstrings:
- def post(self, args): Log-in via a new OAuth2 Session.
- def delete(self): Log-out the active OAuth2 Session. | Implement the Python class `OAuth2Sessions` described below.
Class description:
Login with Session.
Method signatures and docstrings:
- def post(self, args): Log-in via a new OAuth2 Session.
- def delete(self): Log-out the active OAuth2 Session.
<|skeleton|>
class OAuth2Sessions:
"""Login with Session."""
d... | b28af2af01f1c66024e7a4fc20a01b5bd61ca863 | <|skeleton|>
class OAuth2Sessions:
"""Login with Session."""
def post(self, args):
"""Log-in via a new OAuth2 Session."""
<|body_0|>
def delete(self):
"""Log-out the active OAuth2 Session."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OAuth2Sessions:
"""Login with Session."""
def post(self, args):
"""Log-in via a new OAuth2 Session."""
email = args['email']
password = args['password']
user = User.find(email=email, password=password)
failure = None
if user is not None:
status ... | the_stack_v2_python_sparse | wbia/web/modules/auth/resources.py | WildMeOrg/wildbook-ia | train | 48 |
403cf067ecd7f86fd4d44f6172e3db1d5fd35d66 | [
"if resource is None:\n raise TypeError('resource cannot be none')\nif accesspath is None:\n raise TypeError('accesspath cannot be none')\nif session_key is None:\n raise TypeError('session_key cannot be none')\nreturn self.get_or_create(resource=resource, path=accesspath, session_key=session_key, at__gte=... | <|body_start_0|>
if resource is None:
raise TypeError('resource cannot be none')
if accesspath is None:
raise TypeError('accesspath cannot be none')
if session_key is None:
raise TypeError('session_key cannot be none')
return self.get_or_create(resourc... | A custom queryset for FileDownloadEvents | FileDownloadEventQuerySet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDownloadEventQuerySet:
"""A custom queryset for FileDownloadEvents"""
def get_or_create_if_no_duplicates_past_5_minutes(self, resource, accesspath, session_key):
"""Has a FileDownloadEvent for the same path and session been added in the past 5 minutes?"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_072772 | 15,660 | permissive | [
{
"docstring": "Has a FileDownloadEvent for the same path and session been added in the past 5 minutes?",
"name": "get_or_create_if_no_duplicates_past_5_minutes",
"signature": "def get_or_create_if_no_duplicates_past_5_minutes(self, resource, accesspath, session_key)"
},
{
"docstring": "Group by... | 3 | stack_v2_sparse_classes_30k_train_005772 | Implement the Python class `FileDownloadEventQuerySet` described below.
Class description:
A custom queryset for FileDownloadEvents
Method signatures and docstrings:
- def get_or_create_if_no_duplicates_past_5_minutes(self, resource, accesspath, session_key): Has a FileDownloadEvent for the same path and session been... | Implement the Python class `FileDownloadEventQuerySet` described below.
Class description:
A custom queryset for FileDownloadEvents
Method signatures and docstrings:
- def get_or_create_if_no_duplicates_past_5_minutes(self, resource, accesspath, session_key): Has a FileDownloadEvent for the same path and session been... | e3456678b240b49b2ebaf01a2f4b6b8d7721d68f | <|skeleton|>
class FileDownloadEventQuerySet:
"""A custom queryset for FileDownloadEvents"""
def get_or_create_if_no_duplicates_past_5_minutes(self, resource, accesspath, session_key):
"""Has a FileDownloadEvent for the same path and session been added in the past 5 minutes?"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileDownloadEventQuerySet:
"""A custom queryset for FileDownloadEvents"""
def get_or_create_if_no_duplicates_past_5_minutes(self, resource, accesspath, session_key):
"""Has a FileDownloadEvent for the same path and session been added in the past 5 minutes?"""
if resource is None:
... | the_stack_v2_python_sparse | agreements/models.py | cu-library/mellyn | train | 0 |
90a6ff9e9a36537c15f77b8f8e7a8cc5dff8f34a | [
"self.l = []\nself.d = OrderedDict()\nfor i in nums:\n self.l.append(i)\n if i in self.d:\n self.d[i] += 1\n else:\n self.d.update({i: 1})",
"for i in self.d:\n if self.d[i] == 1:\n return i\nreturn -1",
"self.l.append(value)\nif value in self.d:\n self.d[value] += 1\nelse:\n... | <|body_start_0|>
self.l = []
self.d = OrderedDict()
for i in nums:
self.l.append(i)
if i in self.d:
self.d[i] += 1
else:
self.d.update({i: 1})
<|end_body_0|>
<|body_start_1|>
for i in self.d:
if self.d[i] ==... | FirstUnique | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_072773 | 875 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":rtype: int",
"name": "showFirstUnique",
"signature": "def showFirstUnique(self)"
},
{
"docstring": ":type value: int :rtype: None",
"name": "add",
"sign... | 3 | null | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None
<|skeleton|>
class FirstUniq... | 965e6390a76cccf84738d21340f5c049adcc223a | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
self.l = []
self.d = OrderedDict()
for i in nums:
self.l.append(i)
if i in self.d:
self.d[i] += 1
else:
self.d.update({i: 1})
def showFirs... | the_stack_v2_python_sparse | python/First Unique Number.py | SubhradeepSS/LeetCode-Solutions | train | 0 | |
e40d3ff364f9e1e30fe54212fc89f9e27fbd3d9e | [
"sys.stdout = io.StringIO()\nstream_handler = logging.StreamHandler(sys.stdout)\nLOGGER.addHandler(stream_handler)\nexpected_str = ''\nvalidate_date(self.good_date, '', {})\noutput = sys.stdout.getvalue().strip()\nself.assertEqual(output, expected_str)\nLOGGER.removeHandler(stream_handler)",
"sys.stdout = io.Stri... | <|body_start_0|>
sys.stdout = io.StringIO()
stream_handler = logging.StreamHandler(sys.stdout)
LOGGER.addHandler(stream_handler)
expected_str = ''
validate_date(self.good_date, '', {})
output = sys.stdout.getvalue().strip()
self.assertEqual(output, expected_str)
... | Test class for the validate_date() method. | TestValidateDate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestValidateDate:
"""Test class for the validate_date() method."""
def test_good_date(self):
"""Test of a valid date."""
<|body_0|>
def test_bad_date_year(self):
"""Test of a bad date due to the year not being 4-digits."""
<|body_1|>
def test_bad_dat... | stack_v2_sparse_classes_75kplus_train_072774 | 23,348 | permissive | [
{
"docstring": "Test of a valid date.",
"name": "test_good_date",
"signature": "def test_good_date(self)"
},
{
"docstring": "Test of a bad date due to the year not being 4-digits.",
"name": "test_bad_date_year",
"signature": "def test_bad_date_year(self)"
},
{
"docstring": "Test ... | 6 | null | Implement the Python class `TestValidateDate` described below.
Class description:
Test class for the validate_date() method.
Method signatures and docstrings:
- def test_good_date(self): Test of a valid date.
- def test_bad_date_year(self): Test of a bad date due to the year not being 4-digits.
- def test_bad_date_mo... | Implement the Python class `TestValidateDate` described below.
Class description:
Test class for the validate_date() method.
Method signatures and docstrings:
- def test_good_date(self): Test of a valid date.
- def test_bad_date_year(self): Test of a bad date due to the year not being 4-digits.
- def test_bad_date_mo... | 48c1df2e6bef3e03f6eefe9f52808b345e1587b4 | <|skeleton|>
class TestValidateDate:
"""Test class for the validate_date() method."""
def test_good_date(self):
"""Test of a valid date."""
<|body_0|>
def test_bad_date_year(self):
"""Test of a bad date due to the year not being 4-digits."""
<|body_1|>
def test_bad_dat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestValidateDate:
"""Test class for the validate_date() method."""
def test_good_date(self):
"""Test of a valid date."""
sys.stdout = io.StringIO()
stream_handler = logging.StreamHandler(sys.stdout)
LOGGER.addHandler(stream_handler)
expected_str = ''
valida... | the_stack_v2_python_sparse | CHECK_METADATA_FORMAT/_test_apply_metadata_check.py | spacetelescope/MAST_HLSP | train | 0 |
bbf63ddffef889806ebccd73d7b4b878fd19454e | [
"self.mainconfig = mainconfig\nself.dataconfig = dataconfig\nif mainconfig.get('atlas_list', None) is None or mainconfig.get('atlas_list', None) == 'all':\n self.atlas_list = load_txt(os.path.join(rootconfig.path.atlas, 'atlas_list.txt'))\nelif type(mainconfig['atlas_list']) is list:\n self.atlas_list = mainc... | <|body_start_0|>
self.mainconfig = mainconfig
self.dataconfig = dataconfig
if mainconfig.get('atlas_list', None) is None or mainconfig.get('atlas_list', None) == 'all':
self.atlas_list = load_txt(os.path.join(rootconfig.path.atlas, 'atlas_list.txt'))
elif type(mainconfig['atl... | The feature exporter. Export features in all mriscans. | MRIScanProcExporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRIScanProcExporter:
"""The feature exporter. Export features in all mriscans."""
def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False):
"""Init the exporter using mainconfig and dataconfig."""
<|body_0|>
def run_mriscan_at... | stack_v2_sparse_classes_75kplus_train_072775 | 10,193 | no_license | [
{
"docstring": "Init the exporter using mainconfig and dataconfig.",
"name": "__init__",
"signature": "def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False)"
},
{
"docstring": "Run one mriscan and one atlas to export.",
"name": "run_mriscan_atl... | 3 | stack_v2_sparse_classes_30k_train_029937 | Implement the Python class `MRIScanProcExporter` described below.
Class description:
The feature exporter. Export features in all mriscans.
Method signatures and docstrings:
- def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False): Init the exporter using mainconfig and ... | Implement the Python class `MRIScanProcExporter` described below.
Class description:
The feature exporter. Export features in all mriscans.
Method signatures and docstrings:
- def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False): Init the exporter using mainconfig and ... | dabfabdeb2f922a3dcbdaf3fc46f0c4b40598279 | <|skeleton|>
class MRIScanProcExporter:
"""The feature exporter. Export features in all mriscans."""
def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False):
"""Init the exporter using mainconfig and dataconfig."""
<|body_0|>
def run_mriscan_at... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MRIScanProcExporter:
"""The feature exporter. Export features in all mriscans."""
def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False):
"""Init the exporter using mainconfig and dataconfig."""
self.mainconfig = mainconfig
self.datac... | the_stack_v2_python_sparse | mmdps/dms/feature_exporter.py | geyunxiang/mmdps | train | 5 |
0138a77c06865245c98d99bfcf47fb0b1ce9d11e | [
"super().__init__(device=device)\nxyz = _handle_input(x, y, z, dtype, device, 'Translate')\nN = xyz.shape[0]\nmat = torch.eye(4, dtype=dtype, device=device)\nmat = mat.view(1, 4, 4).repeat(N, 1, 1)\nmat[:, 3, :3] = xyz\nself._matrix = mat",
"inv_mask = self._matrix.new_ones([1, 4, 4])\ninv_mask[0, 3, :3] = -1.0\n... | <|body_start_0|>
super().__init__(device=device)
xyz = _handle_input(x, y, z, dtype, device, 'Translate')
N = xyz.shape[0]
mat = torch.eye(4, dtype=dtype, device=device)
mat = mat.view(1, 4, 4).repeat(N, 1, 1)
mat[:, 3, :3] = xyz
self._matrix = mat
<|end_body_0|>
... | Translate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Translate:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.floa... | stack_v2_sparse_classes_75kplus_train_072776 | 43,607 | permissive | [
{
"docstring": "Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.float32, device='cpu') Here x, y, and z will be broadcast against each other and concatenated to for... | 2 | stack_v2_sparse_classes_30k_train_015117 | Implement the Python class `Translate` described below.
Class description:
Implement the Translate class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'): Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, d... | Implement the Python class `Translate` described below.
Class description:
Implement the Translate class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'): Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, d... | 1d240f60a99682e8409363c5829aba14869ba140 | <|skeleton|>
class Translate:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.floa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Translate:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.float32, device='c... | the_stack_v2_python_sparse | soft_intro_vae_3d/datasets/transforms3d.py | LearnerLYH/soft-intro-vae-pytorch | train | 1 | |
bd0f1abfcf830758fb58ba5e12d93d44f79d7085 | [
"super(FCModel, self).__init__()\nsizes.insert(0, n_features)\nlayers = [nn.Linear(size_in, size_out) for size_in, size_out in zip(sizes[:-1], sizes[1:])]\nself.input_norm = nn.LayerNorm(n_features) if input_norm else nn.Identity()\nself.activation = nn.Identity() if activation is None else instantiate_class('torch... | <|body_start_0|>
super(FCModel, self).__init__()
sizes.insert(0, n_features)
layers = [nn.Linear(size_in, size_out) for size_in, size_out in zip(sizes[:-1], sizes[1:])]
self.input_norm = nn.LayerNorm(n_features) if input_norm else nn.Identity()
self.activation = nn.Identity() if ... | This class represents a fully connected neural network model with given layer sizes and activation function. | FCModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCModel:
"""This class represents a fully connected neural network model with given layer sizes and activation function."""
def __init__(self, sizes, input_norm, activation, dropout, n_features):
""":param sizes: list of layer sizes (excluding the input layer size which is given by n... | stack_v2_sparse_classes_75kplus_train_072777 | 21,238 | no_license | [
{
"docstring": ":param sizes: list of layer sizes (excluding the input layer size which is given by n_features parameter) :param input_norm: flag indicating whether to perform layer normalization on the input :param activation: name of the PyTorch activation function, e.g. Sigmoid or Tanh :param dropout: dropou... | 2 | stack_v2_sparse_classes_30k_train_013487 | Implement the Python class `FCModel` described below.
Class description:
This class represents a fully connected neural network model with given layer sizes and activation function.
Method signatures and docstrings:
- def __init__(self, sizes, input_norm, activation, dropout, n_features): :param sizes: list of layer ... | Implement the Python class `FCModel` described below.
Class description:
This class represents a fully connected neural network model with given layer sizes and activation function.
Method signatures and docstrings:
- def __init__(self, sizes, input_norm, activation, dropout, n_features): :param sizes: list of layer ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class FCModel:
"""This class represents a fully connected neural network model with given layer sizes and activation function."""
def __init__(self, sizes, input_norm, activation, dropout, n_features):
""":param sizes: list of layer sizes (excluding the input layer size which is given by n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FCModel:
"""This class represents a fully connected neural network model with given layer sizes and activation function."""
def __init__(self, sizes, input_norm, activation, dropout, n_features):
""":param sizes: list of layer sizes (excluding the input layer size which is given by n_features par... | the_stack_v2_python_sparse | generated/test_allegro_allRank.py | jansel/pytorch-jit-paritybench | train | 35 |
5d515b05714c524a6c42646fa26afae38e68c618 | [
"test, traceback = super(SetAWGParametersTask, self).check(*args, **kwargs)\nerr_path = self.get_error_path()\nfor id, ch in self._channels.items():\n res, tr = ch.check(self)\n aux = {err_path + 'Ch{}_{}'.format(id, err): val for err, val in tr.items()}\n traceback.update(aux)\n test &= res\nreturn (te... | <|body_start_0|>
test, traceback = super(SetAWGParametersTask, self).check(*args, **kwargs)
err_path = self.get_error_path()
for id, ch in self._channels.items():
res, tr = ch.check(self)
aux = {err_path + 'Ch{}_{}'.format(id, err): val for err, val in tr.items()}
... | Set the parameters of the different channels of the AWG. | SetAWGParametersTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetAWGParametersTask:
"""Set the parameters of the different channels of the AWG."""
def check(self, *args, **kwargs):
"""Automatically test all parameters evaluation."""
<|body_0|>
def register_preferences(self):
"""Overriden to handle channels."""
<|bod... | stack_v2_sparse_classes_75kplus_train_072778 | 8,675 | permissive | [
{
"docstring": "Automatically test all parameters evaluation.",
"name": "check",
"signature": "def check(self, *args, **kwargs)"
},
{
"docstring": "Overriden to handle channels.",
"name": "register_preferences",
"signature": "def register_preferences(self)"
},
{
"docstring": "Han... | 4 | stack_v2_sparse_classes_30k_train_033438 | Implement the Python class `SetAWGParametersTask` described below.
Class description:
Set the parameters of the different channels of the AWG.
Method signatures and docstrings:
- def check(self, *args, **kwargs): Automatically test all parameters evaluation.
- def register_preferences(self): Overriden to handle chann... | Implement the Python class `SetAWGParametersTask` described below.
Class description:
Set the parameters of the different channels of the AWG.
Method signatures and docstrings:
- def check(self, *args, **kwargs): Automatically test all parameters evaluation.
- def register_preferences(self): Overriden to handle chann... | b6f1f5b236c7a4e28d9a3bc8da9820c52d789309 | <|skeleton|>
class SetAWGParametersTask:
"""Set the parameters of the different channels of the AWG."""
def check(self, *args, **kwargs):
"""Automatically test all parameters evaluation."""
<|body_0|>
def register_preferences(self):
"""Overriden to handle channels."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SetAWGParametersTask:
"""Set the parameters of the different channels of the AWG."""
def check(self, *args, **kwargs):
"""Automatically test all parameters evaluation."""
test, traceback = super(SetAWGParametersTask, self).check(*args, **kwargs)
err_path = self.get_error_path()
... | the_stack_v2_python_sparse | exopy_hqc_legacy/tasks/tasks/instr/set_awg_parameters.py | Exopy/exopy_hqc_legacy | train | 0 |
321badeb5eebfb5b264d02aab1da193677c8edb2 | [
"discussion = Discussion(title='Sample Discussion')\ntime = discussion.last_modified\ndiscussion.update_last_modified()\nself.assertNotEqual(time, discussion.last_modified)",
"time = timezone.now() + datetime.timedelta(days=30)\nfuture_discussion = Discussion(create_date=time)\nself.assertEqual(future_discussion.... | <|body_start_0|>
discussion = Discussion(title='Sample Discussion')
time = discussion.last_modified
discussion.update_last_modified()
self.assertNotEqual(time, discussion.last_modified)
<|end_body_0|>
<|body_start_1|>
time = timezone.now() + datetime.timedelta(days=30)
f... | DiscussionMethodTestCase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscussionMethodTestCase:
def test_update_last_modified(self):
"""If a discussion is created it should have a default last_modified time. When calling update_last_modified() the discussion last_modified should be reset to the current time. Thus it should not equal the time of instantiati... | stack_v2_sparse_classes_75kplus_train_072779 | 2,139 | permissive | [
{
"docstring": "If a discussion is created it should have a default last_modified time. When calling update_last_modified() the discussion last_modified should be reset to the current time. Thus it should not equal the time of instantiation.",
"name": "test_update_last_modified",
"signature": "def test_... | 4 | stack_v2_sparse_classes_30k_train_020618 | Implement the Python class `DiscussionMethodTestCase` described below.
Class description:
Implement the DiscussionMethodTestCase class.
Method signatures and docstrings:
- def test_update_last_modified(self): If a discussion is created it should have a default last_modified time. When calling update_last_modified() t... | Implement the Python class `DiscussionMethodTestCase` described below.
Class description:
Implement the DiscussionMethodTestCase class.
Method signatures and docstrings:
- def test_update_last_modified(self): If a discussion is created it should have a default last_modified time. When calling update_last_modified() t... | 59f3f3ae727fe52c7897beaf73d157b02cdcb7a3 | <|skeleton|>
class DiscussionMethodTestCase:
def test_update_last_modified(self):
"""If a discussion is created it should have a default last_modified time. When calling update_last_modified() the discussion last_modified should be reset to the current time. Thus it should not equal the time of instantiati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiscussionMethodTestCase:
def test_update_last_modified(self):
"""If a discussion is created it should have a default last_modified time. When calling update_last_modified() the discussion last_modified should be reset to the current time. Thus it should not equal the time of instantiation."""
... | the_stack_v2_python_sparse | discussions/tests.py | pabulumm/neighbors | train | 0 | |
6de0436abd47ba94fac9bb05fdbe77550bf7c91f | [
"self.column_names: List = kargs.pop('column_names')\nself.action: Action = kargs.pop('action')\nsuper().__init__(*args, **kargs)\nself.set_fields_from_dict(['item_column', 'user_fname_column', 'file_suffix', 'zip_for_moodle', 'confirm_items'])\nuser_fname_column = self.fields['user_fname_column'].initial\nitem_col... | <|body_start_0|>
self.column_names: List = kargs.pop('column_names')
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
self.set_fields_from_dict(['item_column', 'user_fname_column', 'file_suffix', 'zip_for_moodle', 'confirm_items'])
user_fname_column = se... | Form to create a ZIP. | ZipActionForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
<|body_0|>
def clean(self):
"""Detect uniques values in one column, and different column names."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_072780 | 20,237 | permissive | [
{
"docstring": "Store column names, action and payload, adjust fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Detect uniques values in one column, and different column names.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048193 | Implement the Python class `ZipActionForm` described below.
Class description:
Form to create a ZIP.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names, action and payload, adjust fields.
- def clean(self): Detect uniques values in one column, and different column names. | Implement the Python class `ZipActionForm` described below.
Class description:
Form to create a ZIP.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names, action and payload, adjust fields.
- def clean(self): Detect uniques values in one column, and different column names.
<|ske... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
<|body_0|>
def clean(self):
"""Detect uniques values in one column, and different column names."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
self.column_names: List = kargs.pop('column_names')
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
... | the_stack_v2_python_sparse | ontask/action/forms/run.py | LucasFranciscoCorreia/ontask_b | train | 0 |
3b31f1100a9974cb0ab35c0ff5497bd83a151224 | [
"self.channelName = ''\nself.connection = None\nself.type = UNKNOWN\nif specName is not None and specVersion is not None:\n self.connectToSpec(specName, specVersion, timeout)\nelse:\n self.specName = None\n self.specVersion = None",
"self.specName = specName\nself.specVersion = specVersion\nself.connecti... | <|body_start_0|>
self.channelName = ''
self.connection = None
self.type = UNKNOWN
if specName is not None and specVersion is not None:
self.connectToSpec(specName, specVersion, timeout)
else:
self.specName = None
self.specVersion = None
<|end_b... | SpecCounter class | SpecCounter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecCounter:
"""SpecCounter class"""
def __init__(self, specName=None, specVersion=None, timeout=None):
"""Constructor Keyword arguments: specName -- the name of the counter in Spec (defaults to None) specVersion -- 'host:port' string representing a Spec server to connect to (default... | stack_v2_sparse_classes_75kplus_train_072781 | 2,948 | permissive | [
{
"docstring": "Constructor Keyword arguments: specName -- the name of the counter in Spec (defaults to None) specVersion -- 'host:port' string representing a Spec server to connect to (defaults to None) timeout -- optional timeout for connection (defaults to None)",
"name": "__init__",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_021873 | Implement the Python class `SpecCounter` described below.
Class description:
SpecCounter class
Method signatures and docstrings:
- def __init__(self, specName=None, specVersion=None, timeout=None): Constructor Keyword arguments: specName -- the name of the counter in Spec (defaults to None) specVersion -- 'host:port'... | Implement the Python class `SpecCounter` described below.
Class description:
SpecCounter class
Method signatures and docstrings:
- def __init__(self, specName=None, specVersion=None, timeout=None): Constructor Keyword arguments: specName -- the name of the counter in Spec (defaults to None) specVersion -- 'host:port'... | 3152bd19d14eca07c946ff9e6d0ee28d87c4d046 | <|skeleton|>
class SpecCounter:
"""SpecCounter class"""
def __init__(self, specName=None, specVersion=None, timeout=None):
"""Constructor Keyword arguments: specName -- the name of the counter in Spec (defaults to None) specVersion -- 'host:port' string representing a Spec server to connect to (default... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpecCounter:
"""SpecCounter class"""
def __init__(self, specName=None, specVersion=None, timeout=None):
"""Constructor Keyword arguments: specName -- the name of the counter in Spec (defaults to None) specVersion -- 'host:port' string representing a Spec server to connect to (defaults to None) ti... | the_stack_v2_python_sparse | python/client/SpecCounter.py | drs378/pyspec | train | 0 |
5f0594a8c73172c3acde30c9b56009d439ec6420 | [
"BaseNet.__init__(self, name=name)\nself.fea = [4, 8, 16, 32, 64]\nself.k_conv = 3\nself.affine_w_initializer = affine_w_initializer\nself.affine_b_initializer = affine_b_initializer\nself.res_param = {'w_initializer': GlorotUniform.get_instance(''), 'w_regularizer': regularizers.l2_regularizer(decay), 'acti_func':... | <|body_start_0|>
BaseNet.__init__(self, name=name)
self.fea = [4, 8, 16, 32, 64]
self.k_conv = 3
self.affine_w_initializer = affine_w_initializer
self.affine_b_initializer = affine_b_initializer
self.res_param = {'w_initializer': GlorotUniform.get_instance(''), 'w_regular... | INetAffine | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INetAffine:
def __init__(self, decay=1e-06, affine_w_initializer=None, affine_b_initializer=None, acti_func='relu', name='inet-affine'):
"""This network estimates affine transformations from a pair of moving and fixed image: Hu et al., Label-driven weakly-supervised learning for multimod... | stack_v2_sparse_classes_75kplus_train_072782 | 4,864 | permissive | [
{
"docstring": "This network estimates affine transformations from a pair of moving and fixed image: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Networks for M... | 2 | null | Implement the Python class `INetAffine` described below.
Class description:
Implement the INetAffine class.
Method signatures and docstrings:
- def __init__(self, decay=1e-06, affine_w_initializer=None, affine_b_initializer=None, acti_func='relu', name='inet-affine'): This network estimates affine transformations fro... | Implement the Python class `INetAffine` described below.
Class description:
Implement the INetAffine class.
Method signatures and docstrings:
- def __init__(self, decay=1e-06, affine_w_initializer=None, affine_b_initializer=None, acti_func='relu', name='inet-affine'): This network estimates affine transformations fro... | 84dd0f85c9a1ab8a72f4c55fcf073379acf5ae1b | <|skeleton|>
class INetAffine:
def __init__(self, decay=1e-06, affine_w_initializer=None, affine_b_initializer=None, acti_func='relu', name='inet-affine'):
"""This network estimates affine transformations from a pair of moving and fixed image: Hu et al., Label-driven weakly-supervised learning for multimod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class INetAffine:
def __init__(self, decay=1e-06, affine_w_initializer=None, affine_b_initializer=None, acti_func='relu', name='inet-affine'):
"""This network estimates affine transformations from a pair of moving and fixed image: Hu et al., Label-driven weakly-supervised learning for multimodal deformable ... | the_stack_v2_python_sparse | niftynet/network/interventional_affine_net.py | 12SigmaTechnologies/NiftyNet-1 | train | 2 | |
1e7a3fee59e54d0a572ff80d2c2de4ce73f21bab | [
"self.items = []\nself.sample_count = sample_count\nself.index = 0",
"if self.index < self.sample_count:\n self.items.append(item)\nelse:\n r = random.randint(0, self.index - 1)\n if r < self.sample_count:\n self.items[r] = item\nself.index += 1"
] | <|body_start_0|>
self.items = []
self.sample_count = sample_count
self.index = 0
<|end_body_0|>
<|body_start_1|>
if self.index < self.sample_count:
self.items.append(item)
else:
r = random.randint(0, self.index - 1)
if r < self.sample_count:
... | Perform reservoir sampling to get a uniform sample from any number of elements. | ReservoirSample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReservoirSample:
"""Perform reservoir sampling to get a uniform sample from any number of elements."""
def __init__(self, sample_count):
"""sample_count is the desired number of sample points self.items contains the sample after we're finished"""
<|body_0|>
def add_item(... | stack_v2_sparse_classes_75kplus_train_072783 | 710 | no_license | [
{
"docstring": "sample_count is the desired number of sample points self.items contains the sample after we're finished",
"name": "__init__",
"signature": "def __init__(self, sample_count)"
},
{
"docstring": "Add an item to the reservoir.",
"name": "add_item",
"signature": "def add_item(... | 2 | stack_v2_sparse_classes_30k_train_007266 | Implement the Python class `ReservoirSample` described below.
Class description:
Perform reservoir sampling to get a uniform sample from any number of elements.
Method signatures and docstrings:
- def __init__(self, sample_count): sample_count is the desired number of sample points self.items contains the sample afte... | Implement the Python class `ReservoirSample` described below.
Class description:
Perform reservoir sampling to get a uniform sample from any number of elements.
Method signatures and docstrings:
- def __init__(self, sample_count): sample_count is the desired number of sample points self.items contains the sample afte... | 3d82ab3afcb3976973c5b5110816a16f1e0e0a13 | <|skeleton|>
class ReservoirSample:
"""Perform reservoir sampling to get a uniform sample from any number of elements."""
def __init__(self, sample_count):
"""sample_count is the desired number of sample points self.items contains the sample after we're finished"""
<|body_0|>
def add_item(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReservoirSample:
"""Perform reservoir sampling to get a uniform sample from any number of elements."""
def __init__(self, sample_count):
"""sample_count is the desired number of sample points self.items contains the sample after we're finished"""
self.items = []
self.sample_count ... | the_stack_v2_python_sparse | src/chapter3/reservoir_sampling.py | smh29/Social-Media-Data-Mining-Analytics | train | 0 |
ce40f3ee670584700c9cf1aed54c41843ec51bfc | [
"self.__k = k\nself.__min_heap = []\nfor n in nums:\n self.add(n)",
"heapq.heappush(self.__min_heap, val)\nif len(self.__min_heap) > self.__k:\n heapq.heappop(self.__min_heap)\nreturn self.__min_heap[0]"
] | <|body_start_0|>
self.__k = k
self.__min_heap = []
for n in nums:
self.add(n)
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.__min_heap, val)
if len(self.__min_heap) > self.__k:
heapq.heappop(self.__min_heap)
return self.__min_heap[0]
<|end_b... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: init :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.__k = k
self.__min_heap = []
for n i... | stack_v2_sparse_classes_75kplus_train_072784 | 667 | no_license | [
{
"docstring": ":type k: init :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047202 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: init :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: init :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, n... | 1804863ca931abedbbb8053bcc771115d0c23a2d | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: init :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: init :type nums: List[int]"""
self.__k = k
self.__min_heap = []
for n in nums:
self.add(n)
def add(self, val):
""":type val: int :rtype: int"""
heapq.heappush(self.__min_heap, val)
if ... | the_stack_v2_python_sparse | leetcodeDS/kth_largest_number_stream.py | PyRPy/algorithms_books | train | 1 | |
5529979421a98b933979989cf80f4d06d2c160cb | [
"self.build_links = False\nself.links_file = None\nself.source_dir = None\nself.build_dir = None\nself.xslt = None",
"if self.source_dir is None:\n if os.path.isdir('schemas'):\n for root, dirnames, filenames in os.walk('schemas'):\n for filename in filenames:\n if fnmatch(file... | <|body_start_0|>
self.build_links = False
self.links_file = None
self.source_dir = None
self.build_dir = None
self.xslt = None
<|end_body_0|>
<|body_start_1|>
if self.source_dir is None:
if os.path.isdir('schemas'):
for root, dirnames, filenam... | Build DTD documentation | BuildDTDDoc | [
"mpich2",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildDTDDoc:
"""Build DTD documentation"""
def initialize_options(self):
"""Set default values for all the options that this command supports."""
<|body_0|>
def finalize_options(self):
"""Set final values for all the options that this command supports."""
... | stack_v2_sparse_classes_75kplus_train_072785 | 6,475 | permissive | [
{
"docstring": "Set default values for all the options that this command supports.",
"name": "initialize_options",
"signature": "def initialize_options(self)"
},
{
"docstring": "Set final values for all the options that this command supports.",
"name": "finalize_options",
"signature": "d... | 3 | null | Implement the Python class `BuildDTDDoc` described below.
Class description:
Build DTD documentation
Method signatures and docstrings:
- def initialize_options(self): Set default values for all the options that this command supports.
- def finalize_options(self): Set final values for all the options that this command... | Implement the Python class `BuildDTDDoc` described below.
Class description:
Build DTD documentation
Method signatures and docstrings:
- def initialize_options(self): Set default values for all the options that this command supports.
- def finalize_options(self): Set final values for all the options that this command... | 826f385767ccf9f608fcfbe35e381a9dbc59db4b | <|skeleton|>
class BuildDTDDoc:
"""Build DTD documentation"""
def initialize_options(self):
"""Set default values for all the options that this command supports."""
<|body_0|>
def finalize_options(self):
"""Set final values for all the options that this command supports."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuildDTDDoc:
"""Build DTD documentation"""
def initialize_options(self):
"""Set default values for all the options that this command supports."""
self.build_links = False
self.links_file = None
self.source_dir = None
self.build_dir = None
self.xslt = None
... | the_stack_v2_python_sparse | setup.py | mikemccllstr/bcfg2 | train | 1 |
b2a89a8459357d33b649e703c68ef30928f39a69 | [
"profile: Profile = get_profile_by_token(request)\nif not profile.has_valid_token:\n return INVALID_CREDENTIALS\nid_: str = request.query_params.get('id')\ntry:\n product: Product = Product.get_by_id(id_)\nexcept (ValueError, TypeError, Product.DoesNotExist):\n return PRODUCT_NOT_FOUND\nserializer = Produc... | <|body_start_0|>
profile: Profile = get_profile_by_token(request)
if not profile.has_valid_token:
return INVALID_CREDENTIALS
id_: str = request.query_params.get('id')
try:
product: Product = Product.get_by_id(id_)
except (ValueError, TypeError, Product.Doe... | ProductView provides handlers for different methods on single product. | ProductView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductView:
"""ProductView provides handlers for different methods on single product."""
def get(self, request: Request) -> Response:
"""Get info about product by its id. :param request: request with "id" field. :return: response whether request is successful with info about product... | stack_v2_sparse_classes_75kplus_train_072786 | 6,415 | no_license | [
{
"docstring": "Get info about product by its id. :param request: request with \"id\" field. :return: response whether request is successful with info about product.",
"name": "get",
"signature": "def get(self, request: Request) -> Response"
},
{
"docstring": "Edit product info. :param request: ... | 4 | stack_v2_sparse_classes_30k_test_001857 | Implement the Python class `ProductView` described below.
Class description:
ProductView provides handlers for different methods on single product.
Method signatures and docstrings:
- def get(self, request: Request) -> Response: Get info about product by its id. :param request: request with "id" field. :return: respo... | Implement the Python class `ProductView` described below.
Class description:
ProductView provides handlers for different methods on single product.
Method signatures and docstrings:
- def get(self, request: Request) -> Response: Get info about product by its id. :param request: request with "id" field. :return: respo... | ef31cba8656b66d8fdbdd6a947bcf00a3ad3f92a | <|skeleton|>
class ProductView:
"""ProductView provides handlers for different methods on single product."""
def get(self, request: Request) -> Response:
"""Get info about product by its id. :param request: request with "id" field. :return: response whether request is successful with info about product... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductView:
"""ProductView provides handlers for different methods on single product."""
def get(self, request: Request) -> Response:
"""Get info about product by its id. :param request: request with "id" field. :return: response whether request is successful with info about product."""
... | the_stack_v2_python_sparse | online-store/backend/views.py | TmLev/microservices | train | 1 |
9de9be0619f5ac63abfcbf56b7adc8bba3bc3651 | [
"def retrieve_machine(*_args, **_kwargs):\n self.fail('retrieve_machine called')\nself.mock(catalog.machine_provider, 'retrieve_machine', retrieve_machine)\ncatalog.update_cataloged_instance(ndb.Key(models.Instance, 'fake-instance'))\nself.failIf(models.Instance.query().get())",
"def retrieve_machine(*_args, *... | <|body_start_0|>
def retrieve_machine(*_args, **_kwargs):
self.fail('retrieve_machine called')
self.mock(catalog.machine_provider, 'retrieve_machine', retrieve_machine)
catalog.update_cataloged_instance(ndb.Key(models.Instance, 'fake-instance'))
self.failIf(models.Instance.qu... | Tests for catalog.update_cataloged_entry. | UpdateCatalogedEntryTest | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateCatalogedEntryTest:
"""Tests for catalog.update_cataloged_entry."""
def test_not_found(self):
"""Ensures nothing happens when the instance doesn't exist."""
<|body_0|>
def test_not_cataloged(self):
"""Ensures nothing happens when the instance is not catalog... | stack_v2_sparse_classes_75kplus_train_072787 | 16,348 | permissive | [
{
"docstring": "Ensures nothing happens when the instance doesn't exist.",
"name": "test_not_found",
"signature": "def test_not_found(self)"
},
{
"docstring": "Ensures nothing happens when the instance is not cataloged.",
"name": "test_not_cataloged",
"signature": "def test_not_cataloged... | 5 | null | Implement the Python class `UpdateCatalogedEntryTest` described below.
Class description:
Tests for catalog.update_cataloged_entry.
Method signatures and docstrings:
- def test_not_found(self): Ensures nothing happens when the instance doesn't exist.
- def test_not_cataloged(self): Ensures nothing happens when the in... | Implement the Python class `UpdateCatalogedEntryTest` described below.
Class description:
Tests for catalog.update_cataloged_entry.
Method signatures and docstrings:
- def test_not_found(self): Ensures nothing happens when the instance doesn't exist.
- def test_not_cataloged(self): Ensures nothing happens when the in... | 0a4fdfc25f89833026be6a8b29c0a27b8f3c5fc4 | <|skeleton|>
class UpdateCatalogedEntryTest:
"""Tests for catalog.update_cataloged_entry."""
def test_not_found(self):
"""Ensures nothing happens when the instance doesn't exist."""
<|body_0|>
def test_not_cataloged(self):
"""Ensures nothing happens when the instance is not catalog... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateCatalogedEntryTest:
"""Tests for catalog.update_cataloged_entry."""
def test_not_found(self):
"""Ensures nothing happens when the instance doesn't exist."""
def retrieve_machine(*_args, **_kwargs):
self.fail('retrieve_machine called')
self.mock(catalog.machine_pr... | the_stack_v2_python_sparse | appengine/gce-backend/catalog_test.py | Swift1313/luci-py | train | 0 |
cd51951988cc830caa77f03f2eeb40d2fcc4bf9b | [
"super(SelfAttention, self).__init__()\nself.in_channel = in_channel\nif out_channel is not None:\n self.out_channel = out_channel\nelse:\n self.out_channel = in_channel\nself.temperature = self.out_channel ** 0.5\nself.q_map = nn.Conv1d(in_channel, out_channel, 1, bias=False)\nself.k_map = nn.Conv1d(in_chann... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.in_channel = in_channel
if out_channel is not None:
self.out_channel = out_channel
else:
self.out_channel = in_channel
self.temperature = self.out_channel ** 0.5
self.q_map = nn.Conv1d(in_... | SelfAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
def __init__(self, in_channel, out_channel=None, attn_dropout=0.1):
""":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel"""
<|body_0|>
def forward(self, x):
""":param x: the f... | stack_v2_sparse_classes_75kplus_train_072788 | 1,662 | permissive | [
{
"docstring": ":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel",
"name": "__init__",
"signature": "def __init__(self, in_channel, out_channel=None, attn_dropout=0.1)"
},
{
"docstring": ":param x: the feature maps fro... | 2 | stack_v2_sparse_classes_30k_train_010101 | Implement the Python class `SelfAttention` described below.
Class description:
Implement the SelfAttention class.
Method signatures and docstrings:
- def __init__(self, in_channel, out_channel=None, attn_dropout=0.1): :param in_channel: previous layer's output feature dimension :param out_channel: size of output vect... | Implement the Python class `SelfAttention` described below.
Class description:
Implement the SelfAttention class.
Method signatures and docstrings:
- def __init__(self, in_channel, out_channel=None, attn_dropout=0.1): :param in_channel: previous layer's output feature dimension :param out_channel: size of output vect... | d046b36458a5b0c57b4783e597bb180fccc4ddb2 | <|skeleton|>
class SelfAttention:
def __init__(self, in_channel, out_channel=None, attn_dropout=0.1):
""":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel"""
<|body_0|>
def forward(self, x):
""":param x: the f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
def __init__(self, in_channel, out_channel=None, attn_dropout=0.1):
""":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel"""
super(SelfAttention, self).__init__()
self.in_channel = in_channel
... | the_stack_v2_python_sparse | models/attention.py | henghuiding/attMPTI | train | 1 | |
4395b639ad576525383ef131324562623231576c | [
"num = 1\nif len(s) < 2:\n return len(s)\nelse:\n for i in range(len(s)):\n for j in range(i + 2, len(s) + 1):\n ss = s[i:j]\n if len(set(s[i:j])) == len(s[i:j]):\n if len(s[i:j]) > num:\n num = len(s[i:j])\n else:\n brea... | <|body_start_0|>
num = 1
if len(s) < 2:
return len(s)
else:
for i in range(len(s)):
for j in range(i + 2, len(s) + 1):
ss = s[i:j]
if len(set(s[i:j])) == len(s[i:j]):
if len(s[i:j]) > num:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def lengthOfLongestSubstring3(self, s):
""":type s: str :rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_072789 | 2,438 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
},
{
"docst... | 5 | stack_v2_sparse_classes_30k_train_034465 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring3(self, s): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring3(self, s): :type... | f1d780b7e8b91b4df704651514018143c6931f9d | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def lengthOfLongestSubstring3(self, s):
""":type s: str :rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
num = 1
if len(s) < 2:
return len(s)
else:
for i in range(len(s)):
for j in range(i + 2, len(s) + 1):
ss = s[i:j]
if l... | the_stack_v2_python_sparse | ProgramForLeetCode/LeetCode/3_lengthOfLongestSubstring.py | DQDH/Algorithm_Code | train | 0 | |
b04a718e315027c66fc980f84291d8ccd17f3527 | [
"super(HypersphereLoss, self).__init__()\nself.t = t\nself.lam = lam\nself.alpha = alpha",
"x = F.normalize(z_a)\ny = F.normalize(z_b)\n\ndef lalign(x, y):\n return (x - y).norm(dim=1).pow(self.alpha).mean()\n\ndef lunif(x):\n sq_pdist = torch.pdist(x, p=2).pow(2)\n return sq_pdist.mul(-self.t).exp().mea... | <|body_start_0|>
super(HypersphereLoss, self).__init__()
self.t = t
self.lam = lam
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
x = F.normalize(z_a)
y = F.normalize(z_b)
def lalign(x, y):
return (x - y).norm(dim=1).pow(self.alpha).mean()
... | Implementation of the loss described in 'Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere.' [0] [0] Tongzhou Wang. et.al, 2020, ... https://arxiv.org/abs/2005.10242 Note: In order for this loss to function as advertized, an l1-normalization to the hypersphere is requ... | HypersphereLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HypersphereLoss:
"""Implementation of the loss described in 'Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere.' [0] [0] Tongzhou Wang. et.al, 2020, ... https://arxiv.org/abs/2005.10242 Note: In order for this loss to function as advertized, an ... | stack_v2_sparse_classes_75kplus_train_072790 | 3,477 | permissive | [
{
"docstring": "Parameters as described in [0] Args: t : float Temperature parameter; proportional to the inverse variance of the Gaussians used to measure uniformity lam : float: Weight balancing the alignment and uniformity loss terms alpha : float Power applied to the alignment term of the loss. At its defau... | 2 | stack_v2_sparse_classes_30k_train_008371 | Implement the Python class `HypersphereLoss` described below.
Class description:
Implementation of the loss described in 'Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere.' [0] [0] Tongzhou Wang. et.al, 2020, ... https://arxiv.org/abs/2005.10242 Note: In order for t... | Implement the Python class `HypersphereLoss` described below.
Class description:
Implementation of the loss described in 'Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere.' [0] [0] Tongzhou Wang. et.al, 2020, ... https://arxiv.org/abs/2005.10242 Note: In order for t... | 5650ee8d4057139acf8aa10c884d5d5cdc2ccb17 | <|skeleton|>
class HypersphereLoss:
"""Implementation of the loss described in 'Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere.' [0] [0] Tongzhou Wang. et.al, 2020, ... https://arxiv.org/abs/2005.10242 Note: In order for this loss to function as advertized, an ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HypersphereLoss:
"""Implementation of the loss described in 'Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere.' [0] [0] Tongzhou Wang. et.al, 2020, ... https://arxiv.org/abs/2005.10242 Note: In order for this loss to function as advertized, an l1-normalizat... | the_stack_v2_python_sparse | lightly/loss/hypersphere_loss.py | lightly-ai/lightly | train | 2,473 |
d17d37989ec89068efcb6dd534acc46c74864df5 | [
"self.__client = Client(verify_ssl_cert=False)\nself.bearer_token = token\nOSM_COMPONENTS = os.environ.get('OSM_COMPONENTS')\nif OSM_COMPONENTS is None:\n print('NO OSM_COMPONENTS in ENV')\nelse:\n self.OSM_COMPONENTS = json.loads(OSM_COMPONENTS)",
"endpoint = '{}/osm/nsd/v1/ns_descriptors'.format(self.OSM_... | <|body_start_0|>
self.__client = Client(verify_ssl_cert=False)
self.bearer_token = token
OSM_COMPONENTS = os.environ.get('OSM_COMPONENTS')
if OSM_COMPONENTS is None:
print('NO OSM_COMPONENTS in ENV')
else:
self.OSM_COMPONENTS = json.loads(OSM_COMPONENTS)
<... | NS Descriptor Class. This class serves as a wrapper for the Network Service Descriptor (NSD) part of the Northbound Interface (NBI) offered by OSM r4. The methods defined in this class help retrieve the NSDs of OSM. Attributes: bearer_token (str): The OSM Authorization Token. Args: token (str): The OSM Authorization To... | Nsd | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nsd:
"""NS Descriptor Class. This class serves as a wrapper for the Network Service Descriptor (NSD) part of the Northbound Interface (NBI) offered by OSM r4. The methods defined in this class help retrieve the NSDs of OSM. Attributes: bearer_token (str): The OSM Authorization Token. Args: token ... | stack_v2_sparse_classes_75kplus_train_072791 | 3,378 | permissive | [
{
"docstring": "NS Descriptor Class Constructor.",
"name": "__init__",
"signature": "def __init__(self, token)"
},
{
"docstring": "Fetch a list of all NS descriptors. Returns: object: A requests object including the list of the NSDs Examples: >>> from nbiapi.identity import bearer_token >>> from... | 3 | null | Implement the Python class `Nsd` described below.
Class description:
NS Descriptor Class. This class serves as a wrapper for the Network Service Descriptor (NSD) part of the Northbound Interface (NBI) offered by OSM r4. The methods defined in this class help retrieve the NSDs of OSM. Attributes: bearer_token (str): Th... | Implement the Python class `Nsd` described below.
Class description:
NS Descriptor Class. This class serves as a wrapper for the Network Service Descriptor (NSD) part of the Northbound Interface (NBI) offered by OSM r4. The methods defined in this class help retrieve the NSDs of OSM. Attributes: bearer_token (str): Th... | a48a15d0190f20913cf313ca28e3daabb3753285 | <|skeleton|>
class Nsd:
"""NS Descriptor Class. This class serves as a wrapper for the Network Service Descriptor (NSD) part of the Northbound Interface (NBI) offered by OSM r4. The methods defined in this class help retrieve the NSDs of OSM. Attributes: bearer_token (str): The OSM Authorization Token. Args: token ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Nsd:
"""NS Descriptor Class. This class serves as a wrapper for the Network Service Descriptor (NSD) part of the Northbound Interface (NBI) offered by OSM r4. The methods defined in this class help retrieve the NSDs of OSM. Attributes: bearer_token (str): The OSM Authorization Token. Args: token (str): The OS... | the_stack_v2_python_sparse | vnv_manager/app/api/management/commands/osm/nbiapi/nsd.py | sonata-nfv/son-monitor | train | 5 |
6c39fed5aa83373235ac02892df9e0a8455d6d34 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceConfigurationDeviceStateSummary()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'compliantDeviceCount': lambda n: setattr(self, 'compliant_device_count', n.get_int_value())... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceConfigurationDeviceStateSummary()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'complia... | DeviceConfigurationDeviceStateSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceConfigurationDeviceStateSummary:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationDeviceStateSummary:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the d... | stack_v2_sparse_classes_75kplus_train_072792 | 3,764 | 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: DeviceConfigurationDeviceStateSummary",
"name": "create_from_discriminator_value",
"signature": "def create_... | 3 | stack_v2_sparse_classes_30k_train_035649 | Implement the Python class `DeviceConfigurationDeviceStateSummary` described below.
Class description:
Implement the DeviceConfigurationDeviceStateSummary class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationDeviceStateSummary: Crea... | Implement the Python class `DeviceConfigurationDeviceStateSummary` described below.
Class description:
Implement the DeviceConfigurationDeviceStateSummary class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationDeviceStateSummary: Crea... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceConfigurationDeviceStateSummary:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationDeviceStateSummary:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceConfigurationDeviceStateSummary:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationDeviceStateSummary:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | the_stack_v2_python_sparse | msgraph/generated/models/device_configuration_device_state_summary.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e28e80b23443159a5f419b15ea8a1cd5a8596982 | [
"super(Transformer, self).__init__()\nself.drop = nn.Dropout(dropout)\nself.emb = nn.Embedding(ntokens, hidden_size)\nif pos_emb:\n self.pos_emb = nn.Embedding(500, hidden_size)\nself.layers = nn.ModuleList([layers.TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout, dropatt=dropatt, relative_bias=rela... | <|body_start_0|>
super(Transformer, self).__init__()
self.drop = nn.Dropout(dropout)
self.emb = nn.Embedding(ntokens, hidden_size)
if pos_emb:
self.pos_emb = nn.Embedding(500, hidden_size)
self.layers = nn.ModuleList([layers.TransformerLayer(hidden_size, nhead, hidden... | Transformer model. | Transformer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""Transformer model."""
def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0):
"""Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number ... | stack_v2_sparse_classes_75kplus_train_072793 | 12,717 | permissive | [
{
"docstring": "Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number of output categories nhead: number of self-attention heads dropout: dropout rate dropatt: drop attention rate relative_bias: bool, indicate whether use a relative position based att... | 5 | stack_v2_sparse_classes_30k_val_001508 | Implement the Python class `Transformer` described below.
Class description:
Transformer model.
Method signatures and docstrings:
- def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0): Initialization. Args: hidden_size: dimension of inputs and... | Implement the Python class `Transformer` described below.
Class description:
Transformer model.
Method signatures and docstrings:
- def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0): Initialization. Args: hidden_size: dimension of inputs and... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Transformer:
"""Transformer model."""
def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0):
"""Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transformer:
"""Transformer model."""
def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0):
"""Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number of output cat... | the_stack_v2_python_sparse | structformer/structformer.py | Jimmy-INL/google-research | train | 1 |
46ef8270f95a390447d1b040233d4689fcfcb1dc | [
"if len(alias) == 1:\n (provider, name), = alias.items()\nelse:\n raise AttributeError(f'Expected single named alias')\ntry:\n session = session or _Session()\n return session.query(Object).filter(Object.aliases[provider] == type_coerce(name, JSON)).one()\nexcept NoResultFound as error:\n raise Objec... | <|body_start_0|>
if len(alias) == 1:
(provider, name), = alias.items()
else:
raise AttributeError(f'Expected single named alias')
try:
session = session or _Session()
return session.query(Object).filter(Object.aliases[provider] == type_coerce(name,... | Object table. | Object | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Object:
"""Object table."""
def from_alias(cls, session: _Session=None, **alias: str) -> Object:
"""Query by named field in `aliases`."""
<|body_0|>
def add_alias(cls, object_id: int, session: _Session=None, **aliases: str) -> None:
"""Add alias(es) to the given ... | stack_v2_sparse_classes_75kplus_train_072794 | 49,365 | permissive | [
{
"docstring": "Query by named field in `aliases`.",
"name": "from_alias",
"signature": "def from_alias(cls, session: _Session=None, **alias: str) -> Object"
},
{
"docstring": "Add alias(es) to the given object.",
"name": "add_alias",
"signature": "def add_alias(cls, object_id: int, sess... | 2 | stack_v2_sparse_classes_30k_train_043910 | Implement the Python class `Object` described below.
Class description:
Object table.
Method signatures and docstrings:
- def from_alias(cls, session: _Session=None, **alias: str) -> Object: Query by named field in `aliases`.
- def add_alias(cls, object_id: int, session: _Session=None, **aliases: str) -> None: Add al... | Implement the Python class `Object` described below.
Class description:
Object table.
Method signatures and docstrings:
- def from_alias(cls, session: _Session=None, **alias: str) -> Object: Query by named field in `aliases`.
- def add_alias(cls, object_id: int, session: _Session=None, **aliases: str) -> None: Add al... | 3f226912ec8d303a067b7c2b794afbb15af00cf9 | <|skeleton|>
class Object:
"""Object table."""
def from_alias(cls, session: _Session=None, **alias: str) -> Object:
"""Query by named field in `aliases`."""
<|body_0|>
def add_alias(cls, object_id: int, session: _Session=None, **aliases: str) -> None:
"""Add alias(es) to the given ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Object:
"""Object table."""
def from_alias(cls, session: _Session=None, **alias: str) -> Object:
"""Query by named field in `aliases`."""
if len(alias) == 1:
(provider, name), = alias.items()
else:
raise AttributeError(f'Expected single named alias')
... | the_stack_v2_python_sparse | refitt/database/model.py | Feliconut/refitt | train | 0 |
c8b27eee8b5c9b83117c4c30bedf601980475f03 | [
"fig_legend = self.get_legend()\nif self.show_legend is not False and fig_legend is not None:\n fig_legend.set_visible(True)\nself.grid(grid_on=True)",
"de = CDensityEstimation(**params)\nxm, malicious_pdf = de.estimate_density(scores[ts.Y == 1])\nxb, benign_pdf = de.estimate_density(scores[ts.Y == 0])\nself.p... | <|body_start_0|>
fig_legend = self.get_legend()
if self.show_legend is not False and fig_legend is not None:
fig_legend.set_visible(True)
self.grid(grid_on=True)
<|end_body_0|>
<|body_start_1|>
de = CDensityEstimation(**params)
xm, malicious_pdf = de.estimate_density... | Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures. | CPlotStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPlotStats:
"""Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures."""
def apply_params_stats(self):
""... | stack_v2_sparse_classes_75kplus_train_072795 | 1,328 | permissive | [
{
"docstring": "Apply defined parameters to active subplot.",
"name": "apply_params_stats",
"signature": "def apply_params_stats(self)"
},
{
"docstring": "Plot density estimation of benign and malicious class.",
"name": "plot_prob_density",
"signature": "def plot_prob_density(self, score... | 2 | stack_v2_sparse_classes_30k_train_003847 | Implement the Python class `CPlotStats` described below.
Class description:
Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures.
Method s... | Implement the Python class `CPlotStats` described below.
Class description:
Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures.
Method s... | 431373e65d8cfe2cb7cf042ce1a6c9519ea5a14a | <|skeleton|>
class CPlotStats:
"""Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures."""
def apply_params_stats(self):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CPlotStats:
"""Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures."""
def apply_params_stats(self):
"""Apply define... | the_stack_v2_python_sparse | src/secml/figure/_plots/c_plot_stats.py | Cinofix/secml | train | 0 |
1784b2e1712998a86ea4fca42fd2e03280f4362e | [
"\"\"\"The wrapped pool resource.\"\"\"\nself.object = obj\n'Whether the resource is currently in use.'\nself.claimed = False\n'The pool that this resource belongs to.'\nself.pool = pool\n'True if this Resource errored.'\nself.errored = False",
"if self.errored:\n self.pool.delete_resource(self)\nelse:\n se... | <|body_start_0|>
"""The wrapped pool resource."""
self.object = obj
'Whether the resource is currently in use.'
self.claimed = False
'The pool that this resource belongs to.'
self.pool = pool
'True if this Resource errored.'
self.errored = False
<|end_body... | A member of the :class:`Pool`, a container for the actual resource being pooled and a marker for whether the resource is currently claimed. | Resource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""A member of the :class:`Pool`, a container for the actual resource being pooled and a marker for whether the resource is currently claimed."""
def __init__(self, obj, pool):
"""Creates a new Resource, wrapping the passed object as the pooled resource. :param obj: the res... | stack_v2_sparse_classes_75kplus_train_072796 | 9,985 | permissive | [
{
"docstring": "Creates a new Resource, wrapping the passed object as the pooled resource. :param obj: the resource to wrap :type obj: object",
"name": "__init__",
"signature": "def __init__(self, obj, pool)"
},
{
"docstring": "Releases this resource back to the pool it came from.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_015473 | Implement the Python class `Resource` described below.
Class description:
A member of the :class:`Pool`, a container for the actual resource being pooled and a marker for whether the resource is currently claimed.
Method signatures and docstrings:
- def __init__(self, obj, pool): Creates a new Resource, wrapping the ... | Implement the Python class `Resource` described below.
Class description:
A member of the :class:`Pool`, a container for the actual resource being pooled and a marker for whether the resource is currently claimed.
Method signatures and docstrings:
- def __init__(self, obj, pool): Creates a new Resource, wrapping the ... | 91de13a16607cdf553d1a194e762734e3bec4231 | <|skeleton|>
class Resource:
"""A member of the :class:`Pool`, a container for the actual resource being pooled and a marker for whether the resource is currently claimed."""
def __init__(self, obj, pool):
"""Creates a new Resource, wrapping the passed object as the pooled resource. :param obj: the res... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resource:
"""A member of the :class:`Pool`, a container for the actual resource being pooled and a marker for whether the resource is currently claimed."""
def __init__(self, obj, pool):
"""Creates a new Resource, wrapping the passed object as the pooled resource. :param obj: the resource to wrap... | the_stack_v2_python_sparse | riak/transports/pool.py | EDITD/riak-python-client | train | 0 |
6b73ac4b3bc78b60632af28d95923be1a41b7ded | [
"classstudy_obj = models.ClassStudyRecord.objects.all()\nprint(classstudy_obj)\nreturn render(request, 'jilu/classstudyrecord.html', {'classstudy_obj': classstudy_obj})",
"action = request.POST.get('action')\nselected_id = request.POST.get('selected_id')\nif hasattr(self, action):\n print(1)\n getattr(self,... | <|body_start_0|>
classstudy_obj = models.ClassStudyRecord.objects.all()
print(classstudy_obj)
return render(request, 'jilu/classstudyrecord.html', {'classstudy_obj': classstudy_obj})
<|end_body_0|>
<|body_start_1|>
action = request.POST.get('action')
selected_id = request.POST.g... | ClassStudyRecord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassStudyRecord:
def get(self, request):
"""获取班级课程记录表的信息并将其呈现在网页上 :param request: :return:"""
<|body_0|>
def post(self, request):
"""从网页上获取用户进行的操作action :param request: :return:"""
<|body_1|>
def batch_delete(self, selected_id):
"""用户在班级课程页面上进行的... | stack_v2_sparse_classes_75kplus_train_072797 | 19,697 | no_license | [
{
"docstring": "获取班级课程记录表的信息并将其呈现在网页上 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "从网页上获取用户进行的操作action :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "用户在班级课程页面上进行的操作的后台执行流程... | 3 | stack_v2_sparse_classes_30k_train_035227 | Implement the Python class `ClassStudyRecord` described below.
Class description:
Implement the ClassStudyRecord class.
Method signatures and docstrings:
- def get(self, request): 获取班级课程记录表的信息并将其呈现在网页上 :param request: :return:
- def post(self, request): 从网页上获取用户进行的操作action :param request: :return:
- def batch_delete(... | Implement the Python class `ClassStudyRecord` described below.
Class description:
Implement the ClassStudyRecord class.
Method signatures and docstrings:
- def get(self, request): 获取班级课程记录表的信息并将其呈现在网页上 :param request: :return:
- def post(self, request): 从网页上获取用户进行的操作action :param request: :return:
- def batch_delete(... | 8751baf67a744867a93ac02dc5ef96b70431e35c | <|skeleton|>
class ClassStudyRecord:
def get(self, request):
"""获取班级课程记录表的信息并将其呈现在网页上 :param request: :return:"""
<|body_0|>
def post(self, request):
"""从网页上获取用户进行的操作action :param request: :return:"""
<|body_1|>
def batch_delete(self, selected_id):
"""用户在班级课程页面上进行的... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassStudyRecord:
def get(self, request):
"""获取班级课程记录表的信息并将其呈现在网页上 :param request: :return:"""
classstudy_obj = models.ClassStudyRecord.objects.all()
print(classstudy_obj)
return render(request, 'jilu/classstudyrecord.html', {'classstudy_obj': classstudy_obj})
def post(sel... | the_stack_v2_python_sparse | crmtest/app01/views.py | jingdaonb/personal | train | 0 | |
fc2aeabca5ab13924be1b872d7ec6d03e207b1df | [
"super(MLP, self).__init__()\nself.hidden_sizes = hidden_sizes\nself.input_size = input_size\nself.output_size = output_size\nself.hidden_activation = hidden_activation\nself.output_activation = output_activation\nself.linear_layer = linear_layer\nself.use_output_layer = use_output_layer\nself.n_category = n_catego... | <|body_start_0|>
super(MLP, self).__init__()
self.hidden_sizes = hidden_sizes
self.input_size = input_size
self.output_size = output_size
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.linear_layer = linear_layer
... | Baseline of Multilayer perceptron. The layer-norm is not implemented here Attributes: input_size (int): size of input output_size (int): size of output layer hidden_sizes (list): sizes of hidden layers hidden_activation: activation function of hidden layers output_activation: activation function of output layer hidden_... | MLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""Baseline of Multilayer perceptron. The layer-norm is not implemented here Attributes: input_size (int): size of input output_size (int): size of output layer hidden_sizes (list): sizes of hidden layers hidden_activation: activation function of hidden layers output_activation: activation f... | stack_v2_sparse_classes_75kplus_train_072798 | 10,144 | no_license | [
{
"docstring": "Initialize. Args: input_size (int): size of input output_size (int): size of output layer hidden_sizes (list): number of hidden layers hidden_activation: activation function of hidden layers output_activation: activation function of output layer linear_layer (nn.Module): linear layer of mlp use_... | 2 | stack_v2_sparse_classes_30k_train_016637 | Implement the Python class `MLP` described below.
Class description:
Baseline of Multilayer perceptron. The layer-norm is not implemented here Attributes: input_size (int): size of input output_size (int): size of output layer hidden_sizes (list): sizes of hidden layers hidden_activation: activation function of hidden... | Implement the Python class `MLP` described below.
Class description:
Baseline of Multilayer perceptron. The layer-norm is not implemented here Attributes: input_size (int): size of input output_size (int): size of output layer hidden_sizes (list): sizes of hidden layers hidden_activation: activation function of hidden... | 2d70d4792e78ceefd4626302fa85e7774e2ff250 | <|skeleton|>
class MLP:
"""Baseline of Multilayer perceptron. The layer-norm is not implemented here Attributes: input_size (int): size of input output_size (int): size of output layer hidden_sizes (list): sizes of hidden layers hidden_activation: activation function of hidden layers output_activation: activation f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLP:
"""Baseline of Multilayer perceptron. The layer-norm is not implemented here Attributes: input_size (int): size of input output_size (int): size of output layer hidden_sizes (list): sizes of hidden layers hidden_activation: activation function of hidden layers output_activation: activation function of ou... | the_stack_v2_python_sparse | src/SDRL_Project/learning_agents/architectures/mlp.py | sbhambr1/symbolic_planning_and_rl | train | 0 |
050450da445dcea31da306828a328bd9d2f3b66a | [
"self.lacp_rate = lacp_rate\nself.mode = mode\nself.xmit_hash_policy = xmit_hash_policy",
"if dictionary is None:\n return None\nlacp_rate = dictionary.get('lacpRate')\nmode = dictionary.get('mode')\nxmit_hash_policy = dictionary.get('xmitHashPolicy')\nreturn cls(lacp_rate, mode, xmit_hash_policy)"
] | <|body_start_0|>
self.lacp_rate = lacp_rate
self.mode = mode
self.xmit_hash_policy = xmit_hash_policy
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
lacp_rate = dictionary.get('lacpRate')
mode = dictionary.get('mode')
xmit_hash_pol... | Implementation of the 'BondingOpts' model. Bonding Opts Attributes: lacp_rate (string): TODO: Type description here. mode (string): TODO: Type description here. xmit_hash_policy (string): TODO: Type description here. | BondingOpts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BondingOpts:
"""Implementation of the 'BondingOpts' model. Bonding Opts Attributes: lacp_rate (string): TODO: Type description here. mode (string): TODO: Type description here. xmit_hash_policy (string): TODO: Type description here."""
def __init__(self, lacp_rate=None, mode=None, xmit_hash_... | stack_v2_sparse_classes_75kplus_train_072799 | 1,747 | permissive | [
{
"docstring": "Constructor for the BondingOpts class",
"name": "__init__",
"signature": "def __init__(self, lacp_rate=None, mode=None, xmit_hash_policy=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the... | 2 | stack_v2_sparse_classes_30k_train_048741 | Implement the Python class `BondingOpts` described below.
Class description:
Implementation of the 'BondingOpts' model. Bonding Opts Attributes: lacp_rate (string): TODO: Type description here. mode (string): TODO: Type description here. xmit_hash_policy (string): TODO: Type description here.
Method signatures and do... | Implement the Python class `BondingOpts` described below.
Class description:
Implementation of the 'BondingOpts' model. Bonding Opts Attributes: lacp_rate (string): TODO: Type description here. mode (string): TODO: Type description here. xmit_hash_policy (string): TODO: Type description here.
Method signatures and do... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BondingOpts:
"""Implementation of the 'BondingOpts' model. Bonding Opts Attributes: lacp_rate (string): TODO: Type description here. mode (string): TODO: Type description here. xmit_hash_policy (string): TODO: Type description here."""
def __init__(self, lacp_rate=None, mode=None, xmit_hash_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BondingOpts:
"""Implementation of the 'BondingOpts' model. Bonding Opts Attributes: lacp_rate (string): TODO: Type description here. mode (string): TODO: Type description here. xmit_hash_policy (string): TODO: Type description here."""
def __init__(self, lacp_rate=None, mode=None, xmit_hash_policy=None):... | the_stack_v2_python_sparse | cohesity_management_sdk/models/bonding_opts.py | cohesity/management-sdk-python | train | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.