blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6f2d9ae8762d2525aad8895a88b6a2dd71e62528 | [
"print('-- create with check --')\nobj = self.filter(**field_check)\nif obj:\n obj = obj[0]\nelse:\n obj = self.create(**kwargs)\nreturn obj",
"print('-- delete with check --')\nif field_check:\n objs = self.filter(id__in=field_check)\nelse:\n objs = self.all()\nif hasattr(self.model, 'username'):\n ... | <|body_start_0|>
print('-- create with check --')
obj = self.filter(**field_check)
if obj:
obj = obj[0]
else:
obj = self.create(**kwargs)
return obj
<|end_body_0|>
<|body_start_1|>
print('-- delete with check --')
if field_check:
... | CRUDManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRUDManager:
def create_with_field_check(self, field_check, **kwargs):
"""创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象"""
<|body_0|>
def delete_with_field_check(self, field_check):
"""批量删除对象 Args: field_check: 待删除对象的id列表 Returns: objs: 删除成功的对象"""
<|bo... | stack_v2_sparse_classes_36k_train_029000 | 1,985 | no_license | [
{
"docstring": "创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象",
"name": "create_with_field_check",
"signature": "def create_with_field_check(self, field_check, **kwargs)"
},
{
"docstring": "批量删除对象 Args: field_check: 待删除对象的id列表 Returns: objs: 删除成功的对象",
"name": "delete_with_field_check"... | 2 | stack_v2_sparse_classes_30k_train_020537 | Implement the Python class `CRUDManager` described below.
Class description:
Implement the CRUDManager class.
Method signatures and docstrings:
- def create_with_field_check(self, field_check, **kwargs): 创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象
- def delete_with_field_check(self, field_check): 批量删除对象 Args... | Implement the Python class `CRUDManager` described below.
Class description:
Implement the CRUDManager class.
Method signatures and docstrings:
- def create_with_field_check(self, field_check, **kwargs): 创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象
- def delete_with_field_check(self, field_check): 批量删除对象 Args... | 6e5a498dd5b63117a6a20aa81ac67a1999d8ac21 | <|skeleton|>
class CRUDManager:
def create_with_field_check(self, field_check, **kwargs):
"""创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象"""
<|body_0|>
def delete_with_field_check(self, field_check):
"""批量删除对象 Args: field_check: 待删除对象的id列表 Returns: objs: 删除成功的对象"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CRUDManager:
def create_with_field_check(self, field_check, **kwargs):
"""创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象"""
print('-- create with check --')
obj = self.filter(**field_check)
if obj:
obj = obj[0]
else:
obj = self.create(**kwa... | the_stack_v2_python_sparse | career/core/managers.py | wyzane/skill-general | train | 0 | |
834b2230ce6db88597d40eefee246cd070ae7e77 | [
"T = '#'.join('!{}%'.format(s))\nC, R = (0, 0)\nP = []\nfor i in range(len(T)):\n P.append(0)\nfor i in range(1, len(T) - 1):\n if i < R:\n P[i] = min(R - i, P[2 * C - i])\n while T[i + P[i] + 1] == T[i - P[i] - 1]:\n P[i] += 1\n if i + P[i] > R:\n C, R = (i, i + P[i])\nradius, inde... | <|body_start_0|>
T = '#'.join('!{}%'.format(s))
C, R = (0, 0)
P = []
for i in range(len(T)):
P.append(0)
for i in range(1, len(T) - 1):
if i < R:
P[i] = min(R - i, P[2 * C - i])
while T[i + P[i] + 1] == T[i - P[i] - 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome_TLE(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
T = '#'.join('!{}%'.format(s))
C, R = (0, 0)
... | stack_v2_sparse_classes_36k_train_029001 | 2,211 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome_TLE",
"signature": "def longestPalindrome_TLE(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome_TLE(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome_TLE(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalindrome(s... | ed0837ce14a22660657ffd15ff99d7cb1804e8c1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome_TLE(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
T = '#'.join('!{}%'.format(s))
C, R = (0, 0)
P = []
for i in range(len(T)):
P.append(0)
for i in range(1, len(T) - 1):
if i < R:
P[i] = min(R - i, P[... | the_stack_v2_python_sparse | python/005-longest-palindromic-substring.py | ByronHsu/leetcode | train | 5 | |
7070090a920da7106ca6de4a1a60287741ce5e16 | [
"matrix = conf.data.matrix\nlen = conf.data.datalen\nif matrix[0] * matrix[1] != len:\n errMsg.append({'code': '000001', 'msg': 'Matrix size and data len unmatach'})\nreturn errMsg",
"num_layers = len(conf.layer)\nfor i in range(0, int(num_layers)):\n if len(conf.layer) <= 0:\n errMsg.append({'code':... | <|body_start_0|>
matrix = conf.data.matrix
len = conf.data.datalen
if matrix[0] * matrix[1] != len:
errMsg.append({'code': '000001', 'msg': 'Matrix size and data len unmatach'})
return errMsg
<|end_body_0|>
<|body_start_1|>
num_layers = len(conf.layer)
for i ... | simple error check for network configuration | CNNConfCheck | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNConfCheck:
"""simple error check for network configuration"""
def check_matrix_size_match(self, errMsg, conf):
"""check initial matrix size :param errMsg: detail config error message :param conf: currently set network configuration :return: append error message on list"""
... | stack_v2_sparse_classes_36k_train_029002 | 2,497 | no_license | [
{
"docstring": "check initial matrix size :param errMsg: detail config error message :param conf: currently set network configuration :return: append error message on list",
"name": "check_matrix_size_match",
"signature": "def check_matrix_size_match(self, errMsg, conf)"
},
{
"docstring": "simpl... | 3 | null | Implement the Python class `CNNConfCheck` described below.
Class description:
simple error check for network configuration
Method signatures and docstrings:
- def check_matrix_size_match(self, errMsg, conf): check initial matrix size :param errMsg: detail config error message :param conf: currently set network config... | Implement the Python class `CNNConfCheck` described below.
Class description:
simple error check for network configuration
Method signatures and docstrings:
- def check_matrix_size_match(self, errMsg, conf): check initial matrix size :param errMsg: detail config error message :param conf: currently set network config... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class CNNConfCheck:
"""simple error check for network configuration"""
def check_matrix_size_match(self, errMsg, conf):
"""check initial matrix size :param errMsg: detail config error message :param conf: currently set network configuration :return: append error message on list"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNNConfCheck:
"""simple error check for network configuration"""
def check_matrix_size_match(self, errMsg, conf):
"""check initial matrix size :param errMsg: detail config error message :param conf: currently set network configuration :return: append error message on list"""
matrix = conf... | the_stack_v2_python_sparse | tfmsacore/validation/conv_checker.py | TensorMSA/tensormsa_old | train | 6 |
22d16349dc78bfb3a087e493bcc0d4bb6269b084 | [
"self.to_units = to_units\nself.kilo_prefix = kilo_prefix\nself._prefix_conversions = None\nself._bits_to_bytes = None\nself._bytes_to_bits = None\nself.bit_conversions = self.byte_conversions = len(to_units) // 2\nself.bit_units = to_units[:self.bit_conversions]\nself.byte_units = to_units[self.byte_conversions:]\... | <|body_start_0|>
self.to_units = to_units
self.kilo_prefix = kilo_prefix
self._prefix_conversions = None
self._bits_to_bytes = None
self._bytes_to_bits = None
self.bit_conversions = self.byte_conversions = len(to_units) // 2
self.bit_units = to_units[:self.bit_con... | A creator of unit-conversion dictionaries | BaseConverter | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseConverter:
"""A creator of unit-conversion dictionaries"""
def __init__(self, to_units, kilo_prefix):
"""base_converter constructor :param: - `to_units`: a list of the units to covert to (has to be half to-bits, half to-bytes) - `kilo_prefix`: kilo multiplier matching type of uni... | stack_v2_sparse_classes_36k_train_029003 | 10,932 | permissive | [
{
"docstring": "base_converter constructor :param: - `to_units`: a list of the units to covert to (has to be half to-bits, half to-bytes) - `kilo_prefix`: kilo multiplier matching type of units",
"name": "__init__",
"signature": "def __init__(self, to_units, kilo_prefix)"
},
{
"docstring": "List... | 6 | stack_v2_sparse_classes_30k_train_014212 | Implement the Python class `BaseConverter` described below.
Class description:
A creator of unit-conversion dictionaries
Method signatures and docstrings:
- def __init__(self, to_units, kilo_prefix): base_converter constructor :param: - `to_units`: a list of the units to covert to (has to be half to-bits, half to-byt... | Implement the Python class `BaseConverter` described below.
Class description:
A creator of unit-conversion dictionaries
Method signatures and docstrings:
- def __init__(self, to_units, kilo_prefix): base_converter constructor :param: - `to_units`: a list of the units to covert to (has to be half to-bits, half to-byt... | 2007bf3fe66edfe704e485141c55caed54fe13aa | <|skeleton|>
class BaseConverter:
"""A creator of unit-conversion dictionaries"""
def __init__(self, to_units, kilo_prefix):
"""base_converter constructor :param: - `to_units`: a list of the units to covert to (has to be half to-bits, half to-bytes) - `kilo_prefix`: kilo multiplier matching type of uni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseConverter:
"""A creator of unit-conversion dictionaries"""
def __init__(self, to_units, kilo_prefix):
"""base_converter constructor :param: - `to_units`: a list of the units to covert to (has to be half to-bits, half to-bytes) - `kilo_prefix`: kilo multiplier matching type of units"""
... | the_stack_v2_python_sparse | utils/iperflexer/unitconverter.py | AndriyZabavskyy/taf | train | 0 |
5f8b7d6416e7eb805fe5ab5fdf9d208b1bfa85c4 | [
"if self.has_option('sssd', 'domains'):\n domains = self.get('sssd', 'domains')\n if domains:\n return [domain.strip() for domain in domains.split(',')]\nreturn []",
"full_domain = 'domain/' + domain\nif full_domain not in self:\n return {}\nreturn self.items(full_domain)"
] | <|body_start_0|>
if self.has_option('sssd', 'domains'):
domains = self.get('sssd', 'domains')
if domains:
return [domain.strip() for domain in domains.split(',')]
return []
<|end_body_0|>
<|body_start_1|>
full_domain = 'domain/' + domain
if full_d... | Parse the content of the ``/etc/sssd/sssd.config`` file. The 'sssd' section must always exist. Within that, the 'domains' parameter is usually defined to give a comma-separated list of the domains that sssd is to manage. The 'sssd' section will define one or more active domains, which are then configured in the 'domain... | SSSD_Config | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSSD_Config:
"""Parse the content of the ``/etc/sssd/sssd.config`` file. The 'sssd' section must always exist. Within that, the 'domains' parameter is usually defined to give a comma-separated list of the domains that sssd is to manage. The 'sssd' section will define one or more active domains, w... | stack_v2_sparse_classes_36k_train_029004 | 3,694 | permissive | [
{
"docstring": "Returns the list of domains defined in the 'sssd' section. This is used to refer to the domain-specific sections of the configuration.",
"name": "domains",
"signature": "def domains(self)"
},
{
"docstring": "Return the configuration dictionary for a specific domain, given as the ... | 2 | null | Implement the Python class `SSSD_Config` described below.
Class description:
Parse the content of the ``/etc/sssd/sssd.config`` file. The 'sssd' section must always exist. Within that, the 'domains' parameter is usually defined to give a comma-separated list of the domains that sssd is to manage. The 'sssd' section wi... | Implement the Python class `SSSD_Config` described below.
Class description:
Parse the content of the ``/etc/sssd/sssd.config`` file. The 'sssd' section must always exist. Within that, the 'domains' parameter is usually defined to give a comma-separated list of the domains that sssd is to manage. The 'sssd' section wi... | b0ea07fc3f4dd8801b505fe70e9b36e628152c4a | <|skeleton|>
class SSSD_Config:
"""Parse the content of the ``/etc/sssd/sssd.config`` file. The 'sssd' section must always exist. Within that, the 'domains' parameter is usually defined to give a comma-separated list of the domains that sssd is to manage. The 'sssd' section will define one or more active domains, w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSSD_Config:
"""Parse the content of the ``/etc/sssd/sssd.config`` file. The 'sssd' section must always exist. Within that, the 'domains' parameter is usually defined to give a comma-separated list of the domains that sssd is to manage. The 'sssd' section will define one or more active domains, which are then... | the_stack_v2_python_sparse | insights/parsers/sssd_conf.py | RedHatInsights/insights-core | train | 144 |
52381c3a9fda6966481f1adfefe1d01985dcad33 | [
"if self.instrument.attr == 'is_locked':\n return not self.instrument.is_on\nreturn self.instrument.is_on",
"if self.instrument.device_class in DEVICE_CLASSES:\n return self.instrument.device_class\nreturn None"
] | <|body_start_0|>
if self.instrument.attr == 'is_locked':
return not self.instrument.is_on
return self.instrument.is_on
<|end_body_0|>
<|body_start_1|>
if self.instrument.device_class in DEVICE_CLASSES:
return self.instrument.device_class
return None
<|end_body_1|... | Representation of a Volvo sensor. | VolvoSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolvoSensor:
"""Representation of a Volvo sensor."""
def is_on(self):
"""Return True if the binary sensor is on, but invert for the 'Door lock'."""
<|body_0|>
def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_029005 | 1,306 | permissive | [
{
"docstring": "Return True if the binary sensor is on, but invert for the 'Door lock'.",
"name": "is_on",
"signature": "def is_on(self)"
},
{
"docstring": "Return the class of this sensor, from DEVICE_CLASSES.",
"name": "device_class",
"signature": "def device_class(self)"
}
] | 2 | null | Implement the Python class `VolvoSensor` described below.
Class description:
Representation of a Volvo sensor.
Method signatures and docstrings:
- def is_on(self): Return True if the binary sensor is on, but invert for the 'Door lock'.
- def device_class(self): Return the class of this sensor, from DEVICE_CLASSES. | Implement the Python class `VolvoSensor` described below.
Class description:
Representation of a Volvo sensor.
Method signatures and docstrings:
- def is_on(self): Return True if the binary sensor is on, but invert for the 'Door lock'.
- def device_class(self): Return the class of this sensor, from DEVICE_CLASSES.
<... | 8f4ec89be6c2505d8a59eee44de335abe308ac9f | <|skeleton|>
class VolvoSensor:
"""Representation of a Volvo sensor."""
def is_on(self):
"""Return True if the binary sensor is on, but invert for the 'Door lock'."""
<|body_0|>
def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolvoSensor:
"""Representation of a Volvo sensor."""
def is_on(self):
"""Return True if the binary sensor is on, but invert for the 'Door lock'."""
if self.instrument.attr == 'is_locked':
return not self.instrument.is_on
return self.instrument.is_on
def device_cla... | the_stack_v2_python_sparse | homeassistant/components/volvooncall/binary_sensor.py | JeffLIrion/home-assistant | train | 5 |
1d52a9d7f4739b88f3d78141512b91bac13b92c4 | [
"tenants = Tenant.find_all()\ntenant_schema = TenantSchema(only=('id', 'tenant_name'))\nreturn tenant_schema.dump(tenants, many=True)",
"tenant = Tenant.find_by_id(tenant_id)\nif tenant:\n tenant_schema = TenantSchema()\n return tenant_schema.dump(tenant)\nraise BusinessException('Invalid tenant', HTTPStatu... | <|body_start_0|>
tenants = Tenant.find_all()
tenant_schema = TenantSchema(only=('id', 'tenant_name'))
return tenant_schema.dump(tenants, many=True)
<|end_body_0|>
<|body_start_1|>
tenant = Tenant.find_by_id(tenant_id)
if tenant:
tenant_schema = TenantSchema()
... | This class manages tenant service. | TenantService | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenantService:
"""This class manages tenant service."""
def get_all():
"""Get tenants."""
<|body_0|>
def get_by_id(tenant_id):
"""Get tenant by id."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tenants = Tenant.find_all()
tenant_schema... | stack_v2_sparse_classes_36k_train_029006 | 769 | permissive | [
{
"docstring": "Get tenants.",
"name": "get_all",
"signature": "def get_all()"
},
{
"docstring": "Get tenant by id.",
"name": "get_by_id",
"signature": "def get_by_id(tenant_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020133 | Implement the Python class `TenantService` described below.
Class description:
This class manages tenant service.
Method signatures and docstrings:
- def get_all(): Get tenants.
- def get_by_id(tenant_id): Get tenant by id. | Implement the Python class `TenantService` described below.
Class description:
This class manages tenant service.
Method signatures and docstrings:
- def get_all(): Get tenants.
- def get_by_id(tenant_id): Get tenant by id.
<|skeleton|>
class TenantService:
"""This class manages tenant service."""
def get_a... | a1a447f364d1e7414ccb073b0749920ec3523e4a | <|skeleton|>
class TenantService:
"""This class manages tenant service."""
def get_all():
"""Get tenants."""
<|body_0|>
def get_by_id(tenant_id):
"""Get tenant by id."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenantService:
"""This class manages tenant service."""
def get_all():
"""Get tenants."""
tenants = Tenant.find_all()
tenant_schema = TenantSchema(only=('id', 'tenant_name'))
return tenant_schema.dump(tenants, many=True)
def get_by_id(tenant_id):
"""Get tenant... | the_stack_v2_python_sparse | forms-flow-api/src/api/services/tenant.py | sumathi-thirumani-aot/forms-flow-ai | train | 0 |
3abfb123a5a1945e491ab5045b7682fb5129b610 | [
"result = ProductLabelGroup.create(args['label_group_name'])\nif isinstance(result, basestring):\n return (500, result)\nelse:\n return {'id': result.id}",
"corp = CorporationFactory.get()\ncorp.product_label_group_repository.delete_label_group(args['label_group_id'])\nreturn {}"
] | <|body_start_0|>
result = ProductLabelGroup.create(args['label_group_name'])
if isinstance(result, basestring):
return (500, result)
else:
return {'id': result.id}
<|end_body_0|>
<|body_start_1|>
corp = CorporationFactory.get()
corp.product_label_group_re... | 商品标签分类 | AProductLableGroup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AProductLableGroup:
"""商品标签分类"""
def put(args):
"""创建标签分类 :return:"""
<|body_0|>
def delete(args):
"""删除标签分类 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = ProductLabelGroup.create(args['label_group_name'])
if isinstan... | stack_v2_sparse_classes_36k_train_029007 | 893 | no_license | [
{
"docstring": "创建标签分类 :return:",
"name": "put",
"signature": "def put(args)"
},
{
"docstring": "删除标签分类 :return:",
"name": "delete",
"signature": "def delete(args)"
}
] | 2 | null | Implement the Python class `AProductLableGroup` described below.
Class description:
商品标签分类
Method signatures and docstrings:
- def put(args): 创建标签分类 :return:
- def delete(args): 删除标签分类 :return: | Implement the Python class `AProductLableGroup` described below.
Class description:
商品标签分类
Method signatures and docstrings:
- def put(args): 创建标签分类 :return:
- def delete(args): 删除标签分类 :return:
<|skeleton|>
class AProductLableGroup:
"""商品标签分类"""
def put(args):
"""创建标签分类 :return:"""
<|body_0|... | 39860a451678ab50ad93ce8ebe2ef8490af65d62 | <|skeleton|>
class AProductLableGroup:
"""商品标签分类"""
def put(args):
"""创建标签分类 :return:"""
<|body_0|>
def delete(args):
"""删除标签分类 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AProductLableGroup:
"""商品标签分类"""
def put(args):
"""创建标签分类 :return:"""
result = ProductLabelGroup.create(args['label_group_name'])
if isinstance(result, basestring):
return (500, result)
else:
return {'id': result.id}
def delete(args):
"... | the_stack_v2_python_sparse | api/mall/product_label/a_product_label_group.py | chengdg/gaia | train | 0 |
c8152e029f6c81d613270fe69b7cb3ad92907c4c | [
"if flag:\n GroupTree(self.driver).click_menu_by_name('Default', '创建同级')\n title_name = '创建同级'\nelse:\n GroupTree(self.driver).click_menu_by_name('Default', '创建下一级')\n title_name = '创建下一级'\nreturn title_name",
"INPUT_TEXT = (By.XPATH, f'//span[contains(text(),\"{til_name}\")]/parent::div/following-sib... | <|body_start_0|>
if flag:
GroupTree(self.driver).click_menu_by_name('Default', '创建同级')
title_name = '创建同级'
else:
GroupTree(self.driver).click_menu_by_name('Default', '创建下一级')
title_name = '创建下一级'
return title_name
<|end_body_0|>
<|body_start_1|>
... | UserPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPage:
def add_department_by_root_name(self, flag=True):
"""从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别"""
<|body_0|>
def create_department_group(self, group_name, til_name, confirm=True):
"""方法封装:用于创建 同级/下一级 分组 :param dep_nam... | stack_v2_sparse_classes_36k_train_029008 | 7,356 | no_license | [
{
"docstring": "从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别",
"name": "add_department_by_root_name",
"signature": "def add_department_by_root_name(self, flag=True)"
},
{
"docstring": "方法封装:用于创建 同级/下一级 分组 :param dep_name: 部分分组名称 :param til_name: dialog弹框中的标题 ... | 2 | stack_v2_sparse_classes_30k_train_017456 | Implement the Python class `UserPage` described below.
Class description:
Implement the UserPage class.
Method signatures and docstrings:
- def add_department_by_root_name(self, flag=True): 从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别
- def create_department_group(self, group_name... | Implement the Python class `UserPage` described below.
Class description:
Implement the UserPage class.
Method signatures and docstrings:
- def add_department_by_root_name(self, flag=True): 从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别
- def create_department_group(self, group_name... | 53ffcfc63447b4462c788d5620872fa54a9283a1 | <|skeleton|>
class UserPage:
def add_department_by_root_name(self, flag=True):
"""从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别"""
<|body_0|>
def create_department_group(self, group_name, til_name, confirm=True):
"""方法封装:用于创建 同级/下一级 分组 :param dep_nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPage:
def add_department_by_root_name(self, flag=True):
"""从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别"""
if flag:
GroupTree(self.driver).click_menu_by_name('Default', '创建同级')
title_name = '创建同级'
else:
GroupT... | the_stack_v2_python_sparse | guard/pages/user_backup.py | qinwenzhu/selenium_pytest_actual | train | 0 | |
ceb4452c1d2962045cef531f5f74ea60a19c819d | [
"requires_grad = False\nmean = input.mean(dim=0)\nvar = input.var(dim=0, unbiased=False)\ndenom = (var + eps).sqrt()\nx_hat = (input - mean) / denom\nout = torch.addcmul(beta, gamma, x_hat)\nctx.save_for_backward(gamma, denom, x_hat)\nreturn out",
"input_needs, gamma_needs, beta_needs = ctx.needs_input_grad\nB, _... | <|body_start_0|>
requires_grad = False
mean = input.mean(dim=0)
var = input.var(dim=0, unbiased=False)
denom = (var + eps).sqrt()
x_hat = (input - mean) / denom
out = torch.addcmul(beta, gamma, x_hat)
ctx.save_for_backward(gamma, denom, x_hat)
return out
<... | This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs. Using torch.autograd.Function allows you to write a custom backward function. The function will be called from the nn.Module CustomBatchNormManualModule Inside forward the tensors are (automatically) not recorded f... | CustomBatchNormManualFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomBatchNormManualFunction:
"""This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs. Using torch.autograd.Function allows you to write a custom backward function. The function will be called from the nn.Module CustomBatchNormManualModule Insi... | stack_v2_sparse_classes_36k_train_029009 | 7,737 | no_license | [
{
"docstring": "Compute the batch normalization Args: ctx: context object handling storing and retrival of tensors and constants and specifying whether tensors need gradients in backward pass input: input tensor of shape (B, n_neurons) gamma: variance scaling tensor, applied per neuron, shape (n_neurons) beta: ... | 2 | stack_v2_sparse_classes_30k_train_020903 | Implement the Python class `CustomBatchNormManualFunction` described below.
Class description:
This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs. Using torch.autograd.Function allows you to write a custom backward function. The function will be called from the nn.... | Implement the Python class `CustomBatchNormManualFunction` described below.
Class description:
This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs. Using torch.autograd.Function allows you to write a custom backward function. The function will be called from the nn.... | b2cd0d67337b101f3e204e519625e1aaf3cea43b | <|skeleton|>
class CustomBatchNormManualFunction:
"""This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs. Using torch.autograd.Function allows you to write a custom backward function. The function will be called from the nn.Module CustomBatchNormManualModule Insi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomBatchNormManualFunction:
"""This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs. Using torch.autograd.Function allows you to write a custom backward function. The function will be called from the nn.Module CustomBatchNormManualModule Inside forward th... | the_stack_v2_python_sparse | assignment_1/code/custom_batchnorm.py | Ivan-Yovchev/uvadlc_practicals_2019 | train | 0 |
3720adc861c07007526e67b32a721799d0488ca6 | [
"script_location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\ndf = pd.read_pickle('%s/%s' % (script_location, data_pickle))\nH = np.array(df['H'], dtype=float)\nalpha = np.array(df['alpha'], dtype=float)\nh = np.array(df['h'], dtype=float)\nself.interpolator = LinearNDInterpolator((h, a... | <|body_start_0|>
script_location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
df = pd.read_pickle('%s/%s' % (script_location, data_pickle))
H = np.array(df['H'], dtype=float)
alpha = np.array(df['alpha'], dtype=float)
h = np.array(df['h'], dtype=float)... | HurstCorrection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HurstCorrection:
def __init__(self, data_pickle='hurst_correction.pl'):
"""When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value ... | stack_v2_sparse_classes_36k_train_029010 | 4,597 | permissive | [
{
"docstring": "When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value of H to feed to the fractional levy motion algorithm in order to achieve a specific... | 2 | stack_v2_sparse_classes_30k_train_008779 | Implement the Python class `HurstCorrection` described below.
Class description:
Implement the HurstCorrection class.
Method signatures and docstrings:
- def __init__(self, data_pickle='hurst_correction.pl'): When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to t... | Implement the Python class `HurstCorrection` described below.
Class description:
Implement the HurstCorrection class.
Method signatures and docstrings:
- def __init__(self, data_pickle='hurst_correction.pl'): When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to t... | e94694f298909352d7e9d912625314a1e46aa5b6 | <|skeleton|>
class HurstCorrection:
def __init__(self, data_pickle='hurst_correction.pl'):
"""When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HurstCorrection:
def __init__(self, data_pickle='hurst_correction.pl'):
"""When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value of H to feed t... | the_stack_v2_python_sparse | LLC_Membranes/timeseries/flm_sim_params.py | NKM-ML/LLC_Membranes | train | 0 | |
69b8ecf656173add61531024d7d8ed636e7f6f2b | [
"stack = []\nresult = [0] * len(temperatures)\nstack.append(0)\nfor i, v in enumerate(temperatures):\n while len(stack) != 0 and v > temperatures[stack[-1]]:\n pre = stack.pop()\n result[pre] = i - pre\n stack.append(i)\nreturn result",
"n = len(temperatures)\ndays = [0] * n\nfor i in range(n ... | <|body_start_0|>
stack = []
result = [0] * len(temperatures)
stack.append(0)
for i, v in enumerate(temperatures):
while len(stack) != 0 and v > temperatures[stack[-1]]:
pre = stack.pop()
result[pre] = i - pre
stack.append(i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_029011 | 1,904 | no_license | [
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(self, temperatures)"
},
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures1",
"signature": "def dailyTemperatures1(... | 2 | stack_v2_sparse_classes_30k_train_015312 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: Lis... | eaeeb9ad2d8cf2a60517cd86f42b30678b5ad2f8 | <|skeleton|>
class Solution:
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
stack = []
result = [0] * len(temperatures)
stack.append(0)
for i, v in enumerate(temperatures):
while len(stack) != 0 and v > temperatures[stack[-1]]:... | the_stack_v2_python_sparse | Python/739. Daily Temperatures.py | maiwen/LeetCode | train | 0 | |
a3ac01b465bcaf541c7789b907369192bae807dd | [
"wm = context.window_manager\nobj = context.active_object\nif wm.verse_connected is True and obj is not None and (obj.type == 'MESH') and (obj.verse_node_id != -1):\n return True\nelse:\n return False",
"wm = context.window_manager\nlayout = self.layout\nvrs_session = session.VerseSession.instance()\nnode =... | <|body_start_0|>
wm = context.window_manager
obj = context.active_object
if wm.verse_connected is True and obj is not None and (obj.type == 'MESH') and (obj.verse_node_id != -1):
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
wm = context.... | GUI of Blender objects shared at Verse server | VerseObjectPermPanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerseObjectPermPanel:
"""GUI of Blender objects shared at Verse server"""
def poll(cls, context):
"""Can be this panel visible"""
<|body_0|>
def draw(self, context):
"""This method draw panel of Verse scenes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_029012 | 18,592 | no_license | [
{
"docstring": "Can be this panel visible",
"name": "poll",
"signature": "def poll(cls, context)"
},
{
"docstring": "This method draw panel of Verse scenes",
"name": "draw",
"signature": "def draw(self, context)"
}
] | 2 | null | Implement the Python class `VerseObjectPermPanel` described below.
Class description:
GUI of Blender objects shared at Verse server
Method signatures and docstrings:
- def poll(cls, context): Can be this panel visible
- def draw(self, context): This method draw panel of Verse scenes | Implement the Python class `VerseObjectPermPanel` described below.
Class description:
GUI of Blender objects shared at Verse server
Method signatures and docstrings:
- def poll(cls, context): Can be this panel visible
- def draw(self, context): This method draw panel of Verse scenes
<|skeleton|>
class VerseObjectPer... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class VerseObjectPermPanel:
"""GUI of Blender objects shared at Verse server"""
def poll(cls, context):
"""Can be this panel visible"""
<|body_0|>
def draw(self, context):
"""This method draw panel of Verse scenes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerseObjectPermPanel:
"""GUI of Blender objects shared at Verse server"""
def poll(cls, context):
"""Can be this panel visible"""
wm = context.window_manager
obj = context.active_object
if wm.verse_connected is True and obj is not None and (obj.type == 'MESH') and (obj.ver... | the_stack_v2_python_sparse | All_In_One/addons/io_verse/ui_object3d.py | 2434325680/Learnbgame | train | 0 |
fae8140ce4cc2a2ac83d4416d69afb2a748cbe81 | [
"if not chars:\n res.append(path)\n return\ni, n = (0, len(chars))\nwhile i < n:\n while 0 < i < n and chars[i] == chars[i - 1]:\n i += 1\n if i < n:\n c = chars.pop(i)\n self.combinations(chars, res, path + [c])\n chars.insert(i, c)\n i += 1\nreturn",
"c, chars, odds = ... | <|body_start_0|>
if not chars:
res.append(path)
return
i, n = (0, len(chars))
while i < n:
while 0 < i < n and chars[i] == chars[i - 1]:
i += 1
if i < n:
c = chars.pop(i)
self.combinations(chars, res,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinations(self, chars, res, path=[]):
""":param chars: :param res: :param path: :return: beats 63.83%"""
<|body_0|>
def generatePalindromes(self, s):
""":type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_029013 | 1,232 | no_license | [
{
"docstring": ":param chars: :param res: :param path: :return: beats 63.83%",
"name": "combinations",
"signature": "def combinations(self, chars, res, path=[])"
},
{
"docstring": ":type s: str :rtype: List[str]",
"name": "generatePalindromes",
"signature": "def generatePalindromes(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinations(self, chars, res, path=[]): :param chars: :param res: :param path: :return: beats 63.83%
- def generatePalindromes(self, s): :type s: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinations(self, chars, res, path=[]): :param chars: :param res: :param path: :return: beats 63.83%
- def generatePalindromes(self, s): :type s: str :rtype: List[str]
<|sk... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def combinations(self, chars, res, path=[]):
""":param chars: :param res: :param path: :return: beats 63.83%"""
<|body_0|>
def generatePalindromes(self, s):
""":type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinations(self, chars, res, path=[]):
""":param chars: :param res: :param path: :return: beats 63.83%"""
if not chars:
res.append(path)
return
i, n = (0, len(chars))
while i < n:
while 0 < i < n and chars[i] == chars[i - 1]:
... | the_stack_v2_python_sparse | LeetCode/267_palindrome_permutation_ii.py | yao23/Machine_Learning_Playground | train | 12 | |
f0ec038e674e38c4c735ab95dc3276bbfe07132d | [
"try:\n theStock = Stock(ticker)\n theQuote = theStock.get_book()['quote']\n us_timezone = tz.gettz('America/New_York')\n theDate = datetime.datetime.fromtimestamp(theQuote['latestUpdate'] / 1000)\n theDate = theDate.astimezone(us_timezone)\n thePrice = D(theQuote['latestPrice']).quantize(D('0.01'... | <|body_start_0|>
try:
theStock = Stock(ticker)
theQuote = theStock.get_book()['quote']
us_timezone = tz.gettz('America/New_York')
theDate = datetime.datetime.fromtimestamp(theQuote['latestUpdate'] / 1000)
theDate = theDate.astimezone(us_timezone)
... | IEX API price extractor. | Source | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Source:
"""IEX API price extractor."""
def get_latest_price(self, ticker):
"""Fetch the current latest price. The date may differ. This routine attempts to fetch the most recent available price, and returns the actual date of the quoted price, which may differ from the date this call... | stack_v2_sparse_classes_36k_train_029014 | 4,307 | no_license | [
{
"docstring": "Fetch the current latest price. The date may differ. This routine attempts to fetch the most recent available price, and returns the actual date of the quoted price, which may differ from the date this call is made at. {1cfa25e37fc1} Args: ticker: A string, the ticker to be fetched by the source... | 2 | stack_v2_sparse_classes_30k_train_021653 | Implement the Python class `Source` described below.
Class description:
IEX API price extractor.
Method signatures and docstrings:
- def get_latest_price(self, ticker): Fetch the current latest price. The date may differ. This routine attempts to fetch the most recent available price, and returns the actual date of t... | Implement the Python class `Source` described below.
Class description:
IEX API price extractor.
Method signatures and docstrings:
- def get_latest_price(self, ticker): Fetch the current latest price. The date may differ. This routine attempts to fetch the most recent available price, and returns the actual date of t... | 8709cafe99d32ed445a39fc7f137b32df350be45 | <|skeleton|>
class Source:
"""IEX API price extractor."""
def get_latest_price(self, ticker):
"""Fetch the current latest price. The date may differ. This routine attempts to fetch the most recent available price, and returns the actual date of the quoted price, which may differ from the date this call... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Source:
"""IEX API price extractor."""
def get_latest_price(self, ticker):
"""Fetch the current latest price. The date may differ. This routine attempts to fetch the most recent available price, and returns the actual date of the quoted price, which may differ from the date this call is made at. ... | the_stack_v2_python_sparse | price/iexcloud.py | grostim/Beancount-myTools | train | 4 |
d32bed55295035141333b179478f099bac7aaefe | [
"Compilation.__init__(self, sandbox)\nsource_file = tempfile.mktemp(suffix='.py', prefix='elif_code_')\nself.exec_file = self.sandbox.mktemp(prefix='exec_', suffix='.pyc')\nwith open(source_file, 'w') as f:\n f.write(code)\ntry:\n py_compile.compile(source_file, self.exec_file, doraise=True)\n self.return_... | <|body_start_0|>
Compilation.__init__(self, sandbox)
source_file = tempfile.mktemp(suffix='.py', prefix='elif_code_')
self.exec_file = self.sandbox.mktemp(prefix='exec_', suffix='.pyc')
with open(source_file, 'w') as f:
f.write(code)
try:
py_compile.compil... | PythonCompilation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonCompilation:
def __init__(self, sandbox, code):
"""Compiles the code Parameters: - code must be encoded in UTF8"""
<|body_0|>
def run(self, params=list(), stdin=None):
"""Runs the code in the sandbox and return its process's feedback"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_029015 | 4,057 | no_license | [
{
"docstring": "Compiles the code Parameters: - code must be encoded in UTF8",
"name": "__init__",
"signature": "def __init__(self, sandbox, code)"
},
{
"docstring": "Runs the code in the sandbox and return its process's feedback",
"name": "run",
"signature": "def run(self, params=list()... | 2 | stack_v2_sparse_classes_30k_train_006978 | Implement the Python class `PythonCompilation` described below.
Class description:
Implement the PythonCompilation class.
Method signatures and docstrings:
- def __init__(self, sandbox, code): Compiles the code Parameters: - code must be encoded in UTF8
- def run(self, params=list(), stdin=None): Runs the code in the... | Implement the Python class `PythonCompilation` described below.
Class description:
Implement the PythonCompilation class.
Method signatures and docstrings:
- def __init__(self, sandbox, code): Compiles the code Parameters: - code must be encoded in UTF8
- def run(self, params=list(), stdin=None): Runs the code in the... | d20e5f1ee1a9ac7b4fd50b23c58016af5cd91178 | <|skeleton|>
class PythonCompilation:
def __init__(self, sandbox, code):
"""Compiles the code Parameters: - code must be encoded in UTF8"""
<|body_0|>
def run(self, params=list(), stdin=None):
"""Runs the code in the sandbox and return its process's feedback"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PythonCompilation:
def __init__(self, sandbox, code):
"""Compiles the code Parameters: - code must be encoded in UTF8"""
Compilation.__init__(self, sandbox)
source_file = tempfile.mktemp(suffix='.py', prefix='elif_code_')
self.exec_file = self.sandbox.mktemp(prefix='exec_', suf... | the_stack_v2_python_sparse | src/compilation.py | INSA-4IF-SpecIFic/elif | train | 0 | |
2ffeee91f53ed69de3fe2392bb2e44aecbbf4ac2 | [
"string_builder = ''\nif s == '':\n return True\nfor i in range(len(s)):\n string_builder += s[i]\n if string_builder in dict:\n try:\n if self.wordBreak_TLE(s[i + 1:], dict):\n return True\n else:\n continue\n except IndexError:\n ... | <|body_start_0|>
string_builder = ''
if s == '':
return True
for i in range(len(s)):
string_builder += s[i]
if string_builder in dict:
try:
if self.wordBreak_TLE(s[i + 1:], dict):
return True
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
... | stack_v2_sparse_classes_36k_train_029016 | 3,284 | permissive | [
{
"docstring": "TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean",
"name": "wordBreak_TLE",
"signature": "def wordBrea... | 2 | stack_v2_sparse_classes_30k_train_016357 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_TLE(self, s, dict): TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can u... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_TLE(self, s, dict): TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can u... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
string_bu... | the_stack_v2_python_sparse | 139 Word Break.py | Aminaba123/LeetCode | train | 1 | |
d0cecff4ee02e5fcb692726947e3b79546ddac09 | [
"if self.is_bitmap_value and type(self.data) is int:\n for value, label in self.choices:\n yield (value, label, bool(self.data & value))\nelse:\n yield from super().iter_choices()",
"try:\n if self.is_bitmap_value:\n self.data = [self.coerce(v) for v, _ in self.choices if v & value]\n el... | <|body_start_0|>
if self.is_bitmap_value and type(self.data) is int:
for value, label in self.choices:
yield (value, label, bool(self.data & value))
else:
yield from super().iter_choices()
<|end_body_0|>
<|body_start_1|>
try:
if self.is_bitmap... | Multiple value selection widget. No different from a normal multi select field, except this one can take (and validate) multiple choices and value (by defualt) can be a bitmap of selected choices (the choice value should be an integer). | BitmapMultipleValueField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitmapMultipleValueField:
"""Multiple value selection widget. No different from a normal multi select field, except this one can take (and validate) multiple choices and value (by defualt) can be a bitmap of selected choices (the choice value should be an integer)."""
def iter_choices(self):... | stack_v2_sparse_classes_36k_train_029017 | 15,157 | permissive | [
{
"docstring": "Iterate through the list of choces.",
"name": "iter_choices",
"signature": "def iter_choices(self)"
},
{
"docstring": "Map selected value representation to the a list to internal domain value.",
"name": "process_data",
"signature": "def process_data(self, value)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_018902 | Implement the Python class `BitmapMultipleValueField` described below.
Class description:
Multiple value selection widget. No different from a normal multi select field, except this one can take (and validate) multiple choices and value (by defualt) can be a bitmap of selected choices (the choice value should be an in... | Implement the Python class `BitmapMultipleValueField` described below.
Class description:
Multiple value selection widget. No different from a normal multi select field, except this one can take (and validate) multiple choices and value (by defualt) can be a bitmap of selected choices (the choice value should be an in... | ba412d49cff0158842878753b65fc60731df158c | <|skeleton|>
class BitmapMultipleValueField:
"""Multiple value selection widget. No different from a normal multi select field, except this one can take (and validate) multiple choices and value (by defualt) can be a bitmap of selected choices (the choice value should be an integer)."""
def iter_choices(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BitmapMultipleValueField:
"""Multiple value selection widget. No different from a normal multi select field, except this one can take (and validate) multiple choices and value (by defualt) can be a bitmap of selected choices (the choice value should be an integer)."""
def iter_choices(self):
"""I... | the_stack_v2_python_sparse | orcid_hub/forms.py | jpeerz/NZ-ORCID-Hub | train | 0 |
96c6d3bdf363067247f1825a28e290fb28febc1f | [
"self.maxDiff = None\nuser_email = 'cristina@gmail.com'\nuser = User.objects.create(username=user_email, email=user_email, password='password')\nDeliveryAddress.objects.create(first_name='cristina', last_name='garbuz', street='street', apt_nr=21, user=user, zip_code=14, city='Stockholm', country='Sweden')\nresponse... | <|body_start_0|>
self.maxDiff = None
user_email = 'cristina@gmail.com'
user = User.objects.create(username=user_email, email=user_email, password='password')
DeliveryAddress.objects.create(first_name='cristina', last_name='garbuz', street='street', apt_nr=21, user=user, zip_code=14, city... | AddressRetrieveTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressRetrieveTest:
def test_retrieve_address(self):
"""tests that the address information is retrieved from the database."""
<|body_0|>
def test_retrieve_latest_address(self):
"""tests that the address information is retrieved from the database."""
<|body_1... | stack_v2_sparse_classes_36k_train_029018 | 7,789 | no_license | [
{
"docstring": "tests that the address information is retrieved from the database.",
"name": "test_retrieve_address",
"signature": "def test_retrieve_address(self)"
},
{
"docstring": "tests that the address information is retrieved from the database.",
"name": "test_retrieve_latest_address",... | 2 | null | Implement the Python class `AddressRetrieveTest` described below.
Class description:
Implement the AddressRetrieveTest class.
Method signatures and docstrings:
- def test_retrieve_address(self): tests that the address information is retrieved from the database.
- def test_retrieve_latest_address(self): tests that the... | Implement the Python class `AddressRetrieveTest` described below.
Class description:
Implement the AddressRetrieveTest class.
Method signatures and docstrings:
- def test_retrieve_address(self): tests that the address information is retrieved from the database.
- def test_retrieve_latest_address(self): tests that the... | d84bdedc9ed011dc009cd1b6d42eed1925ccc977 | <|skeleton|>
class AddressRetrieveTest:
def test_retrieve_address(self):
"""tests that the address information is retrieved from the database."""
<|body_0|>
def test_retrieve_latest_address(self):
"""tests that the address information is retrieved from the database."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddressRetrieveTest:
def test_retrieve_address(self):
"""tests that the address information is retrieved from the database."""
self.maxDiff = None
user_email = 'cristina@gmail.com'
user = User.objects.create(username=user_email, email=user_email, password='password')
De... | the_stack_v2_python_sparse | backend/user/tests.py | Code-Institute-Submissions/vintage-earrings | train | 0 | |
0af39809a48ef84eb839da2a195294583691886e | [
"if sell_kind == 'yellow':\n if sell_number > self.store_dog[0]['number']:\n print('We dont have enough dogs you want for sell,Sorry.')\n else:\n print('Successfully sell {} dogs, which kind is {}'.format(sell_number, self.store_dog[0]['color']))\n self.store_dog[0]['number'] -= sell_numb... | <|body_start_0|>
if sell_kind == 'yellow':
if sell_number > self.store_dog[0]['number']:
print('We dont have enough dogs you want for sell,Sorry.')
else:
print('Successfully sell {} dogs, which kind is {}'.format(sell_number, self.store_dog[0]['color']))
... | 这个类用于保存不同品种的狗的库存情况 | cpdog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cpdog:
"""这个类用于保存不同品种的狗的库存情况"""
def sell_dog(self, sell_number, sell_kind):
"""参数为出售的数量和出售的品种,如果不符合店家的购买要求(数量不够或者没有品种)则输出抱歉语句, 否则提示出售成功并且返回出售的金额"""
<|body_0|>
def purchase_dog(self, buy_number, buy_kind):
"""输入参数为购买的数量和购买的品种,不是以上三种的视作购买失败,简化上面的出售语句,显得过于繁琐,可以在最初做条... | stack_v2_sparse_classes_36k_train_029019 | 3,472 | no_license | [
{
"docstring": "参数为出售的数量和出售的品种,如果不符合店家的购买要求(数量不够或者没有品种)则输出抱歉语句, 否则提示出售成功并且返回出售的金额",
"name": "sell_dog",
"signature": "def sell_dog(self, sell_number, sell_kind)"
},
{
"docstring": "输入参数为购买的数量和购买的品种,不是以上三种的视作购买失败,简化上面的出售语句,显得过于繁琐,可以在最初做条件语句 返回值为购买所花的金额",
"name": "purchase_dog",
"signature... | 2 | null | Implement the Python class `cpdog` described below.
Class description:
这个类用于保存不同品种的狗的库存情况
Method signatures and docstrings:
- def sell_dog(self, sell_number, sell_kind): 参数为出售的数量和出售的品种,如果不符合店家的购买要求(数量不够或者没有品种)则输出抱歉语句, 否则提示出售成功并且返回出售的金额
- def purchase_dog(self, buy_number, buy_kind): 输入参数为购买的数量和购买的品种,不是以上三种的视作购买失败,简化上... | Implement the Python class `cpdog` described below.
Class description:
这个类用于保存不同品种的狗的库存情况
Method signatures and docstrings:
- def sell_dog(self, sell_number, sell_kind): 参数为出售的数量和出售的品种,如果不符合店家的购买要求(数量不够或者没有品种)则输出抱歉语句, 否则提示出售成功并且返回出售的金额
- def purchase_dog(self, buy_number, buy_kind): 输入参数为购买的数量和购买的品种,不是以上三种的视作购买失败,简化上... | 9b1a9bbbbe69e14f5e7183ecd301f14b0e34b4b1 | <|skeleton|>
class cpdog:
"""这个类用于保存不同品种的狗的库存情况"""
def sell_dog(self, sell_number, sell_kind):
"""参数为出售的数量和出售的品种,如果不符合店家的购买要求(数量不够或者没有品种)则输出抱歉语句, 否则提示出售成功并且返回出售的金额"""
<|body_0|>
def purchase_dog(self, buy_number, buy_kind):
"""输入参数为购买的数量和购买的品种,不是以上三种的视作购买失败,简化上面的出售语句,显得过于繁琐,可以在最初做条... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class cpdog:
"""这个类用于保存不同品种的狗的库存情况"""
def sell_dog(self, sell_number, sell_kind):
"""参数为出售的数量和出售的品种,如果不符合店家的购买要求(数量不够或者没有品种)则输出抱歉语句, 否则提示出售成功并且返回出售的金额"""
if sell_kind == 'yellow':
if sell_number > self.store_dog[0]['number']:
print('We dont have enough dogs you want ... | the_stack_v2_python_sparse | homework6/01_cpgod.py | WOWspring/pythonhomework | train | 2 |
1113487d7b3e2ed6974b1b1ce8444f51ba120ccc | [
"self.descr = 'Monitor'\nself.position = position\nself.data = data\nself.log = log\nself.model = model\nself.query_interval_secs = 300",
"print('Monitor price for sell signal')\nsell_trigger = False\nstoploss = 0.15\nprint('stoploss is:', self.position.buy_price * (1 - stoploss))\nwhile not sell_trigger:\n pr... | <|body_start_0|>
self.descr = 'Monitor'
self.position = position
self.data = data
self.log = log
self.model = model
self.query_interval_secs = 300
<|end_body_0|>
<|body_start_1|>
print('Monitor price for sell signal')
sell_trigger = False
stoploss... | classdocs | Monitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monitor:
"""classdocs"""
def __init__(self, data, position, log, model):
"""Constructor"""
<|body_0|>
def performAction(self):
"""Monitor action should get features for current or virtual time send features to the model to get a prediction if prediction is 'sell'... | stack_v2_sparse_classes_36k_train_029020 | 2,192 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, data, position, log, model)"
},
{
"docstring": "Monitor action should get features for current or virtual time send features to the model to get a prediction if prediction is 'sell' (2) then move to sell action",
... | 2 | stack_v2_sparse_classes_30k_train_016915 | Implement the Python class `Monitor` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, data, position, log, model): Constructor
- def performAction(self): Monitor action should get features for current or virtual time send features to the model to get a prediction if... | Implement the Python class `Monitor` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, data, position, log, model): Constructor
- def performAction(self): Monitor action should get features for current or virtual time send features to the model to get a prediction if... | 96db5175ce8def5210bb0696a3d442ac14dee58f | <|skeleton|>
class Monitor:
"""classdocs"""
def __init__(self, data, position, log, model):
"""Constructor"""
<|body_0|>
def performAction(self):
"""Monitor action should get features for current or virtual time send features to the model to get a prediction if prediction is 'sell'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Monitor:
"""classdocs"""
def __init__(self, data, position, log, model):
"""Constructor"""
self.descr = 'Monitor'
self.position = position
self.data = data
self.log = log
self.model = model
self.query_interval_secs = 300
def performAction(self)... | the_stack_v2_python_sparse | monitor.py | ThatsRichApps/malgus | train | 0 |
1a443b76c13e15eed4842416b38f2faae4813523 | [
"while True:\n logger.info('extracting movies from postgres')\n df = (yield)\n if not df.empty:\n genres_ids = id_list(df['id'])\n query = f'\\n SELECT movie_id, array_agg(name) as genre\\n FROM genre\\n JOIN (SELECT * FROM ... | <|body_start_0|>
while True:
logger.info('extracting movies from postgres')
df = (yield)
if not df.empty:
genres_ids = id_list(df['id'])
query = f'\n SELECT movie_id, array_agg(name) as genre\n FROM... | Class for etl process, which moves data from postgres DB to elasticsearch | GenreETL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenreETL:
"""Class for etl process, which moves data from postgres DB to elasticsearch"""
def extract_first_level_connections(self, data):
"""Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres ... | stack_v2_sparse_classes_36k_train_029021 | 2,866 | no_license | [
{
"docstring": "Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres data + movies",
"name": "extract_first_level_connections",
"signature": "def extract_first_level_connections(self, data)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_test_000152 | Implement the Python class `GenreETL` described below.
Class description:
Class for etl process, which moves data from postgres DB to elasticsearch
Method signatures and docstrings:
- def extract_first_level_connections(self, data): Coroutine that queries postgres to get genres based on the movies ids gotten in the p... | Implement the Python class `GenreETL` described below.
Class description:
Class for etl process, which moves data from postgres DB to elasticsearch
Method signatures and docstrings:
- def extract_first_level_connections(self, data): Coroutine that queries postgres to get genres based on the movies ids gotten in the p... | 4ddc8a77e5a9e9bc2a900c7bb6ffbcf5999e8c89 | <|skeleton|>
class GenreETL:
"""Class for etl process, which moves data from postgres DB to elasticsearch"""
def extract_first_level_connections(self, data):
"""Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenreETL:
"""Class for etl process, which moves data from postgres DB to elasticsearch"""
def extract_first_level_connections(self, data):
"""Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres data + movies... | the_stack_v2_python_sparse | postgres_to_es/etl_genre.py | maffka123/Admin_panel_sprint_2 | train | 0 |
22d0c183a8fd94a53b7c172bb6955cc73a7b9aa1 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jkmoy_mfflynn', 'jkmoy_mfflynn')\nurl = 'http://gis.cityofboston.gov/arcgis/rest/services/PublicSafety/OpenData/MapServer/2/query?where=1%3D1&outFields=*&outSR=4326&f=json'\nresponse = urllib.request.url... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jkmoy_mfflynn', 'jkmoy_mfflynn')
url = 'http://gis.cityofboston.gov/arcgis/rest/services/PublicSafety/OpenData/MapServer/2/query?where=1%3D1&outFields=*&o... | fire_departments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fire_departments:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyth... | stack_v2_sparse_classes_36k_train_029022 | 3,941 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_020573 | Implement the Python class `fire_departments` described below.
Class description:
Implement the fire_departments class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=N... | Implement the Python class `fire_departments` described below.
Class description:
Implement the fire_departments class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=N... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class fire_departments:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class fire_departments:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jkmoy_mfflynn', 'jkmoy_mfflynn')
... | the_stack_v2_python_sparse | jkmoy_mfflynn/fire_departments.py | maximega/course-2019-spr-proj | train | 2 | |
78db134fffac10f1e3c757a6506cbf1135214a5f | [
"rawline = self.file.readline()\nwhile rawline:\n rematch = self.line_re.match(rawline)\n if not rematch:\n rawline = self.file.readline()\n continue\n while rematch:\n rep = Replica()\n self.reps.append(rep)\n rep.index = [0 for i in range(self.numexchg)]\n rep.ne... | <|body_start_0|>
rawline = self.file.readline()
while rawline:
rematch = self.line_re.match(rawline)
if not rematch:
rawline = self.file.readline()
continue
while rematch:
rep = Replica()
self.reps.append... | A class for H-REMD log file | HRemLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HRemLog:
"""A class for H-REMD log file"""
def _get_replicas(self):
"""Gets all of the replica information from the first block of repinfo"""
<|body_0|>
def _parse(self):
"""Parses the rem.log file and loads the data arrays"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_029023 | 12,296 | no_license | [
{
"docstring": "Gets all of the replica information from the first block of repinfo",
"name": "_get_replicas",
"signature": "def _get_replicas(self)"
},
{
"docstring": "Parses the rem.log file and loads the data arrays",
"name": "_parse",
"signature": "def _parse(self)"
}
] | 2 | null | Implement the Python class `HRemLog` described below.
Class description:
A class for H-REMD log file
Method signatures and docstrings:
- def _get_replicas(self): Gets all of the replica information from the first block of repinfo
- def _parse(self): Parses the rem.log file and loads the data arrays | Implement the Python class `HRemLog` described below.
Class description:
A class for H-REMD log file
Method signatures and docstrings:
- def _get_replicas(self): Gets all of the replica information from the first block of repinfo
- def _parse(self): Parses the rem.log file and loads the data arrays
<|skeleton|>
clas... | 5cec8112637be7a19c4aac893f612aa8c354b733 | <|skeleton|>
class HRemLog:
"""A class for H-REMD log file"""
def _get_replicas(self):
"""Gets all of the replica information from the first block of repinfo"""
<|body_0|>
def _parse(self):
"""Parses the rem.log file and loads the data arrays"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HRemLog:
"""A class for H-REMD log file"""
def _get_replicas(self):
"""Gets all of the replica information from the first block of repinfo"""
rawline = self.file.readline()
while rawline:
rematch = self.line_re.match(rawline)
if not rematch:
... | the_stack_v2_python_sparse | remd.py | jeff-wang/JmsScripts | train | 0 |
636892c6bc9c98639a20469731f65a6a5cf04f03 | [
"uri = self.base_path % {'firewall_id': firewall_id, 'action': 'reboot'}\nresp = session.post(uri, endpoint_filter=self.service, json={'type': type})\nself._translate_response(resp, has_body=False)\nreturn self",
"uri = self.base_path % {'firewall_id': firewall_id, 'action': 'reset_password'}\nresp = session.post... | <|body_start_0|>
uri = self.base_path % {'firewall_id': firewall_id, 'action': 'reboot'}
resp = session.post(uri, endpoint_filter=self.service, json={'type': type})
self._translate_response(resp, has_body=False)
return self
<|end_body_0|>
<|body_start_1|>
uri = self.base_path % ... | FirewallAction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirewallAction:
def reboot(self, session, firewall_id, type):
"""Reboot firewall."""
<|body_0|>
def reset_password(self, session, firewall_id, username):
"""Reset password of firewall instance."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
uri = s... | stack_v2_sparse_classes_36k_train_029024 | 1,864 | permissive | [
{
"docstring": "Reboot firewall.",
"name": "reboot",
"signature": "def reboot(self, session, firewall_id, type)"
},
{
"docstring": "Reset password of firewall instance.",
"name": "reset_password",
"signature": "def reset_password(self, session, firewall_id, username)"
}
] | 2 | null | Implement the Python class `FirewallAction` described below.
Class description:
Implement the FirewallAction class.
Method signatures and docstrings:
- def reboot(self, session, firewall_id, type): Reboot firewall.
- def reset_password(self, session, firewall_id, username): Reset password of firewall instance. | Implement the Python class `FirewallAction` described below.
Class description:
Implement the FirewallAction class.
Method signatures and docstrings:
- def reboot(self, session, firewall_id, type): Reboot firewall.
- def reset_password(self, session, firewall_id, username): Reset password of firewall instance.
<|ske... | c2dafba850c4e6fb55b5e10de79257bbc9a01af3 | <|skeleton|>
class FirewallAction:
def reboot(self, session, firewall_id, type):
"""Reboot firewall."""
<|body_0|>
def reset_password(self, session, firewall_id, username):
"""Reset password of firewall instance."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FirewallAction:
def reboot(self, session, firewall_id, type):
"""Reboot firewall."""
uri = self.base_path % {'firewall_id': firewall_id, 'action': 'reboot'}
resp = session.post(uri, endpoint_filter=self.service, json={'type': type})
self._translate_response(resp, has_body=False... | the_stack_v2_python_sparse | ecl/network/v2/firewall_action.py | nttcom/eclsdk | train | 5 | |
013483d4a643c55c498b227c40ec580e8a9e4a0a | [
"df = Spark.RDataFrame(self.maintreename, self.filenames, sparkcontext=connection)\ndefinepersample_code = '\\n if(rdfsampleinfo_.Contains(\"{}\")) return 1;\\n else if (rdfsampleinfo_.Contains(\"{}\")) return 2;\\n else if (rdfsampleinfo_.Contains(\"{}\")) return 3;\\n else return 0;\\n... | <|body_start_0|>
df = Spark.RDataFrame(self.maintreename, self.filenames, sparkcontext=connection)
definepersample_code = '\n if(rdfsampleinfo_.Contains("{}")) return 1;\n else if (rdfsampleinfo_.Contains("{}")) return 2;\n else if (rdfsampleinfo_.Contains("{}")) return 3;\n ... | Check the working of merge operations in the reducer function. | TestDefinePerSample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDefinePerSample:
"""Check the working of merge operations in the reducer function."""
def test_definepersample_simple(self, connection):
"""Test DefinePerSample operation on three samples using a predefined string of operations."""
<|body_0|>
def test_definepersample... | stack_v2_sparse_classes_36k_train_029025 | 4,549 | no_license | [
{
"docstring": "Test DefinePerSample operation on three samples using a predefined string of operations.",
"name": "test_definepersample_simple",
"signature": "def test_definepersample_simple(self, connection)"
},
{
"docstring": "Test DefinePerSample operation on three samples using C++ function... | 2 | null | Implement the Python class `TestDefinePerSample` described below.
Class description:
Check the working of merge operations in the reducer function.
Method signatures and docstrings:
- def test_definepersample_simple(self, connection): Test DefinePerSample operation on three samples using a predefined string of operat... | Implement the Python class `TestDefinePerSample` described below.
Class description:
Check the working of merge operations in the reducer function.
Method signatures and docstrings:
- def test_definepersample_simple(self, connection): Test DefinePerSample operation on three samples using a predefined string of operat... | 134508460915282a5d82d6cbbb6e6afa14653413 | <|skeleton|>
class TestDefinePerSample:
"""Check the working of merge operations in the reducer function."""
def test_definepersample_simple(self, connection):
"""Test DefinePerSample operation on three samples using a predefined string of operations."""
<|body_0|>
def test_definepersample... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDefinePerSample:
"""Check the working of merge operations in the reducer function."""
def test_definepersample_simple(self, connection):
"""Test DefinePerSample operation on three samples using a predefined string of operations."""
df = Spark.RDataFrame(self.maintreename, self.filenam... | the_stack_v2_python_sparse | python/distrdf/spark/check_definepersample.py | root-project/roottest | train | 41 |
6ead54789686b0fe9dface9f24d2437fc4d03690 | [
"super(Receiver, self).__init__(name='monitowl.receiver')\nself.queue = queue\nself.sqlite_factory = sqlite_factory",
"super(Receiver, self).run()\nwith self.sqlite_factory() as conn:\n while self.running.is_set():\n time.sleep(1)\n while True:\n try:\n msg = self.queue.... | <|body_start_0|>
super(Receiver, self).__init__(name='monitowl.receiver')
self.queue = queue
self.sqlite_factory = sqlite_factory
<|end_body_0|>
<|body_start_1|>
super(Receiver, self).run()
with self.sqlite_factory() as conn:
while self.running.is_set():
... | Receiver process - we run one instance of it. Responsible for reading data from multiprocessing.Queue and storing it in sqlite buffer. | Receiver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Receiver:
"""Receiver process - we run one instance of it. Responsible for reading data from multiprocessing.Queue and storing it in sqlite buffer."""
def __init__(self, queue, sqlite_factory):
"""Initialize variables, setup queue and sqlite."""
<|body_0|>
def run(self):... | stack_v2_sparse_classes_36k_train_029026 | 45,885 | permissive | [
{
"docstring": "Initialize variables, setup queue and sqlite.",
"name": "__init__",
"signature": "def __init__(self, queue, sqlite_factory)"
},
{
"docstring": "Collect data from sensorprocs (via multiprocessing.Queue) and store it in local buffer (sqlite).",
"name": "run",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_017942 | Implement the Python class `Receiver` described below.
Class description:
Receiver process - we run one instance of it. Responsible for reading data from multiprocessing.Queue and storing it in sqlite buffer.
Method signatures and docstrings:
- def __init__(self, queue, sqlite_factory): Initialize variables, setup qu... | Implement the Python class `Receiver` described below.
Class description:
Receiver process - we run one instance of it. Responsible for reading data from multiprocessing.Queue and storing it in sqlite buffer.
Method signatures and docstrings:
- def __init__(self, queue, sqlite_factory): Initialize variables, setup qu... | d3c36672bf444a4ab9a285f32c11a4ac3d2bda31 | <|skeleton|>
class Receiver:
"""Receiver process - we run one instance of it. Responsible for reading data from multiprocessing.Queue and storing it in sqlite buffer."""
def __init__(self, queue, sqlite_factory):
"""Initialize variables, setup queue and sqlite."""
<|body_0|>
def run(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Receiver:
"""Receiver process - we run one instance of it. Responsible for reading data from multiprocessing.Queue and storing it in sqlite buffer."""
def __init__(self, queue, sqlite_factory):
"""Initialize variables, setup queue and sqlite."""
super(Receiver, self).__init__(name='monito... | the_stack_v2_python_sparse | whmonit/client/agent.py | whitehats/monitowl-agent | train | 1 |
2dce3b473ad7a713f1dda527c5e46b678bb8d5cd | [
"with warnings_override(clauses='>= 3.8', action='ignore', category=SyntaxWarning) as _:\n try:\n import magic\n return True\n except ModuleNotFoundError as ex:\n pass\nreturn False",
"filename = bf_check.check_file(filename)\nimport magic\nrv = magic.from_file(filename, mime=True)\nif ... | <|body_start_0|>
with warnings_override(clauses='>= 3.8', action='ignore', category=SyntaxWarning) as _:
try:
import magic
return True
except ModuleNotFoundError as ex:
pass
return False
<|end_body_0|>
<|body_start_1|>
file... | _bf_mime_type_detector_magic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _bf_mime_type_detector_magic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_029027 | 1,011 | permissive | [
{
"docstring": "Return True if this class is supported on the current platform.",
"name": "is_supported",
"signature": "def is_supported(clazz)"
},
{
"docstring": "Detect the mime type for file.",
"name": "detect_mime_type",
"signature": "def detect_mime_type(clazz, filename)"
}
] | 2 | null | Implement the Python class `_bf_mime_type_detector_magic` described below.
Class description:
Implement the _bf_mime_type_detector_magic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filename): Detect t... | Implement the Python class `_bf_mime_type_detector_magic` described below.
Class description:
Implement the _bf_mime_type_detector_magic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filename): Detect t... | b9dd35b518848cea82e43d5016e425cc7dac32e5 | <|skeleton|>
class _bf_mime_type_detector_magic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _bf_mime_type_detector_magic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
with warnings_override(clauses='>= 3.8', action='ignore', category=SyntaxWarning) as _:
try:
import magic
return True
... | the_stack_v2_python_sparse | lib/bes/files/mime/_detail/_bf_mime_type_detector_magic.py | reconstruir/bes | train | 0 | |
95911b7442ade4ac4df9d38b27e632ebe0756c47 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IdentityProtectionRoot()",
"from .risk_detection import RiskDetection\nfrom .risky_service_principal import RiskyServicePrincipal\nfrom .risky_user import RiskyUser\nfrom .service_principal_risk_detection import ServicePrincipalRiskDet... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IdentityProtectionRoot()
<|end_body_0|>
<|body_start_1|>
from .risk_detection import RiskDetection
from .risky_service_principal import RiskyServicePrincipal
from .risky_user imp... | IdentityProtectionRoot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityProtectionRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot:
"""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 ... | stack_v2_sparse_classes_36k_train_029028 | 4,560 | 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: IdentityProtectionRoot",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | null | Implement the Python class `IdentityProtectionRoot` described below.
Class description:
Implement the IdentityProtectionRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot: Creates a new instance of the appropriate class b... | Implement the Python class `IdentityProtectionRoot` described below.
Class description:
Implement the IdentityProtectionRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IdentityProtectionRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityProtectionRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/identity_protection_root.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4928ee6d634a06c78fea409a015bcef877cd035e | [
"self._addr_port = addr_port\nself.connections = {}\nself.accessory_handler = accessory_handler\nself.server = None\nself._serve_task = None\nself._connection_cleanup = None\nself.loop = None",
"self.loop = loop\nself.server = await loop.create_server(lambda: HAPServerProtocol(loop, self.connections, self.accesso... | <|body_start_0|>
self._addr_port = addr_port
self.connections = {}
self.accessory_handler = accessory_handler
self.server = None
self._serve_task = None
self._connection_cleanup = None
self.loop = None
<|end_body_0|>
<|body_start_1|>
self.loop = loop
... | Point of contact for HAP clients. The HAPServer handles all incoming client requests (e.g. pair) and also handles communication from Accessories to clients (value changes). The outbound communication is something like HTTP push. @note: Client requests responses as well as outgoing event notifications happen through the... | HAPServer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HAPServer:
"""Point of contact for HAP clients. The HAPServer handles all incoming client requests (e.g. pair) and also handles communication from Accessories to clients (value changes). The outbound communication is something like HTTP push. @note: Client requests responses as well as outgoing e... | stack_v2_sparse_classes_36k_train_029029 | 3,104 | permissive | [
{
"docstring": "Create a HAP Server.",
"name": "__init__",
"signature": "def __init__(self, addr_port, accessory_handler)"
},
{
"docstring": "Start the http-hap server.",
"name": "async_start",
"signature": "async def async_start(self, loop)"
},
{
"docstring": "Cleanup stale conn... | 5 | stack_v2_sparse_classes_30k_train_014851 | Implement the Python class `HAPServer` described below.
Class description:
Point of contact for HAP clients. The HAPServer handles all incoming client requests (e.g. pair) and also handles communication from Accessories to clients (value changes). The outbound communication is something like HTTP push. @note: Client r... | Implement the Python class `HAPServer` described below.
Class description:
Point of contact for HAP clients. The HAPServer handles all incoming client requests (e.g. pair) and also handles communication from Accessories to clients (value changes). The outbound communication is something like HTTP push. @note: Client r... | 5f45a5e208ef33e37228e9fa9e5c08732d9816b2 | <|skeleton|>
class HAPServer:
"""Point of contact for HAP clients. The HAPServer handles all incoming client requests (e.g. pair) and also handles communication from Accessories to clients (value changes). The outbound communication is something like HTTP push. @note: Client requests responses as well as outgoing e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HAPServer:
"""Point of contact for HAP clients. The HAPServer handles all incoming client requests (e.g. pair) and also handles communication from Accessories to clients (value changes). The outbound communication is something like HTTP push. @note: Client requests responses as well as outgoing event notifica... | the_stack_v2_python_sparse | pyhap/hap_server.py | ikalchev/HAP-python | train | 581 |
454daf817820a8e0ce9a9a33fb7ab5eefdeff117 | [
"student = g.user\napply = GoingoutApplyModel.objects(student=student).first()\nreturn self.unicode_safe_json_response({'sat': apply.on_saturday, 'sun': apply.on_sunday}, 200)",
"student = g.user\nnow = datetime.now()\nif current_app.testing or (now.weekday() == 6 and now.time() > time(20, 30)) or 0 <= now.weekda... | <|body_start_0|>
student = g.user
apply = GoingoutApplyModel.objects(student=student).first()
return self.unicode_safe_json_response({'sat': apply.on_saturday, 'sun': apply.on_sunday}, 200)
<|end_body_0|>
<|body_start_1|>
student = g.user
now = datetime.now()
if current_... | Goingout | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Goingout:
def get(self):
"""외출신청 정보 조회"""
<|body_0|>
def post(self):
"""외출신청"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
student = g.user
apply = GoingoutApplyModel.objects(student=student).first()
return self.unicode_safe_json_r... | stack_v2_sparse_classes_36k_train_029030 | 1,393 | permissive | [
{
"docstring": "외출신청 정보 조회",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "외출신청",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016887 | Implement the Python class `Goingout` described below.
Class description:
Implement the Goingout class.
Method signatures and docstrings:
- def get(self): 외출신청 정보 조회
- def post(self): 외출신청 | Implement the Python class `Goingout` described below.
Class description:
Implement the Goingout class.
Method signatures and docstrings:
- def get(self): 외출신청 정보 조회
- def post(self): 외출신청
<|skeleton|>
class Goingout:
def get(self):
"""외출신청 정보 조회"""
<|body_0|>
def post(self):
"""외출신... | de585fe904a2bf15f9fc74219eae176151a0f8ca | <|skeleton|>
class Goingout:
def get(self):
"""외출신청 정보 조회"""
<|body_0|>
def post(self):
"""외출신청"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Goingout:
def get(self):
"""외출신청 정보 조회"""
student = g.user
apply = GoingoutApplyModel.objects(student=student).first()
return self.unicode_safe_json_response({'sat': apply.on_saturday, 'sun': apply.on_sunday}, 200)
def post(self):
"""외출신청"""
student = g.use... | the_stack_v2_python_sparse | Server/app/views/v1/student/apply/goingout.py | miraedbswo/DMS-Backend | train | 2 | |
2f7d6ad4aea869e8698bce2c357252010789bd9e | [
"MyClass.instance_counter += 1\nself.var1 = kwargs['var1']\nself.var2 = kwargs['var2']\nself.var3 = kwargs['var3']\nprint('MyClass.instance_counter = {}'.format(MyClass.instance_counter))\nif MyClass.instance_counter == 1:\n print(textwrap.dedent('\\n Note to self: to pass in the args list and the... | <|body_start_0|>
MyClass.instance_counter += 1
self.var1 = kwargs['var1']
self.var2 = kwargs['var2']
self.var3 = kwargs['var3']
print('MyClass.instance_counter = {}'.format(MyClass.instance_counter))
if MyClass.instance_counter == 1:
print(textwrap.dedent('\n ... | MyClass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyClass:
def __init__(self, *args, **kwargs):
"""Constructor to create a new MyClass instance. Parameters: *args: special syntax to capture a list of all list arguments **kwargs: special syntax to capture a dict of all keyword arguments passed in as key:value pairs (written as `someFunc(... | stack_v2_sparse_classes_36k_train_029031 | 7,023 | permissive | [
{
"docstring": "Constructor to create a new MyClass instance. Parameters: *args: special syntax to capture a list of all list arguments **kwargs: special syntax to capture a dict of all keyword arguments passed in as key:value pairs (written as `someFunc(key1 = value1, key2 = value2)` when you call the method).... | 2 | stack_v2_sparse_classes_30k_train_020478 | Implement the Python class `MyClass` described below.
Class description:
Implement the MyClass class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor to create a new MyClass instance. Parameters: *args: special syntax to capture a list of all list arguments **kwargs: special synta... | Implement the Python class `MyClass` described below.
Class description:
Implement the MyClass class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor to create a new MyClass instance. Parameters: *args: special syntax to capture a list of all list arguments **kwargs: special synta... | b3b72301db4e9b955077b6472d962ca89c204247 | <|skeleton|>
class MyClass:
def __init__(self, *args, **kwargs):
"""Constructor to create a new MyClass instance. Parameters: *args: special syntax to capture a list of all list arguments **kwargs: special syntax to capture a dict of all keyword arguments passed in as key:value pairs (written as `someFunc(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyClass:
def __init__(self, *args, **kwargs):
"""Constructor to create a new MyClass instance. Parameters: *args: special syntax to capture a list of all list arguments **kwargs: special syntax to capture a dict of all keyword arguments passed in as key:value pairs (written as `someFunc(key1 = value1,... | the_stack_v2_python_sparse | python/slots_practice/slots_practice.py | ElectricRCAircraftGuy/eRCaGuy_hello_world | train | 89 | |
44401ac3845f5b8fe7ef5ae711a32136832dff38 | [
"self.rewards = []\nself.vars = []\nself.filename = filename\nplt.show()\nself.axes = plt.gca()\nself.axes.set_xlim(0, number_of_iterations)",
"self.rewards += [reward]\nself.vars += [variance]\nplt.plot(range(len(self.rewards)), self.rewards, c='b')\nplt.draw()\nplt.pause(1e-17)\nif self.filename is not None:\n ... | <|body_start_0|>
self.rewards = []
self.vars = []
self.filename = filename
plt.show()
self.axes = plt.gca()
self.axes.set_xlim(0, number_of_iterations)
<|end_body_0|>
<|body_start_1|>
self.rewards += [reward]
self.vars += [variance]
plt.plot(range... | LearningCurvePlotter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningCurvePlotter:
def __init__(self, number_of_iterations, filename):
"""Create a plotter for the learning curve :param number_of_iterations: {int} the number of iterations, that TRPO shall be trained :param filename: {string} the filename, where the plot shall be saved"""
<|... | stack_v2_sparse_classes_36k_train_029032 | 1,221 | no_license | [
{
"docstring": "Create a plotter for the learning curve :param number_of_iterations: {int} the number of iterations, that TRPO shall be trained :param filename: {string} the filename, where the plot shall be saved",
"name": "__init__",
"signature": "def __init__(self, number_of_iterations, filename)"
... | 2 | stack_v2_sparse_classes_30k_train_008233 | Implement the Python class `LearningCurvePlotter` described below.
Class description:
Implement the LearningCurvePlotter class.
Method signatures and docstrings:
- def __init__(self, number_of_iterations, filename): Create a plotter for the learning curve :param number_of_iterations: {int} the number of iterations, t... | Implement the Python class `LearningCurvePlotter` described below.
Class description:
Implement the LearningCurvePlotter class.
Method signatures and docstrings:
- def __init__(self, number_of_iterations, filename): Create a plotter for the learning curve :param number_of_iterations: {int} the number of iterations, t... | afc6611e2bff94c547372684a21962c8dda853ff | <|skeleton|>
class LearningCurvePlotter:
def __init__(self, number_of_iterations, filename):
"""Create a plotter for the learning curve :param number_of_iterations: {int} the number of iterations, that TRPO shall be trained :param filename: {string} the filename, where the plot shall be saved"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearningCurvePlotter:
def __init__(self, number_of_iterations, filename):
"""Create a plotter for the learning curve :param number_of_iterations: {int} the number of iterations, that TRPO shall be trained :param filename: {string} the filename, where the plot shall be saved"""
self.rewards = [... | the_stack_v2_python_sparse | TRPO/plotting.py | MaxKircher/RL-project | train | 1 | |
7db22ff38457a0b2a8c2a5dfda41684f3b44b93f | [
"logger.debug('Logging debug message')\nself._client = boto3.client('ssm', region_name=strRegion)\nself._project = '/' + (strProject.rstrip('/') + '/').lstrip('/')\nself._environment = strEnvironment.strip('/')",
"logger.debug('Logging debug message')\nstrIn = self._project + self._environment + '/' + strKey\npar... | <|body_start_0|>
logger.debug('Logging debug message')
self._client = boto3.client('ssm', region_name=strRegion)
self._project = '/' + (strProject.rstrip('/') + '/').lstrip('/')
self._environment = strEnvironment.strip('/')
<|end_body_0|>
<|body_start_1|>
logger.debug('Logging d... | This class is to help extract information from AWS Parameter Store, such as database user id's, passwords etc etc | AWSParameterStore | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSParameterStore:
"""This class is to help extract information from AWS Parameter Store, such as database user id's, passwords etc etc"""
def __init__(self, strProject, strEnvironment, strRegion):
"""Assume my keys are stored in the format: /strProject/strEnvironment/strKey"""
... | stack_v2_sparse_classes_36k_train_029033 | 1,327 | permissive | [
{
"docstring": "Assume my keys are stored in the format: /strProject/strEnvironment/strKey",
"name": "__init__",
"signature": "def __init__(self, strProject, strEnvironment, strRegion)"
},
{
"docstring": "Build key in form /strProject/strEnvironment/strKey, then extract it from client",
"nam... | 2 | null | Implement the Python class `AWSParameterStore` described below.
Class description:
This class is to help extract information from AWS Parameter Store, such as database user id's, passwords etc etc
Method signatures and docstrings:
- def __init__(self, strProject, strEnvironment, strRegion): Assume my keys are stored ... | Implement the Python class `AWSParameterStore` described below.
Class description:
This class is to help extract information from AWS Parameter Store, such as database user id's, passwords etc etc
Method signatures and docstrings:
- def __init__(self, strProject, strEnvironment, strRegion): Assume my keys are stored ... | e6a6a76376d122b224d4744314e687f660aad770 | <|skeleton|>
class AWSParameterStore:
"""This class is to help extract information from AWS Parameter Store, such as database user id's, passwords etc etc"""
def __init__(self, strProject, strEnvironment, strRegion):
"""Assume my keys are stored in the format: /strProject/strEnvironment/strKey"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSParameterStore:
"""This class is to help extract information from AWS Parameter Store, such as database user id's, passwords etc etc"""
def __init__(self, strProject, strEnvironment, strRegion):
"""Assume my keys are stored in the format: /strProject/strEnvironment/strKey"""
logger.deb... | the_stack_v2_python_sparse | ebdjango/scripts/AWSParameterStore.py | MarkyMark1000/AWS---PYTHON---COPY---MYWEBSITE | train | 1 |
c12e937c4718da223b566e8370eaf4066e41203d | [
"if tci is None:\n tci = [0, 0]\ntci = listify(tci)\nif tpid is None:\n tpid = [0 for _ in tci]\ntpid = listify(tpid)\nver_args = [{'name': 'vport', 'arg': vport, 't': 'vport'}, {'name': 'tci', 'arg': tci, 't': 'tci'}, {'name': 'tpid', 'arg': tpid, 't': 'tpid'}]\nEMUValidator.verify(ver_args)\nif tpid != [0, ... | <|body_start_0|>
if tci is None:
tci = [0, 0]
tci = listify(tci)
if tpid is None:
tpid = [0 for _ in tci]
tpid = listify(tpid)
ver_args = [{'name': 'vport', 'arg': vport, 't': 'vport'}, {'name': 'tci', 'arg': tci, 't': 'tci'}, {'name': 'tpid', 'arg': tpid,... | EMUNamespaceKey | [
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"GPL-2.0-only",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EMUNamespaceKey:
def __init__(self, vport, tci=None, tpid=None, **kwargs):
"""Creates a namespace key, defines a namespace in emulation server. .. code-block:: python # creating a namespace key with no vlans ns_key = EMUNamespaceKey(vport = 0) # creating a namespace key with vlan using d... | stack_v2_sparse_classes_36k_train_029034 | 21,620 | permissive | [
{
"docstring": "Creates a namespace key, defines a namespace in emulation server. .. code-block:: python # creating a namespace key with no vlans ns_key = EMUNamespaceKey(vport = 0) # creating a namespace key with vlan using default tpid(0x8100) ns_key = EMUNamespaceKey(vport = 0, tci = 1) # creating a namespac... | 2 | null | Implement the Python class `EMUNamespaceKey` described below.
Class description:
Implement the EMUNamespaceKey class.
Method signatures and docstrings:
- def __init__(self, vport, tci=None, tpid=None, **kwargs): Creates a namespace key, defines a namespace in emulation server. .. code-block:: python # creating a name... | Implement the Python class `EMUNamespaceKey` described below.
Class description:
Implement the EMUNamespaceKey class.
Method signatures and docstrings:
- def __init__(self, vport, tci=None, tpid=None, **kwargs): Creates a namespace key, defines a namespace in emulation server. .. code-block:: python # creating a name... | 564fb7ba2a003065270a9bcc9946e7a7473f668e | <|skeleton|>
class EMUNamespaceKey:
def __init__(self, vport, tci=None, tpid=None, **kwargs):
"""Creates a namespace key, defines a namespace in emulation server. .. code-block:: python # creating a namespace key with no vlans ns_key = EMUNamespaceKey(vport = 0) # creating a namespace key with vlan using d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EMUNamespaceKey:
def __init__(self, vport, tci=None, tpid=None, **kwargs):
"""Creates a namespace key, defines a namespace in emulation server. .. code-block:: python # creating a namespace key with no vlans ns_key = EMUNamespaceKey(vport = 0) # creating a namespace key with vlan using default tpid(0x... | the_stack_v2_python_sparse | scripts/automation/trex_control_plane/interactive/trex/emu/trex_emu_profile.py | ramakristipati/trex-core | train | 0 | |
51150a4095974d2d452ece500216ccd2cdec12bf | [
"if image_no < len(Explosion.sprites):\n image = Explosion.sprites[image_no]\nelse:\n image = Explosion.sprites[0]\nsuper().__init__(initial_x, initial_y, game_width, game_height, image, debug)\nself.sound.play('explosion')\nself.tts = tick_life",
"if self.tts:\n self.tts -= 1\nelse:\n self.kill()\nsu... | <|body_start_0|>
if image_no < len(Explosion.sprites):
image = Explosion.sprites[image_no]
else:
image = Explosion.sprites[0]
super().__init__(initial_x, initial_y, game_width, game_height, image, debug)
self.sound.play('explosion')
self.tts = tick_life
<|... | Explosion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Explosion:
def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False):
"""The main class for the explosion"""
<|body_0|>
def update(self):
"""Update the explosion"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_029035 | 1,151 | permissive | [
{
"docstring": "The main class for the explosion",
"name": "__init__",
"signature": "def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False)"
},
{
"docstring": "Update the explosion",
"name": "update",
"sig... | 2 | null | Implement the Python class `Explosion` described below.
Class description:
Implement the Explosion class.
Method signatures and docstrings:
- def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False): The main class for the explosion
- de... | Implement the Python class `Explosion` described below.
Class description:
Implement the Explosion class.
Method signatures and docstrings:
- def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False): The main class for the explosion
- de... | 6f8f2da4fd26ef1d77c0c6183230c3a5e6bf0bb9 | <|skeleton|>
class Explosion:
def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False):
"""The main class for the explosion"""
<|body_0|>
def update(self):
"""Update the explosion"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Explosion:
def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False):
"""The main class for the explosion"""
if image_no < len(Explosion.sprites):
image = Explosion.sprites[image_no]
else:
... | the_stack_v2_python_sparse | gym_invaders/gym_game/envs/classes/Game/Sprites/Explosion.py | Jh123x/Orbital | train | 4 | |
9b58ef2b28761f7d76595ec670c015288dcf0c35 | [
"ans = []\nboard = [['.'] * n for _ in range(n)]\nself.fill_row(ans, board, [], n, 0)\nreturn ans",
"if row == n:\n ans.append([''.join(i) for i in board])\n return\nfor col in range(n):\n available = True\n for position in positions:\n if row == position[0] or col == position[1] or abs(row - p... | <|body_start_0|>
ans = []
board = [['.'] * n for _ in range(n)]
self.fill_row(ans, board, [], n, 0)
return ans
<|end_body_0|>
<|body_start_1|>
if row == n:
ans.append([''.join(i) for i in board])
return
for col in range(n):
available =... | 20190818 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
<|body_0|>
def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: int, row: int):
"""填入行""... | stack_v2_sparse_classes_36k_train_029036 | 1,601 | no_license | [
{
"docstring": "暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n: int) -> List[List[str]]"
},
{
"docstring": "填入行",
"name": "fill_row",
"signature": "def fill_row(self, ans: List[List[str]], board: List[List[str]], pos... | 2 | stack_v2_sparse_classes_30k_train_010267 | Implement the Python class `Solution` described below.
Class description:
20190818
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了
- def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: ... | Implement the Python class `Solution` described below.
Class description:
20190818
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了
- def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: ... | efea806d49f07d78e3db0390696778d4a7fc6c28 | <|skeleton|>
class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
<|body_0|>
def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: int, row: int):
"""填入行""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
ans = []
board = [['.'] * n for _ in range(n)]
self.fill_row(ans, board, [], n, 0)
return ans
def fill_row(self, ans: List[L... | the_stack_v2_python_sparse | ToolsX/leetcode/0051/0051.py | JunLei-MI/PythonX | train | 0 |
07b1b2b0ab58c5a50cf38a1ffc0cb187b124d41f | [
"super(InputRandom, self).store(prng)\nself.seed.store(prng.seed)\ngstate = prng.state\nself.state.store(gstate[1])\nself.set_pos.store(gstate[2])\nself.has_gauss.store(gstate[3])\nself.gauss.store(gstate[4])",
"super(InputRandom, self).fetch()\nif not self.state._explicit:\n return Random(seed=self.seed.fetch... | <|body_start_0|>
super(InputRandom, self).store(prng)
self.seed.store(prng.seed)
gstate = prng.state
self.state.store(gstate[1])
self.set_pos.store(gstate[2])
self.has_gauss.store(gstate[3])
self.gauss.store(gstate[4])
<|end_body_0|>
<|body_start_1|>
supe... | Random input class. Handles generating the appropriate random number class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: seed: An optional integer giving a seed to initialise the random number generator from. Defaults to 123456. state: An optional a... | InputRandom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputRandom:
"""Random input class. Handles generating the appropriate random number class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: seed: An optional integer giving a seed to initialise the random number generator from. D... | stack_v2_sparse_classes_36k_train_029037 | 3,907 | no_license | [
{
"docstring": "Takes a random number instance and stores a minimal representation of it. Args: prng: A random number object from which to initialise from.",
"name": "store",
"signature": "def store(self, prng)"
},
{
"docstring": "Creates a random number object. Returns: An random number object ... | 2 | null | Implement the Python class `InputRandom` described below.
Class description:
Random input class. Handles generating the appropriate random number class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: seed: An optional integer giving a seed to initial... | Implement the Python class `InputRandom` described below.
Class description:
Random input class. Handles generating the appropriate random number class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: seed: An optional integer giving a seed to initial... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class InputRandom:
"""Random input class. Handles generating the appropriate random number class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: seed: An optional integer giving a seed to initialise the random number generator from. D... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputRandom:
"""Random input class. Handles generating the appropriate random number class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: seed: An optional integer giving a seed to initialise the random number generator from. Defaults to 12... | the_stack_v2_python_sparse | ipi/inputs/prng.py | i-pi/i-pi | train | 170 |
b764c9e186da963d07af840d9743b87cc3fec3a4 | [
"with self._preprocess_graph_lock:\n if self._preprocess_graph is None:\n self._preprocess_graph = PreprocessGraph()",
"dataset, image_path, label = element\nimage_data = tf.io.gfile.GFile(image_path, 'rb').read()\nif self._preprocess_graph is None:\n raise RuntimeError('self._preprocess_graph not in... | <|body_start_0|>
with self._preprocess_graph_lock:
if self._preprocess_graph is None:
self._preprocess_graph = PreprocessGraph()
<|end_body_0|>
<|body_start_1|>
dataset, image_path, label = element
image_data = tf.io.gfile.GFile(image_path, 'rb').read()
if se... | Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord. | PreprocessImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessImage:
"""Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord."""
def start_bundle(self):
... | stack_v2_sparse_classes_36k_train_029038 | 12,153 | permissive | [
{
"docstring": "Starts an Apache Beam bundle. We cache the Tensorflow session per bundle to avoid cold starts for the processing of each element.",
"name": "start_bundle",
"signature": "def start_bundle(self)"
},
{
"docstring": "Calculates the bottleneck for an image. Args: element: A beam.PColl... | 2 | null | Implement the Python class `PreprocessImage` described below.
Class description:
Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRe... | Implement the Python class `PreprocessImage` described below.
Class description:
Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRe... | cb8ad454b351b86c70a32b70a0ff57049ab1d9c6 | <|skeleton|>
class PreprocessImage:
"""Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord."""
def start_bundle(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreprocessImage:
"""Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord."""
def start_bundle(self):
"""Sta... | the_stack_v2_python_sparse | imaging/ml/ml_codelab/scripts/preprocess/preprocess.py | GoogleCloudPlatform/healthcare | train | 368 |
c72430c1dae49d4ab1fb960fe3cbfcbb7732bb96 | [
"cmd = ['--board=randonname', 'power_manager']\nself.PatchObject(workon_helper, 'WorkonHelper')\nself.PatchObject(command, 'UseProgressBar', return_value=True)\nwith MockBuildCommand(cmd) as build:\n operation_run = self.PatchObject(cros_build.BrilloBuildOperation, 'Run')\n build.inst.Run()\n self.assertTr... | <|body_start_0|>
cmd = ['--board=randonname', 'power_manager']
self.PatchObject(workon_helper, 'WorkonHelper')
self.PatchObject(command, 'UseProgressBar', return_value=True)
with MockBuildCommand(cmd) as build:
operation_run = self.PatchObject(cros_build.BrilloBuildOperation,... | Test class for our BuildCommand class. | BuildCommandTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildCommandTest:
"""Test class for our BuildCommand class."""
def testBrilloBuildOperationCalled(self):
"""Test that BrilloBuildOperation is used when appropriate."""
<|body_0|>
def testBrilloBuildOperationNotCalled(self):
"""Test that BrilloBuildOperation is no... | stack_v2_sparse_classes_36k_train_029039 | 4,632 | permissive | [
{
"docstring": "Test that BrilloBuildOperation is used when appropriate.",
"name": "testBrilloBuildOperationCalled",
"signature": "def testBrilloBuildOperationCalled(self)"
},
{
"docstring": "Test that BrilloBuildOperation is not used when it shouldn't be.",
"name": "testBrilloBuildOperation... | 4 | stack_v2_sparse_classes_30k_train_014185 | Implement the Python class `BuildCommandTest` described below.
Class description:
Test class for our BuildCommand class.
Method signatures and docstrings:
- def testBrilloBuildOperationCalled(self): Test that BrilloBuildOperation is used when appropriate.
- def testBrilloBuildOperationNotCalled(self): Test that Brill... | Implement the Python class `BuildCommandTest` described below.
Class description:
Test class for our BuildCommand class.
Method signatures and docstrings:
- def testBrilloBuildOperationCalled(self): Test that BrilloBuildOperation is used when appropriate.
- def testBrilloBuildOperationNotCalled(self): Test that Brill... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class BuildCommandTest:
"""Test class for our BuildCommand class."""
def testBrilloBuildOperationCalled(self):
"""Test that BrilloBuildOperation is used when appropriate."""
<|body_0|>
def testBrilloBuildOperationNotCalled(self):
"""Test that BrilloBuildOperation is no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildCommandTest:
"""Test class for our BuildCommand class."""
def testBrilloBuildOperationCalled(self):
"""Test that BrilloBuildOperation is used when appropriate."""
cmd = ['--board=randonname', 'power_manager']
self.PatchObject(workon_helper, 'WorkonHelper')
self.PatchO... | the_stack_v2_python_sparse | third_party/chromite/cli/cros/cros_build_unittest.py | metux/chromium-suckless | train | 5 |
1b09195ed75184e7317f225582e474fda33c717a | [
"self._center = _format_LatLng(lat, lng, precision)\nself._radius = radius\nedge_color = kwargs.get('edge_color')\nself._edge_color = _get_hex_color(edge_color) if edge_color is not None else None\nself._edge_alpha = kwargs.get('edge_alpha')\nself._edge_width = kwargs.get('edge_width')\nface_color = kwargs.get('fac... | <|body_start_0|>
self._center = _format_LatLng(lat, lng, precision)
self._radius = radius
edge_color = kwargs.get('edge_color')
self._edge_color = _get_hex_color(edge_color) if edge_color is not None else None
self._edge_alpha = kwargs.get('edge_alpha')
self._edge_width =... | _Circle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Circle:
def __init__(self, lat, lng, radius, precision, **kwargs):
"""Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round ... | stack_v2_sparse_classes_36k_train_029040 | 2,435 | permissive | [
{
"docstring": "Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: edge_color (str): Color of the circle's ... | 2 | stack_v2_sparse_classes_30k_train_009827 | Implement the Python class `_Circle` described below.
Class description:
Implement the _Circle class.
Method signatures and docstrings:
- def __init__(self, lat, lng, radius, precision, **kwargs): Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int)... | Implement the Python class `_Circle` described below.
Class description:
Implement the _Circle class.
Method signatures and docstrings:
- def __init__(self, lat, lng, radius, precision, **kwargs): Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int)... | 8654a5a370b5ec309e1282c457eaf375c3dcb4bb | <|skeleton|>
class _Circle:
def __init__(self, lat, lng, radius, precision, **kwargs):
"""Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Circle:
def __init__(self, lat, lng, radius, precision, **kwargs):
"""Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round to for lat/lng... | the_stack_v2_python_sparse | gmplot/drawables/symbols/circle.py | fishke22/gmplot | train | 0 | |
0f3c4d5f5b4612aeda45948a58d301a4e843daf1 | [
"from collections import defaultdict\nself.d = defaultdict(set)\nfor word in dictionary:\n if len(word) <= 2:\n key = word\n else:\n key = word[0] + str(len(word) - 2) + word[-1]\n self.d[key].add(word)",
"if len(word) <= 2:\n key = word\nelse:\n key = word[0] + str(len(word) - 2) + w... | <|body_start_0|>
from collections import defaultdict
self.d = defaultdict(set)
for word in dictionary:
if len(word) <= 2:
key = word
else:
key = word[0] + str(len(word) - 2) + word[-1]
self.d[key].add(word)
<|end_body_0|>
<|bod... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from collections import defaultdict
self.d ... | stack_v2_sparse_classes_36k_train_029041 | 948 | no_license | [
{
"docstring": ":type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | null | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
def __init_... | fe79161211cc08c269cde9e1fdcfed27de11f2cb | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
from collections import defaultdict
self.d = defaultdict(set)
for word in dictionary:
if len(word) <= 2:
key = word
else:
key = word[0] + str... | the_stack_v2_python_sparse | MyLeetCode/python/Unique Word Abbreviation.py | ihuei801/leetcode | train | 0 | |
f79c1fc0d7b3ce46ff545255bcb10a80ce40d2a3 | [
"dict = json.loads(request.body.decode())\nreceiver = dict.get('receiver')\nprovince_id = dict.get('province_id')\ncity_id = dict.get('city_id')\ndistrict_id = dict.get('district_id')\nplace = dict.get('place')\nmobile = dict.get('mobile')\nphone = dict.get('tel')\nemail = dict.get('email')\nif not all([receiver, p... | <|body_start_0|>
dict = json.loads(request.body.decode())
receiver = dict.get('receiver')
province_id = dict.get('province_id')
city_id = dict.get('city_id')
district_id = dict.get('district_id')
place = dict.get('place')
mobile = dict.get('mobile')
phone ... | UpdateDestroyAddressView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyAddressView:
def put(self, request, address_id):
"""更新某一个指定的地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除对应的地址"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict = json.loads(request.body.decode())
receiver = d... | stack_v2_sparse_classes_36k_train_029042 | 22,210 | permissive | [
{
"docstring": "更新某一个指定的地址",
"name": "put",
"signature": "def put(self, request, address_id)"
},
{
"docstring": "删除对应的地址",
"name": "delete",
"signature": "def delete(self, request, address_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016536 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
Implement the UpdateDestroyAddressView class.
Method signatures and docstrings:
- def put(self, request, address_id): 更新某一个指定的地址
- def delete(self, request, address_id): 删除对应的地址 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
Implement the UpdateDestroyAddressView class.
Method signatures and docstrings:
- def put(self, request, address_id): 更新某一个指定的地址
- def delete(self, request, address_id): 删除对应的地址
<|skeleton|>
class UpdateDestroyAddressView:
... | e037bd86fd221e1a41a44059d148fe2f980ab0a5 | <|skeleton|>
class UpdateDestroyAddressView:
def put(self, request, address_id):
"""更新某一个指定的地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除对应的地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateDestroyAddressView:
def put(self, request, address_id):
"""更新某一个指定的地址"""
dict = json.loads(request.body.decode())
receiver = dict.get('receiver')
province_id = dict.get('province_id')
city_id = dict.get('city_id')
district_id = dict.get('district_id')
... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | wlyswh2010/meiduo_admin_project | train | 0 | |
4da0d84e1b1df00e7ac8a6c85880a3d77a67174b | [
"nums_len = len(nums)\nmin_sublen = nums_len + 1\nsubnums_sum = [[0 for _ in range(nums_len)] for _ in range(nums_len)]\nfor i in range(nums_len - 1, -1, -1):\n for j in range(nums_len - 1, i - 1, -1):\n if i == j:\n subnums_sum[i][i] = nums[i]\n else:\n subnums_sum[i][j] = su... | <|body_start_0|>
nums_len = len(nums)
min_sublen = nums_len + 1
subnums_sum = [[0 for _ in range(nums_len)] for _ in range(nums_len)]
for i in range(nums_len - 1, -1, -1):
for j in range(nums_len - 1, i - 1, -1):
if i == j:
subnums_sum[i][i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
"""note:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 :param s: :param nums: :return:"""
<|body_0|>
def minSubArrayLen2(self, s: int, nums: List[int]) -> int:
"""n... | stack_v2_sparse_classes_36k_train_029043 | 3,156 | no_license | [
{
"docstring": "note:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 :param s: :param nums: :return:",
"name": "minSubArrayLen",
"signature": "def minSubArrayLen(self, s: int, nums: List[int]) -> int"
},
{
"docstring": "note:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen(self, s: int, nums: List[int]) -> int: note:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 :param s: :param nums: :return:
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen(self, s: int, nums: List[int]) -> int: note:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 :param s: :param nums: :return:
-... | f7421522c437c952698736dbac8fb7ac6c0b8b88 | <|skeleton|>
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
"""note:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 :param s: :param nums: :return:"""
<|body_0|>
def minSubArrayLen2(self, s: int, nums: List[int]) -> int:
"""n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
"""note:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 :param s: :param nums: :return:"""
nums_len = len(nums)
min_sublen = nums_len + 1
subnums_sum = [[0 for _ in range(nums_... | the_stack_v2_python_sparse | leetcode/daily_question/20200628_min_subarray_len.py | whitepaper2/data_beauty | train | 0 | |
685b3d3a646fb5fd6990e153ab32864142515467 | [
"f_count = len(filter_seq)\nevent_seq_tuple = itertools.tee(aevent_seq, f_count + 1)\nfor filter_desc, event_seq in zip(filter_seq, event_seq_tuple[1:]):\n offset = filter_desc.get('offset', 0)\n new_event_seq = filter_desc.get('filter').filter_objects(event_seq)\n for event in new_event_seq:\n filt... | <|body_start_0|>
f_count = len(filter_seq)
event_seq_tuple = itertools.tee(aevent_seq, f_count + 1)
for filter_desc, event_seq in zip(filter_seq, event_seq_tuple[1:]):
offset = filter_desc.get('offset', 0)
new_event_seq = filter_desc.get('filter').filter_objects(event_seq... | ... | BaseEventSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseEventSelector:
"""..."""
def plot(self, aevent_seq, chart, filter_seq):
""":param aevent_seq: :param chart: :param filter_seq:"""
<|body_0|>
def filter_events(self, event_seq, **kwargs):
"""Should be implemented :param event_seq:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_029044 | 24,668 | permissive | [
{
"docstring": ":param aevent_seq: :param chart: :param filter_seq:",
"name": "plot",
"signature": "def plot(self, aevent_seq, chart, filter_seq)"
},
{
"docstring": "Should be implemented :param event_seq:",
"name": "filter_events",
"signature": "def filter_events(self, event_seq, **kwar... | 2 | null | Implement the Python class `BaseEventSelector` described below.
Class description:
...
Method signatures and docstrings:
- def plot(self, aevent_seq, chart, filter_seq): :param aevent_seq: :param chart: :param filter_seq:
- def filter_events(self, event_seq, **kwargs): Should be implemented :param event_seq: | Implement the Python class `BaseEventSelector` described below.
Class description:
...
Method signatures and docstrings:
- def plot(self, aevent_seq, chart, filter_seq): :param aevent_seq: :param chart: :param filter_seq:
- def filter_events(self, event_seq, **kwargs): Should be implemented :param event_seq:
<|skele... | 617ff45c9c3c96bbd9a975aef15f1b2697282b9c | <|skeleton|>
class BaseEventSelector:
"""..."""
def plot(self, aevent_seq, chart, filter_seq):
""":param aevent_seq: :param chart: :param filter_seq:"""
<|body_0|>
def filter_events(self, event_seq, **kwargs):
"""Should be implemented :param event_seq:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseEventSelector:
"""..."""
def plot(self, aevent_seq, chart, filter_seq):
""":param aevent_seq: :param chart: :param filter_seq:"""
f_count = len(filter_seq)
event_seq_tuple = itertools.tee(aevent_seq, f_count + 1)
for filter_desc, event_seq in zip(filter_seq, event_seq_... | the_stack_v2_python_sparse | shot_detector/charts/event/old_event_chart.py | w495/python-video-shot-detector | train | 20 |
37df6ce18c4ba8d1992ec9b70dd9bffc2ee55246 | [
"self.numberOfSimulations = numberOfSimulations\nself.T = T\nself.initialValue = initialValue\nself.sigma = sigma\nself.r = r\nnp.random.seed(seed)",
"standardNormalRealizations = np.random.standard_normal(self.numberOfSimulations)\nfirstPart = self.initialValue * math.exp((self.r - 0.5 * self.sigma ** 2) * self.... | <|body_start_0|>
self.numberOfSimulations = numberOfSimulations
self.T = T
self.initialValue = initialValue
self.sigma = sigma
self.r = r
np.random.seed(seed)
<|end_body_0|>
<|body_start_1|>
standardNormalRealizations = np.random.standard_normal(self.numberOfSimu... | In this class we generate N realizations of a log-normal process dX_t = r X_t dt + sigma X_t dW_t at time T>0. We do it by writing X_T = X_0 exp((r- 0.5 sigma^2) T + sigma T^0.5 Z), where Z is a standard normal random variable. We proceed in two different ways: - we generate the N realizations of Z directly; - we first... | GenerateBlackScholes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateBlackScholes:
"""In this class we generate N realizations of a log-normal process dX_t = r X_t dt + sigma X_t dW_t at time T>0. We do it by writing X_T = X_0 exp((r- 0.5 sigma^2) T + sigma T^0.5 Z), where Z is a standard normal random variable. We proceed in two different ways: - we gener... | stack_v2_sparse_classes_36k_train_029045 | 5,988 | no_license | [
{
"docstring": "Parameters ---------- numberOfSimulations : int the number of simulated values of the process at maturity T : float the maturity of the option initialValue : float the initial value of the process sigma : float the standard deviation r : float the interest rate. Default = 0 seed : int the seed t... | 3 | stack_v2_sparse_classes_30k_train_021349 | Implement the Python class `GenerateBlackScholes` described below.
Class description:
In this class we generate N realizations of a log-normal process dX_t = r X_t dt + sigma X_t dW_t at time T>0. We do it by writing X_T = X_0 exp((r- 0.5 sigma^2) T + sigma T^0.5 Z), where Z is a standard normal random variable. We pr... | Implement the Python class `GenerateBlackScholes` described below.
Class description:
In this class we generate N realizations of a log-normal process dX_t = r X_t dt + sigma X_t dW_t at time T>0. We do it by writing X_T = X_0 exp((r- 0.5 sigma^2) T + sigma T^0.5 Z), where Z is a standard normal random variable. We pr... | 4314e47509b05523ee547be9ba6970870f9bcde0 | <|skeleton|>
class GenerateBlackScholes:
"""In this class we generate N realizations of a log-normal process dX_t = r X_t dt + sigma X_t dW_t at time T>0. We do it by writing X_T = X_0 exp((r- 0.5 sigma^2) T + sigma T^0.5 Z), where Z is a standard normal random variable. We proceed in two different ways: - we gener... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenerateBlackScholes:
"""In this class we generate N realizations of a log-normal process dX_t = r X_t dt + sigma X_t dW_t at time T>0. We do it by writing X_T = X_0 exp((r- 0.5 sigma^2) T + sigma T^0.5 Z), where Z is a standard normal random variable. We proceed in two different ways: - we generate the N rea... | the_stack_v2_python_sparse | Computational-finance-python/montecarlovariancereduction/antitheticvariables/generateBlackScholes.py | AndreaMaz/Computational-finance-python | train | 1 |
f3417ecf525e955648492a7cd858dad1b06f9119 | [
"input_shapes = [[None, 1, 2], [64, 2, 2], [None, 3, 2]]\nconcat_layer = layers.MergeLayer(mode='concat', axis=1)\nconcat_output_shape = concat_layer.compute_output_shape(input_shapes)\nself.assertEqual(concat_output_shape, [64, 6, 2])\nsum_layer = layers.MergeLayer(mode='sum', axis=1)\nsum_output_shape = sum_layer... | <|body_start_0|>
input_shapes = [[None, 1, 2], [64, 2, 2], [None, 3, 2]]
concat_layer = layers.MergeLayer(mode='concat', axis=1)
concat_output_shape = concat_layer.compute_output_shape(input_shapes)
self.assertEqual(concat_output_shape, [64, 6, 2])
sum_layer = layers.MergeLayer(m... | Tests MergeLayer. | MergeLayerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_output_shape(self):
"""Tests MergeLayer.compute_output_shape function."""
<|body_0|>
def test_layer_logics(self):
"""Test the logic of MergeLayer."""
<|body_1|>
def test_trainable_variables(self):
... | stack_v2_sparse_classes_36k_train_029046 | 11,544 | permissive | [
{
"docstring": "Tests MergeLayer.compute_output_shape function.",
"name": "test_output_shape",
"signature": "def test_output_shape(self)"
},
{
"docstring": "Test the logic of MergeLayer.",
"name": "test_layer_logics",
"signature": "def test_layer_logics(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_002512 | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_output_shape(self): Tests MergeLayer.compute_output_shape function.
- def test_layer_logics(self): Test the logic of MergeLayer.
- def test_trainable_variables(self): Test the... | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_output_shape(self): Tests MergeLayer.compute_output_shape function.
- def test_layer_logics(self): Test the logic of MergeLayer.
- def test_trainable_variables(self): Test the... | 0704b3d4c93915b9a6f96b725e49ae20bf5d1e90 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_output_shape(self):
"""Tests MergeLayer.compute_output_shape function."""
<|body_0|>
def test_layer_logics(self):
"""Test the logic of MergeLayer."""
<|body_1|>
def test_trainable_variables(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeLayerTest:
"""Tests MergeLayer."""
def test_output_shape(self):
"""Tests MergeLayer.compute_output_shape function."""
input_shapes = [[None, 1, 2], [64, 2, 2], [None, 3, 2]]
concat_layer = layers.MergeLayer(mode='concat', axis=1)
concat_output_shape = concat_layer.com... | the_stack_v2_python_sparse | texar/tf/core/layers_test.py | arita37/texar | train | 2 |
998b981b27648294c5a3969f13806919b625d01f | [
"self.memo = {}\nres = 0\nl = 0\nr = 0\nwhile r < len(S):\n while not self.helper(S[l:r + 1], T):\n l += 1\n res += r - l + 1\n r += 1\nreturn res",
"if not sub_str:\n return True\nif sub_str in self.memo:\n return self.memo[sub_str]\nres = True\ni = 0\nfor c in sub_str:\n while i < len(T... | <|body_start_0|>
self.memo = {}
res = 0
l = 0
r = 0
while r < len(S):
while not self.helper(S[l:r + 1], T):
l += 1
res += r - l + 1
r += 1
return res
<|end_body_0|>
<|body_start_1|>
if not sub_str:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def func(self, S, T):
"""Args: S: str T: str Return: int"""
<|body_0|>
def helper(self, sub_str, T):
"""sub_str是不是T的子序列 Args: sub_str: str T: str Return: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.memo = {}
res = 0
... | stack_v2_sparse_classes_36k_train_029047 | 1,200 | no_license | [
{
"docstring": "Args: S: str T: str Return: int",
"name": "func",
"signature": "def func(self, S, T)"
},
{
"docstring": "sub_str是不是T的子序列 Args: sub_str: str T: str Return: bool",
"name": "helper",
"signature": "def helper(self, sub_str, T)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, S, T): Args: S: str T: str Return: int
- def helper(self, sub_str, T): sub_str是不是T的子序列 Args: sub_str: str T: str Return: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, S, T): Args: S: str T: str Return: int
- def helper(self, sub_str, T): sub_str是不是T的子序列 Args: sub_str: str T: str Return: bool
<|skeleton|>
class Solution:
de... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def func(self, S, T):
"""Args: S: str T: str Return: int"""
<|body_0|>
def helper(self, sub_str, T):
"""sub_str是不是T的子序列 Args: sub_str: str T: str Return: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def func(self, S, T):
"""Args: S: str T: str Return: int"""
self.memo = {}
res = 0
l = 0
r = 0
while r < len(S):
while not self.helper(S[l:r + 1], T):
l += 1
res += r - l + 1
r += 1
return res... | the_stack_v2_python_sparse | 秋招/阿里/1.py | AiZhanghan/Leetcode | train | 0 | |
8ff67c32c27c3ce8e9e2d623ec1b626734b61c7f | [
"super().__init__(fmt='%(message)s', datefmt='%Y-%m-%d %H:%M:%S', style='%')\nself.append_br = append_br\nself.replace_nl_with_br = replace_nl_with_br",
"super().format(record)\nrecord.asctime = self.formatTime(record, self.datefmt)\nbg_col = self.log_background_colors[record.levelno]\nmsg = escape(record.getMess... | <|body_start_0|>
super().__init__(fmt='%(message)s', datefmt='%Y-%m-%d %H:%M:%S', style='%')
self.append_br = append_br
self.replace_nl_with_br = replace_nl_with_br
<|end_body_0|>
<|body_start_1|>
super().format(record)
record.asctime = self.formatTime(record, self.datefmt)
... | Class to format Python logs in coloured HTML. | HtmlColorFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlColorFormatter:
"""Class to format Python logs in coloured HTML."""
def __init__(self, append_br: bool=False, replace_nl_with_br: bool=True) -> None:
"""Args: append_br: append ``<br>`` to each line? replace_nl_with_br: replace ``\\n`` with ``<br>`` in messages? See https://hg.py... | stack_v2_sparse_classes_36k_train_029048 | 26,012 | permissive | [
{
"docstring": "Args: append_br: append ``<br>`` to each line? replace_nl_with_br: replace ``\\\\n`` with ``<br>`` in messages? See https://hg.python.org/cpython/file/3.5/Lib/logging/__init__.py",
"name": "__init__",
"signature": "def __init__(self, append_br: bool=False, replace_nl_with_br: bool=True) ... | 2 | null | Implement the Python class `HtmlColorFormatter` described below.
Class description:
Class to format Python logs in coloured HTML.
Method signatures and docstrings:
- def __init__(self, append_br: bool=False, replace_nl_with_br: bool=True) -> None: Args: append_br: append ``<br>`` to each line? replace_nl_with_br: rep... | Implement the Python class `HtmlColorFormatter` described below.
Class description:
Class to format Python logs in coloured HTML.
Method signatures and docstrings:
- def __init__(self, append_br: bool=False, replace_nl_with_br: bool=True) -> None: Args: append_br: append ``<br>`` to each line? replace_nl_with_br: rep... | 86ec00e039a85b90609c8fe4b221d183912eaec4 | <|skeleton|>
class HtmlColorFormatter:
"""Class to format Python logs in coloured HTML."""
def __init__(self, append_br: bool=False, replace_nl_with_br: bool=True) -> None:
"""Args: append_br: append ``<br>`` to each line? replace_nl_with_br: replace ``\\n`` with ``<br>`` in messages? See https://hg.py... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlColorFormatter:
"""Class to format Python logs in coloured HTML."""
def __init__(self, append_br: bool=False, replace_nl_with_br: bool=True) -> None:
"""Args: append_br: append ``<br>`` to each line? replace_nl_with_br: replace ``\\n`` with ``<br>`` in messages? See https://hg.python.org/cpyt... | the_stack_v2_python_sparse | cardinal_pythonlib/logs.py | RudolfCardinal/pythonlib | train | 12 |
d92f46d1023c2b91e32cbe82ab07c61bfb614667 | [
"print('Making autoaligner from reference %s' % reference)\nfrom riglib.stereo_opengl import xfm\nself._quat = xfm.Quaternion\nself.ref = np.load(reference)['reference']\nself.xfm = xfm.Quaternion()\nself.off1 = np.array([0, 0, 0])\nself.off2 = np.array([0, 0, 0])",
"mdata = data.mean(0)[:, :3]\navail = (data[:, ... | <|body_start_0|>
print('Making autoaligner from reference %s' % reference)
from riglib.stereo_opengl import xfm
self._quat = xfm.Quaternion
self.ref = np.load(reference)['reference']
self.xfm = xfm.Quaternion()
self.off1 = np.array([0, 0, 0])
self.off2 = np.array(... | Runs the autoalignment filter to center everything into the chair coordinates | AutoAlign | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoAlign:
"""Runs the autoalignment filter to center everything into the chair coordinates"""
def __init__(self, reference):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def __call__(self, data):
"""Docstring Parameters ---------- Returns ---... | stack_v2_sparse_classes_36k_train_029049 | 6,997 | permissive | [
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "__init__",
"signature": "def __init__(self, reference)"
},
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "__call__",
"signature": "def __call__(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006872 | Implement the Python class `AutoAlign` described below.
Class description:
Runs the autoalignment filter to center everything into the chair coordinates
Method signatures and docstrings:
- def __init__(self, reference): Docstring Parameters ---------- Returns -------
- def __call__(self, data): Docstring Parameters -... | Implement the Python class `AutoAlign` described below.
Class description:
Runs the autoalignment filter to center everything into the chair coordinates
Method signatures and docstrings:
- def __init__(self, reference): Docstring Parameters ---------- Returns -------
- def __call__(self, data): Docstring Parameters -... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class AutoAlign:
"""Runs the autoalignment filter to center everything into the chair coordinates"""
def __init__(self, reference):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def __call__(self, data):
"""Docstring Parameters ---------- Returns ---... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoAlign:
"""Runs the autoalignment filter to center everything into the chair coordinates"""
def __init__(self, reference):
"""Docstring Parameters ---------- Returns -------"""
print('Making autoaligner from reference %s' % reference)
from riglib.stereo_opengl import xfm
... | the_stack_v2_python_sparse | riglib/calibrations.py | carmenalab/brain-python-interface | train | 9 |
d59f4dd0f01cf318713bf8a3ba63deb47216f43d | [
"citizen_ids_set = set()\ncitizen_ids = []\nfor citizen in v:\n citizen_ids.append(citizen.citizen_id)\n citizen_ids_set.add(citizen.citizen_id)\nif len(citizen_ids) > len(citizen_ids_set):\n raise ValueError('citizen ids in import are not unique')\nreturn v",
"relatives = {citizen.citizen_id: set(citize... | <|body_start_0|>
citizen_ids_set = set()
citizen_ids = []
for citizen in v:
citizen_ids.append(citizen.citizen_id)
citizen_ids_set.add(citizen.citizen_id)
if len(citizen_ids) > len(citizen_ids_set):
raise ValueError('citizen ids in import are not uniqu... | Import model. | Import | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Import:
"""Import model."""
def citizens_ids_unique(cls, v: List[Citizen]) -> List[Citizen]:
"""Validate that every citizen in import has unique id."""
<|body_0|>
def citizens_relatives_mutual(cls, v: List[Citizen]) -> List[Citizen]:
"""Validate that every relati... | stack_v2_sparse_classes_36k_train_029050 | 4,636 | no_license | [
{
"docstring": "Validate that every citizen in import has unique id.",
"name": "citizens_ids_unique",
"signature": "def citizens_ids_unique(cls, v: List[Citizen]) -> List[Citizen]"
},
{
"docstring": "Validate that every relation is mutual.",
"name": "citizens_relatives_mutual",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_013995 | Implement the Python class `Import` described below.
Class description:
Import model.
Method signatures and docstrings:
- def citizens_ids_unique(cls, v: List[Citizen]) -> List[Citizen]: Validate that every citizen in import has unique id.
- def citizens_relatives_mutual(cls, v: List[Citizen]) -> List[Citizen]: Valid... | Implement the Python class `Import` described below.
Class description:
Import model.
Method signatures and docstrings:
- def citizens_ids_unique(cls, v: List[Citizen]) -> List[Citizen]: Validate that every citizen in import has unique id.
- def citizens_relatives_mutual(cls, v: List[Citizen]) -> List[Citizen]: Valid... | 852b7037655f93b1c28dfe1cb638c9a2b558f53b | <|skeleton|>
class Import:
"""Import model."""
def citizens_ids_unique(cls, v: List[Citizen]) -> List[Citizen]:
"""Validate that every citizen in import has unique id."""
<|body_0|>
def citizens_relatives_mutual(cls, v: List[Citizen]) -> List[Citizen]:
"""Validate that every relati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Import:
"""Import model."""
def citizens_ids_unique(cls, v: List[Citizen]) -> List[Citizen]:
"""Validate that every citizen in import has unique id."""
citizen_ids_set = set()
citizen_ids = []
for citizen in v:
citizen_ids.append(citizen.citizen_id)
... | the_stack_v2_python_sparse | ecommerce_analyzer/api/scheme.py | paramoshin/yandex_backend_task | train | 1 |
20b2c14f441ffda5f7b7b72ba27663b23b1599ab | [
"result = []\ncurr = root\nwhile curr:\n if not curr.left:\n result.append(curr.val)\n curr = curr.right\n else:\n node = curr.left\n while node.right and node.right != curr:\n node = node.right\n if not node.right:\n node.right = curr\n curr... | <|body_start_0|>
result = []
curr = root
while curr:
if not curr.left:
result.append(curr.val)
curr = curr.right
else:
node = curr.left
while node.right and node.right != curr:
node = node... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
cur... | stack_v2_sparse_classes_36k_train_029051 | 1,779 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_2",
"signature": "def inorderTraversal_2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_2(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_2(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solution... | 0ca8983505ef5f694b68198742aaf50fc0b80e6b | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
result = []
curr = root
while curr:
if not curr.left:
result.append(curr.val)
curr = curr.right
else:
node = curr.lef... | the_stack_v2_python_sparse | leetcode 051-100/94. Binary Tree Inorder Traversal.py | raxxar1024/code_snippet | train | 0 | |
8833d88228d4cd13b8f1c1357938aaa7dc715d21 | [
"if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():\n qs = Well.objects.all()\nelse:\n qs = Well.objects.all().exclude(well_publication_status='Unpublished')\nreturn qs",
"qs = self.get_queryset()\nlocations = self.filter_queryset(qs)\ncount = locations.count()\nif count > 2000:\n raise P... | <|body_start_0|>
if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():
qs = Well.objects.all()
else:
qs = Well.objects.all().exclude(well_publication_status='Unpublished')
return qs
<|end_body_0|>
<|body_start_1|>
qs = self.get_queryset()
loc... | returns well locations for a given search get: returns a list of wells with locations only | WellLocationListAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WellLocationListAPIView:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
<|body_0|>
def get(self, request):
"""cancels req... | stack_v2_sparse_classes_36k_train_029052 | 24,123 | permissive | [
{
"docstring": "Excludes Unpublished wells for users without edit permissions",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "cancels request if too many wells are found",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | null | Implement the Python class `WellLocationListAPIView` described below.
Class description:
returns well locations for a given search get: returns a list of wells with locations only
Method signatures and docstrings:
- def get_queryset(self): Excludes Unpublished wells for users without edit permissions
- def get(self, ... | Implement the Python class `WellLocationListAPIView` described below.
Class description:
returns well locations for a given search get: returns a list of wells with locations only
Method signatures and docstrings:
- def get_queryset(self): Excludes Unpublished wells for users without edit permissions
- def get(self, ... | 88e801bf58d281aa6b7bf7092a83c1f6e12d5b83 | <|skeleton|>
class WellLocationListAPIView:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
<|body_0|>
def get(self, request):
"""cancels req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WellLocationListAPIView:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():
... | the_stack_v2_python_sparse | app/backend/wells/views.py | anissa-agahchen/gwells | train | 1 |
5b12e5b78c4d631a9b34ab4ce02471abbef2f73a | [
"print('運行has_permission()')\nrole_list = request.user.roles.all()\nfor role in role_list:\n for perm in role.permissions.all():\n print(role, perm)\n if perm.resource == view.basename and perm.method == view.action:\n return True\nif request.user.is_superuser:\n return True\nelse:\n ... | <|body_start_0|>
print('運行has_permission()')
role_list = request.user.roles.all()
for role in role_list:
for perm in role.permissions.all():
print(role, perm)
if perm.resource == view.basename and perm.method == view.action:
return ... | MyPermission | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPermission:
def has_permission(self, request, view):
"""Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentica... | stack_v2_sparse_classes_36k_train_029053 | 3,035 | no_license | [
{
"docstring": "Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentication)後,自動將當前用戶封裝到request中 view: 可通過它調用視圖相關參數 - view.basename: 在url... | 2 | null | Implement the Python class `MyPermission` described below.
Class description:
Implement the MyPermission class.
Method signatures and docstrings:
- def has_permission(self, request, view): Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permi... | Implement the Python class `MyPermission` described below.
Class description:
Implement the MyPermission class.
Method signatures and docstrings:
- def has_permission(self, request, view): Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permi... | f9cb1670fb84b9eb8aaaf7cd5cf9139ab4ef4053 | <|skeleton|>
class MyPermission:
def has_permission(self, request, view):
"""Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentica... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyPermission:
def has_permission(self, request, view):
"""Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentication)後,自動將當前用戶... | the_stack_v2_python_sparse | Web網頁框架/框架(Django Rest Framework)/200725_權限設計/mysite/api/utils/permission.py | narru888/PythonWork-py37- | train | 0 | |
6c6337a8f4d52f85fed454115a905bd85e590a68 | [
"super(VDVAE, self).__init__()\nprint('>>> creating model')\nself.activation = act_fn\nself.variational = variational\nself.output_variance = output_variance\nself.device = device\nself.batch_norm = batch_norm\nself.p_dropout = p_dropout\nself.residual_size = residual_size\nself.gen_disc = gen_disc\nself.encoder = ... | <|body_start_0|>
super(VDVAE, self).__init__()
print('>>> creating model')
self.activation = act_fn
self.variational = variational
self.output_variance = output_variance
self.device = device
self.batch_norm = batch_norm
self.p_dropout = p_dropout
s... | VDVAE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VDVAE:
def __init__(self, input_n=96, act_fn=nn.GELU(), variational=False, output_variance=False, device='cuda', batch_norm=False, p_dropout=0.0, n_zs=[50, 10, 5, 2], residual_size=200, gen_disc=False):
""":param input_n: num of input feature :param hidden_layers: num of hidden feature, ... | stack_v2_sparse_classes_36k_train_029054 | 5,321 | permissive | [
{
"docstring": ":param input_n: num of input feature :param hidden_layers: num of hidden feature, decoder is made symmetric :param n_z: latent variable size :param p_dropout: drop out prob. :param num_stage: number of residual blocks :param node_n: number of nodes in graph",
"name": "__init__",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_018560 | Implement the Python class `VDVAE` described below.
Class description:
Implement the VDVAE class.
Method signatures and docstrings:
- def __init__(self, input_n=96, act_fn=nn.GELU(), variational=False, output_variance=False, device='cuda', batch_norm=False, p_dropout=0.0, n_zs=[50, 10, 5, 2], residual_size=200, gen_d... | Implement the Python class `VDVAE` described below.
Class description:
Implement the VDVAE class.
Method signatures and docstrings:
- def __init__(self, input_n=96, act_fn=nn.GELU(), variational=False, output_variance=False, device='cuda', batch_norm=False, p_dropout=0.0, n_zs=[50, 10, 5, 2], residual_size=200, gen_d... | 873caa496d14c9a9723581cdf1464f44db4cf358 | <|skeleton|>
class VDVAE:
def __init__(self, input_n=96, act_fn=nn.GELU(), variational=False, output_variance=False, device='cuda', batch_norm=False, p_dropout=0.0, n_zs=[50, 10, 5, 2], residual_size=200, gen_disc=False):
""":param input_n: num of input feature :param hidden_layers: num of hidden feature, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VDVAE:
def __init__(self, input_n=96, act_fn=nn.GELU(), variational=False, output_variance=False, device='cuda', batch_norm=False, p_dropout=0.0, n_zs=[50, 10, 5, 2], residual_size=200, gen_disc=False):
""":param input_n: num of input feature :param hidden_layers: num of hidden feature, decoder is mad... | the_stack_v2_python_sparse | models/VDVAE.py | bouracha/Gen_Motion | train | 2 | |
412358d842f92b79c81e9d576d65ffb43d0a40be | [
"Inferencia.__init__(self)\nself.clases_candidatas = clases_candidatas\nself.atributos_usados = atributos_usados",
"print('*** Ejecución de la inferencia Especificar')\nprint()\nif len(self.clases_candidatas) > 0:\n clase = self.clases_candidatas[0]\n for nombre, atributo in list(clase.atributos.items()):\n... | <|body_start_0|>
Inferencia.__init__(self)
self.clases_candidatas = clases_candidatas
self.atributos_usados = atributos_usados
<|end_body_0|>
<|body_start_1|>
print('*** Ejecución de la inferencia Especificar')
print()
if len(self.clases_candidatas) > 0:
clas... | Dado un conjunto de clases candidatas no vacío especifica un atributo para extraer su valor en otra inferencia. | Especificar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Especificar:
"""Dado un conjunto de clases candidatas no vacío especifica un atributo para extraer su valor en otra inferencia."""
def __init__(self, clases_candidatas, atributos_usados):
"""@param clases_candidatas: Lista de clases candidatas @param atributos_usados: Lista de atribu... | stack_v2_sparse_classes_36k_train_029055 | 1,261 | no_license | [
{
"docstring": "@param clases_candidatas: Lista de clases candidatas @param atributos_usados: Lista de atributos ya seleccionados",
"name": "__init__",
"signature": "def __init__(self, clases_candidatas, atributos_usados)"
},
{
"docstring": "Ejecución del método de la inferencia @return: Devuelv... | 2 | stack_v2_sparse_classes_30k_train_002204 | Implement the Python class `Especificar` described below.
Class description:
Dado un conjunto de clases candidatas no vacío especifica un atributo para extraer su valor en otra inferencia.
Method signatures and docstrings:
- def __init__(self, clases_candidatas, atributos_usados): @param clases_candidatas: Lista de c... | Implement the Python class `Especificar` described below.
Class description:
Dado un conjunto de clases candidatas no vacío especifica un atributo para extraer su valor en otra inferencia.
Method signatures and docstrings:
- def __init__(self, clases_candidatas, atributos_usados): @param clases_candidatas: Lista de c... | d6b3620c932f4c3bfb49b6c20b6796b7a337f411 | <|skeleton|>
class Especificar:
"""Dado un conjunto de clases candidatas no vacío especifica un atributo para extraer su valor en otra inferencia."""
def __init__(self, clases_candidatas, atributos_usados):
"""@param clases_candidatas: Lista de clases candidatas @param atributos_usados: Lista de atribu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Especificar:
"""Dado un conjunto de clases candidatas no vacío especifica un atributo para extraer su valor en otra inferencia."""
def __init__(self, clases_candidatas, atributos_usados):
"""@param clases_candidatas: Lista de clases candidatas @param atributos_usados: Lista de atributos ya selecc... | the_stack_v2_python_sparse | classification/inference/especificar.py | sgomez/master-ia | train | 0 |
938ce690330520ec7c5069c205f9e6ed3a2f9aac | [
"super(SparqlBasedDeductionEngineExtended, self).__init__()\nself.relation = relation\nself.query_executer = kg_query_interface\nself.quality = quality\nself.quality_aggregation = quality_aggregation\nself.labels_indexer = Indexer(store=kg_query_interface.type, endpoint=kg_query_interface.endpoint, graph=kg_query_i... | <|body_start_0|>
super(SparqlBasedDeductionEngineExtended, self).__init__()
self.relation = relation
self.query_executer = kg_query_interface
self.quality = quality
self.quality_aggregation = quality_aggregation
self.labels_indexer = Indexer(store=kg_query_interface.type,... | Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions | SparqlBasedDeductionEngineExtended | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparqlBasedDeductionEngineExtended:
"""Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions"""
def __init__(self, kg_query_interface: KGQueryInterfaceExtended, relation=DEFUALT_AUX_RELATION, qua... | stack_v2_sparse_classes_36k_train_029056 | 10,782 | permissive | [
{
"docstring": ":param kg_query_interface: interface for the KG. :param relation: the relation used in the predicted triple (optional) :param quality: objective quality measure for ranking the predictions (optional) by default the exclusive coverage of the rules is used :param quality_aggregation: the methd use... | 5 | stack_v2_sparse_classes_30k_train_008957 | Implement the Python class `SparqlBasedDeductionEngineExtended` described below.
Class description:
Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions
Method signatures and docstrings:
- def __init__(self, kg_query_int... | Implement the Python class `SparqlBasedDeductionEngineExtended` described below.
Class description:
Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions
Method signatures and docstrings:
- def __init__(self, kg_query_int... | 09e943a23207381de3c3a9e6f70015882b8ec4af | <|skeleton|>
class SparqlBasedDeductionEngineExtended:
"""Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions"""
def __init__(self, kg_query_interface: KGQueryInterfaceExtended, relation=DEFUALT_AUX_RELATION, qua... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparqlBasedDeductionEngineExtended:
"""Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions"""
def __init__(self, kg_query_interface: KGQueryInterfaceExtended, relation=DEFUALT_AUX_RELATION, quality='x_cover... | the_stack_v2_python_sparse | excut/feedback/rulebased_deduction/deduction_engine_extended.py | mhmgad/ExCut | train | 9 |
e733a5a81b038b0214d9a2aedc741ebf0c8aacd2 | [
"super(MembreForm, self).__init__(*args, **kwargs)\nself.fields['instruments'].label = 'Instruments (choisissez-en un ou plusieurs)'\nself.fields['chant'].label = 'Chant (cochez la case si vous chantez)'",
"username = self.cleaned_data.get('username')\nemail = self.cleaned_data.get('email')\nif User.objects.filte... | <|body_start_0|>
super(MembreForm, self).__init__(*args, **kwargs)
self.fields['instruments'].label = 'Instruments (choisissez-en un ou plusieurs)'
self.fields['chant'].label = 'Chant (cochez la case si vous chantez)'
<|end_body_0|>
<|body_start_1|>
username = self.cleaned_data.get('use... | Classe qui permet la création d'un formulaire pour renseigner les champs d'un nouveau membre | MembreForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MembreForm:
"""Classe qui permet la création d'un formulaire pour renseigner les champs d'un nouveau membre"""
def __init__(self, *args, **kwargs):
"""Constructeur"""
<|body_0|>
def clean(self):
"""Surcharge de la méthode clean :return: les données nettoyées :rty... | stack_v2_sparse_classes_36k_train_029057 | 5,786 | no_license | [
{
"docstring": "Constructeur",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Surcharge de la méthode clean :return: les données nettoyées :rtype: dict",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011037 | Implement the Python class `MembreForm` described below.
Class description:
Classe qui permet la création d'un formulaire pour renseigner les champs d'un nouveau membre
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructeur
- def clean(self): Surcharge de la méthode clean :return: les d... | Implement the Python class `MembreForm` described below.
Class description:
Classe qui permet la création d'un formulaire pour renseigner les champs d'un nouveau membre
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructeur
- def clean(self): Surcharge de la méthode clean :return: les d... | 9cae63a4bd487d58931d800b0208426862a2191d | <|skeleton|>
class MembreForm:
"""Classe qui permet la création d'un formulaire pour renseigner les champs d'un nouveau membre"""
def __init__(self, *args, **kwargs):
"""Constructeur"""
<|body_0|>
def clean(self):
"""Surcharge de la méthode clean :return: les données nettoyées :rty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MembreForm:
"""Classe qui permet la création d'un formulaire pour renseigner les champs d'un nouveau membre"""
def __init__(self, *args, **kwargs):
"""Constructeur"""
super(MembreForm, self).__init__(*args, **kwargs)
self.fields['instruments'].label = 'Instruments (choisissez-en u... | the_stack_v2_python_sparse | lyre_d_alliez/lyre_d_alliez/forms.py | JL31/Site_Lyre_d_Alliez | train | 0 |
7e713d2efc01559c5da5d1452c604bacdbb1655b | [
"super(rDMinBatch, self).__init__()\nself.d = d\nself.rnn = RecurrentDiscriminator(num_nodes, d, num_layers=num_layers, bidirectional=bidirectional)\nself.featmap_dim = num_nodes // 2\nT_ten_init = torch.randn(self.featmap_dim, d) * 0.1\nself.T_tensor = nn.Parameter(T_ten_init, requires_grad=True)\nself.fc = nn.Lin... | <|body_start_0|>
super(rDMinBatch, self).__init__()
self.d = d
self.rnn = RecurrentDiscriminator(num_nodes, d, num_layers=num_layers, bidirectional=bidirectional)
self.featmap_dim = num_nodes // 2
T_ten_init = torch.randn(self.featmap_dim, d) * 0.1
self.T_tensor = nn.Para... | rDMinBatch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class rDMinBatch:
def __init__(self, num_nodes, d, num_layers=3, bidirectional=True):
"""Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch."""
<|body_0|>
def forward(self, x, matching=False):
"""Architecture is si... | stack_v2_sparse_classes_36k_train_029058 | 1,741 | no_license | [
{
"docstring": "Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch.",
"name": "__init__",
"signature": "def __init__(self, num_nodes, d, num_layers=3, bidirectional=True)"
},
{
"docstring": "Architecture is similar to DCGANs Add minibatc... | 2 | stack_v2_sparse_classes_30k_train_019394 | Implement the Python class `rDMinBatch` described below.
Class description:
Implement the rDMinBatch class.
Method signatures and docstrings:
- def __init__(self, num_nodes, d, num_layers=3, bidirectional=True): Minibatch discrimination: learn a tensor to encode side information from other examples in the same miniba... | Implement the Python class `rDMinBatch` described below.
Class description:
Implement the rDMinBatch class.
Method signatures and docstrings:
- def __init__(self, num_nodes, d, num_layers=3, bidirectional=True): Minibatch discrimination: learn a tensor to encode side information from other examples in the same miniba... | 022d836d89cd61200c81fa81b044148326f9aa72 | <|skeleton|>
class rDMinBatch:
def __init__(self, num_nodes, d, num_layers=3, bidirectional=True):
"""Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch."""
<|body_0|>
def forward(self, x, matching=False):
"""Architecture is si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class rDMinBatch:
def __init__(self, num_nodes, d, num_layers=3, bidirectional=True):
"""Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch."""
super(rDMinBatch, self).__init__()
self.d = d
self.rnn = RecurrentDiscriminator(n... | the_stack_v2_python_sparse | discriminators/rD_min_batch.py | DanielLongo/eegML | train | 13 | |
b4643d057c94727aab206871daa05d033c2da29a | [
"self.vectors = vec2d\nself.list_index = 0\nself.element_index = 0",
"if self.hasNext():\n value = self.vectors[self.list_index][self.element_index]\n self.element_index += 1\n return value",
"while self.list_index < len(self.vectors):\n if self.element_index < len(self.vectors[self.list_index]):\n ... | <|body_start_0|>
self.vectors = vec2d
self.list_index = 0
self.element_index = 0
<|end_body_0|>
<|body_start_1|>
if self.hasNext():
value = self.vectors[self.list_index][self.element_index]
self.element_index += 1
return value
<|end_body_1|>
<|body_s... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_029059 | 1,316 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_003104 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | 086b7c9b3651a0e70c5794f6c264eb975cc90363 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vectors = vec2d
self.list_index = 0
self.element_index = 0
def next(self):
""":rtype: int"""
if self.hasNext():
value = self.vector... | the_stack_v2_python_sparse | flatten_2d_vector.py | chunweiliu/leetcode2 | train | 4 | |
63674f287632baa99b4736c3f1e17aaff0840a6a | [
"seller = Shop_Seller(id=shopId).get()\nif seller:\n itemList = Shop_Seller(id=shopId).get().itemList\n itemList = [marshal(item, output_shopItem) for item in itemList]\n return Response(data=itemList)\nelse:\n return Response(code=HttpStatus.HTTP_404_NOT_FOUND, message='无符合条件的商家')",
"if not current_u... | <|body_start_0|>
seller = Shop_Seller(id=shopId).get()
if seller:
itemList = Shop_Seller(id=shopId).get().itemList
itemList = [marshal(item, output_shopItem) for item in itemList]
return Response(data=itemList)
else:
return Response(code=HttpStatus... | Menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
def get(self, shopId):
"""获取商家商品列表 :return:"""
<|body_0|>
def post(self, shopId):
"""添加商品 :param shopId: :return:"""
<|body_1|>
def put(self, shopId):
"""修改商品信息,可进行部分字段更新 :param shopId: :return:"""
<|body_2|>
def delete(self, s... | stack_v2_sparse_classes_36k_train_029060 | 14,722 | no_license | [
{
"docstring": "获取商家商品列表 :return:",
"name": "get",
"signature": "def get(self, shopId)"
},
{
"docstring": "添加商品 :param shopId: :return:",
"name": "post",
"signature": "def post(self, shopId)"
},
{
"docstring": "修改商品信息,可进行部分字段更新 :param shopId: :return:",
"name": "put",
"si... | 4 | stack_v2_sparse_classes_30k_train_018946 | Implement the Python class `Menu` described below.
Class description:
Implement the Menu class.
Method signatures and docstrings:
- def get(self, shopId): 获取商家商品列表 :return:
- def post(self, shopId): 添加商品 :param shopId: :return:
- def put(self, shopId): 修改商品信息,可进行部分字段更新 :param shopId: :return:
- def delete(self, shopI... | Implement the Python class `Menu` described below.
Class description:
Implement the Menu class.
Method signatures and docstrings:
- def get(self, shopId): 获取商家商品列表 :return:
- def post(self, shopId): 添加商品 :param shopId: :return:
- def put(self, shopId): 修改商品信息,可进行部分字段更新 :param shopId: :return:
- def delete(self, shopI... | 34a2bf4a51cc40a22dd43cb5eb88af7c2f2c5120 | <|skeleton|>
class Menu:
def get(self, shopId):
"""获取商家商品列表 :return:"""
<|body_0|>
def post(self, shopId):
"""添加商品 :param shopId: :return:"""
<|body_1|>
def put(self, shopId):
"""修改商品信息,可进行部分字段更新 :param shopId: :return:"""
<|body_2|>
def delete(self, s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
def get(self, shopId):
"""获取商家商品列表 :return:"""
seller = Shop_Seller(id=shopId).get()
if seller:
itemList = Shop_Seller(id=shopId).get().itemList
itemList = [marshal(item, output_shopItem) for item in itemList]
return Response(data=itemList)
... | the_stack_v2_python_sparse | App/Shop/Controller/ShopResource.py | Vulcanhy/api.grooo-master | train | 0 | |
099d5e40e24e18dd502a7d9fba52e88352f999cf | [
"flag = True\ntemp = i\nwhile i > 0:\n num = i % 10\n i = i // 10\n if num == 0 or temp % num != 0:\n flag = False\nreturn flag",
"dividing_num_list = []\nfor i in range(left, right + 1):\n flag = self.judge_dividing_number(i)\n if flag:\n dividing_num_list.append(i)\nreturn dividing_... | <|body_start_0|>
flag = True
temp = i
while i > 0:
num = i % 10
i = i // 10
if num == 0 or temp % num != 0:
flag = False
return flag
<|end_body_0|>
<|body_start_1|>
dividing_num_list = []
for i in range(left, right + 1)... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def judge_dividing_number(self, i: int) -> bool:
"""判断是不是自除数 Args: i: 输入数 Returns: 布尔值"""
<|body_0|>
def self_dividing_numbers(self, left: int, right: int) -> List[int]:
"""找出自除数 Args: left: 左边 right: 右边 Returns: list链表"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_029061 | 2,205 | permissive | [
{
"docstring": "判断是不是自除数 Args: i: 输入数 Returns: 布尔值",
"name": "judge_dividing_number",
"signature": "def judge_dividing_number(self, i: int) -> bool"
},
{
"docstring": "找出自除数 Args: left: 左边 right: 右边 Returns: list链表",
"name": "self_dividing_numbers",
"signature": "def self_dividing_number... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def judge_dividing_number(self, i: int) -> bool: 判断是不是自除数 Args: i: 输入数 Returns: 布尔值
- def self_dividing_numbers(self, left: int, right: int) -> List[int]: 找出自除数 Args: left: 左边 ri... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def judge_dividing_number(self, i: int) -> bool: 判断是不是自除数 Args: i: 输入数 Returns: 布尔值
- def self_dividing_numbers(self, left: int, right: int) -> List[int]: 找出自除数 Args: left: 左边 ri... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def judge_dividing_number(self, i: int) -> bool:
"""判断是不是自除数 Args: i: 输入数 Returns: 布尔值"""
<|body_0|>
def self_dividing_numbers(self, left: int, right: int) -> List[int]:
"""找出自除数 Args: left: 左边 right: 右边 Returns: list链表"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def judge_dividing_number(self, i: int) -> bool:
"""判断是不是自除数 Args: i: 输入数 Returns: 布尔值"""
flag = True
temp = i
while i > 0:
num = i % 10
i = i // 10
if num == 0 or temp % num != 0:
flag = False
return flag
... | the_stack_v2_python_sparse | src/leetcodepython/array/self_diving_number_728.py | zhangyu345293721/leetcode | train | 101 | |
e4428ab29bea1994cb3e7a3c82f1321f86b55519 | [
"codep_querry = '\\n INSERT INTO code_problems(title, language, content)\\n VALUES(%s, %s, %s)\\n RETURNING codeId, title, language, content\\n '\ncodep_data = (title, language, content)\nresponse = Quora_Db.add_to_db(codep_querry, codep_data)\nreturn response",
"codep_title_querry = '... | <|body_start_0|>
codep_querry = '\n INSERT INTO code_problems(title, language, content)\n VALUES(%s, %s, %s)\n RETURNING codeId, title, language, content\n '
codep_data = (title, language, content)
response = Quora_Db.add_to_db(codep_querry, codep_data)
return... | This class creates a code problems operations | Code_problemsModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Code_problemsModel:
"""This class creates a code problems operations"""
def create_codep(self, title, language, content):
"""Method to create a coding problem"""
<|body_0|>
def get_codep_by_title(self, title):
"""Get coding problem by its title"""
<|body_... | stack_v2_sparse_classes_36k_train_029062 | 979 | no_license | [
{
"docstring": "Method to create a coding problem",
"name": "create_codep",
"signature": "def create_codep(self, title, language, content)"
},
{
"docstring": "Get coding problem by its title",
"name": "get_codep_by_title",
"signature": "def get_codep_by_title(self, title)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000623 | Implement the Python class `Code_problemsModel` described below.
Class description:
This class creates a code problems operations
Method signatures and docstrings:
- def create_codep(self, title, language, content): Method to create a coding problem
- def get_codep_by_title(self, title): Get coding problem by its tit... | Implement the Python class `Code_problemsModel` described below.
Class description:
This class creates a code problems operations
Method signatures and docstrings:
- def create_codep(self, title, language, content): Method to create a coding problem
- def get_codep_by_title(self, title): Get coding problem by its tit... | 344722cc48d859e956f06b642af6ffbd7403e60d | <|skeleton|>
class Code_problemsModel:
"""This class creates a code problems operations"""
def create_codep(self, title, language, content):
"""Method to create a coding problem"""
<|body_0|>
def get_codep_by_title(self, title):
"""Get coding problem by its title"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Code_problemsModel:
"""This class creates a code problems operations"""
def create_codep(self, title, language, content):
"""Method to create a coding problem"""
codep_querry = '\n INSERT INTO code_problems(title, language, content)\n VALUES(%s, %s, %s)\n RETURNING co... | the_stack_v2_python_sparse | app/auth/v1/models/create_problem_models.py | RoyRasugu/flask-api | train | 0 |
27ef62367eb12eaa8044d3bd766823a9a74f9ff5 | [
"s = '1'\nfor _ in range(n - 1):\n seq = ''\n i = 0\n j = 1\n for i in range(len(s)):\n if i + 1 < len(s) and s[i] == s[i + 1]:\n j += 1\n else:\n seq += str(j) + str(s[i])\n j = 1\n s = seq\nreturn s",
"s = '1'\nfor _ in range(n - 1):\n s = re.... | <|body_start_0|>
s = '1'
for _ in range(n - 1):
seq = ''
i = 0
j = 1
for i in range(len(s)):
if i + 1 < len(s) and s[i] == s[i + 1]:
j += 1
else:
seq += str(j) + str(s[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def countAndSay2(self, n):
""":type n: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = '1'
for _ in range(n - 1):
seq = ''
... | stack_v2_sparse_classes_36k_train_029063 | 725 | no_license | [
{
"docstring": ":type n: int :rtype: str",
"name": "countAndSay",
"signature": "def countAndSay(self, n)"
},
{
"docstring": ":type n: int :rtype: str",
"name": "countAndSay2",
"signature": "def countAndSay2(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay(self, n): :type n: int :rtype: str
- def countAndSay2(self, n): :type n: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay(self, n): :type n: int :rtype: str
- def countAndSay2(self, n): :type n: int :rtype: str
<|skeleton|>
class Solution:
def countAndSay(self, n):
""":... | 863b89be674a82eef60c0f33d726ac08d43f2e01 | <|skeleton|>
class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def countAndSay2(self, n):
""":type n: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
s = '1'
for _ in range(n - 1):
seq = ''
i = 0
j = 1
for i in range(len(s)):
if i + 1 < len(s) and s[i] == s[i + 1]:
j += 1
... | the_stack_v2_python_sparse | q38_Count_and_Say.py | Ryuya1995/leetcode | train | 0 | |
d01e4f7e3b3ee39208237293aaf6869aefbce9e5 | [
"label = 'a'\nbytes = [ord('a') + 128]\nself.assertEqual(make_dafsa.encode_label(label), bytes)",
"label = 'ab'\nbytes = [ord('b') + 128, ord('a')]\nself.assertEqual(make_dafsa.encode_label(label), bytes)"
] | <|body_start_0|>
label = 'a'
bytes = [ord('a') + 128]
self.assertEqual(make_dafsa.encode_label(label), bytes)
<|end_body_0|>
<|body_start_1|>
label = 'ab'
bytes = [ord('b') + 128, ord('a')]
self.assertEqual(make_dafsa.encode_label(label), bytes)
<|end_body_1|>
| EncodeLabelTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncodeLabelTest:
def testChar(self):
"""Tests to encode a single character label."""
<|body_0|>
def testChars(self):
"""Tests to encode a multi character label."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
label = 'a'
bytes = [ord('a') + ... | stack_v2_sparse_classes_36k_train_029064 | 20,781 | permissive | [
{
"docstring": "Tests to encode a single character label.",
"name": "testChar",
"signature": "def testChar(self)"
},
{
"docstring": "Tests to encode a multi character label.",
"name": "testChars",
"signature": "def testChars(self)"
}
] | 2 | null | Implement the Python class `EncodeLabelTest` described below.
Class description:
Implement the EncodeLabelTest class.
Method signatures and docstrings:
- def testChar(self): Tests to encode a single character label.
- def testChars(self): Tests to encode a multi character label. | Implement the Python class `EncodeLabelTest` described below.
Class description:
Implement the EncodeLabelTest class.
Method signatures and docstrings:
- def testChar(self): Tests to encode a single character label.
- def testChars(self): Tests to encode a multi character label.
<|skeleton|>
class EncodeLabelTest:
... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class EncodeLabelTest:
def testChar(self):
"""Tests to encode a single character label."""
<|body_0|>
def testChars(self):
"""Tests to encode a multi character label."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncodeLabelTest:
def testChar(self):
"""Tests to encode a single character label."""
label = 'a'
bytes = [ord('a') + 128]
self.assertEqual(make_dafsa.encode_label(label), bytes)
def testChars(self):
"""Tests to encode a multi character label."""
label = 'ab... | the_stack_v2_python_sparse | tools/media_engagement_preload/make_dafsa_unittest.py | chromium/chromium | train | 17,408 | |
9e9631d2d4c3a58eedf84773a91631fadcbb55e9 | [
"definitions = self.definitions\nrendered = template\ntokens = self._find_tokens(template)\nfor token in tokens:\n if token == self.INDEX_TAG:\n value = str(index)\n elif token in search_data or token == self.TERM_TAG:\n terms = self._get_relevant_search_terms(token, topic, search_data)\n ... | <|body_start_0|>
definitions = self.definitions
rendered = template
tokens = self._find_tokens(template)
for token in tokens:
if token == self.INDEX_TAG:
value = str(index)
elif token in search_data or token == self.TERM_TAG:
terms ... | BaseURLConstructor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseURLConstructor:
def _construct_clause(self, template, search_data, topic=None, term=None, index=1):
"""Construct clause Construct URL clause by recursing depth-first to replace template tokens via search topic, term, and/or index. I/O: template: string with 1+ tokens specified via {}... | stack_v2_sparse_classes_36k_train_029065 | 8,799 | no_license | [
{
"docstring": "Construct clause Construct URL clause by recursing depth-first to replace template tokens via search topic, term, and/or index. I/O: template: string with 1+ tokens specified via {} search_data: encoded search data, an ordered dict topic=None: search data key to specify any terms term=None: sear... | 3 | stack_v2_sparse_classes_30k_train_020465 | Implement the Python class `BaseURLConstructor` described below.
Class description:
Implement the BaseURLConstructor class.
Method signatures and docstrings:
- def _construct_clause(self, template, search_data, topic=None, term=None, index=1): Construct clause Construct URL clause by recursing depth-first to replace ... | Implement the Python class `BaseURLConstructor` described below.
Class description:
Implement the BaseURLConstructor class.
Method signatures and docstrings:
- def _construct_clause(self, template, search_data, topic=None, term=None, index=1): Construct clause Construct URL clause by recursing depth-first to replace ... | 76394f5859c6e5aefd99be0dd3babbde82038387 | <|skeleton|>
class BaseURLConstructor:
def _construct_clause(self, template, search_data, topic=None, term=None, index=1):
"""Construct clause Construct URL clause by recursing depth-first to replace template tokens via search topic, term, and/or index. I/O: template: string with 1+ tokens specified via {}... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseURLConstructor:
def _construct_clause(self, template, search_data, topic=None, term=None, index=1):
"""Construct clause Construct URL clause by recursing depth-first to replace template tokens via search topic, term, and/or index. I/O: template: string with 1+ tokens specified via {} search_data: ... | the_stack_v2_python_sparse | contextualize/extraction/url.py | IntertwineIO/contextualize | train | 2 | |
03ca7dc00f2281c3515f8f3289fbd68faa1f928b | [
"parser.add_argument('WORKFLOW_ID', help='The ID of the Workflow.')\nparser.add_argument('--params', metavar='KEY=VALUE', type=arg_parsers.ArgDict(), help='Params to run Workflow with.')\nrun_flags.AddsRegionResourceArg(parser)",
"client = client_util.GetClientInstance()\nmessages = client_util.GetMessagesModule(... | <|body_start_0|>
parser.add_argument('WORKFLOW_ID', help='The ID of the Workflow.')
parser.add_argument('--params', metavar='KEY=VALUE', type=arg_parsers.ArgDict(), help='Params to run Workflow with.')
run_flags.AddsRegionResourceArg(parser)
<|end_body_0|>
<|body_start_1|>
client = clie... | Run a Workflow. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Run a Workflow."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|body_0|>
def Run(self, args):
... | stack_v2_sparse_classes_36k_train_029066 | 4,471 | permissive | [
{
"docstring": "Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the... | 2 | null | Implement the Python class `Create` described below.
Class description:
Run a Workflow.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser... | Implement the Python class `Create` described below.
Class description:
Run a Workflow.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Create:
"""Run a Workflow."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|body_0|>
def Run(self, args):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Run a Workflow."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
parser.add_argument('WORKFLOW_ID', help='The ID of the Wo... | the_stack_v2_python_sparse | lib/surface/builds/workflows/run.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
7a5df11757a99665bdbc443d38235ec4a7846dd1 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('yufeng72', 'yufeng72')\nurl = 'http://datamechanics.io/data/yufeng72/Bus_Stops.csv'\nresponse = urllib.request.urlopen(url)\nr = csv.reader(io.StringIO(response.read().decode('utf-8')), delimiter=',')\nr... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yufeng72', 'yufeng72')
url = 'http://datamechanics.io/data/yufeng72/Bus_Stops.csv'
response = urllib.request.urlopen(url)
r = csv.reader(i... | RetrieveBusStops | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetrieveBusStops:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyth... | stack_v2_sparse_classes_36k_train_029067 | 4,088 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `RetrieveBusStops` described below.
Class description:
Implement the RetrieveBusStops class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=N... | Implement the Python class `RetrieveBusStops` described below.
Class description:
Implement the RetrieveBusStops class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=N... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class RetrieveBusStops:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetrieveBusStops:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yufeng72', 'yufeng72')
url... | the_stack_v2_python_sparse | yufeng72/RetrieveBusStops.py | maximega/course-2019-spr-proj | train | 2 | |
648780a0b95f3e9c02c676e264065ee9d40bacb6 | [
"self.X = X\nassert self.X.ndim == 2\nself.k = k\nself.X_shape = self.X.shape\nself.X_samples = self.X_shape[0]\nself.X_features = self.X_shape[1]\nself.centX = self._centralize()\nself.convM = self._cov()\nself.convF_value, self.convF_vector = self._extract()\nself.Z_features = self._reduced()",
"X_mean = np.mea... | <|body_start_0|>
self.X = X
assert self.X.ndim == 2
self.k = k
self.X_shape = self.X.shape
self.X_samples = self.X_shape[0]
self.X_features = self.X_shape[1]
self.centX = self._centralize()
self.convM = self._cov()
self.convF_value, self.convF_vect... | PCA算法实现 | PCA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCA:
"""PCA算法实现"""
def __init__(self, X, k):
"""初始化PCA类,并执行1.中心化,2.构造协方差矩阵,3.提取特征值与特征向量,4,降维 :param X: 输入的特征矩阵,行表示样本,列表示特征 :type X: np.ndarray :param k: 降维的目标维度 :type k: int"""
<|body_0|>
def _centralize(self):
"""中心化 :return: 中心化的矩阵,即原始矩阵没个元素按列减去该列的均值 :rtype: np... | stack_v2_sparse_classes_36k_train_029068 | 2,902 | no_license | [
{
"docstring": "初始化PCA类,并执行1.中心化,2.构造协方差矩阵,3.提取特征值与特征向量,4,降维 :param X: 输入的特征矩阵,行表示样本,列表示特征 :type X: np.ndarray :param k: 降维的目标维度 :type k: int",
"name": "__init__",
"signature": "def __init__(self, X, k)"
},
{
"docstring": "中心化 :return: 中心化的矩阵,即原始矩阵没个元素按列减去该列的均值 :rtype: np.ndarray",
"name": "... | 5 | null | Implement the Python class `PCA` described below.
Class description:
PCA算法实现
Method signatures and docstrings:
- def __init__(self, X, k): 初始化PCA类,并执行1.中心化,2.构造协方差矩阵,3.提取特征值与特征向量,4,降维 :param X: 输入的特征矩阵,行表示样本,列表示特征 :type X: np.ndarray :param k: 降维的目标维度 :type k: int
- def _centralize(self): 中心化 :return: 中心化的矩阵,即原始矩阵没个元... | Implement the Python class `PCA` described below.
Class description:
PCA算法实现
Method signatures and docstrings:
- def __init__(self, X, k): 初始化PCA类,并执行1.中心化,2.构造协方差矩阵,3.提取特征值与特征向量,4,降维 :param X: 输入的特征矩阵,行表示样本,列表示特征 :type X: np.ndarray :param k: 降维的目标维度 :type k: int
- def _centralize(self): 中心化 :return: 中心化的矩阵,即原始矩阵没个元... | f2a1b2f8b6b292815d92a294d49954616d3624d5 | <|skeleton|>
class PCA:
"""PCA算法实现"""
def __init__(self, X, k):
"""初始化PCA类,并执行1.中心化,2.构造协方差矩阵,3.提取特征值与特征向量,4,降维 :param X: 输入的特征矩阵,行表示样本,列表示特征 :type X: np.ndarray :param k: 降维的目标维度 :type k: int"""
<|body_0|>
def _centralize(self):
"""中心化 :return: 中心化的矩阵,即原始矩阵没个元素按列减去该列的均值 :rtype: np... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCA:
"""PCA算法实现"""
def __init__(self, X, k):
"""初始化PCA类,并执行1.中心化,2.构造协方差矩阵,3.提取特征值与特征向量,4,降维 :param X: 输入的特征矩阵,行表示样本,列表示特征 :type X: np.ndarray :param k: 降维的目标维度 :type k: int"""
self.X = X
assert self.X.ndim == 2
self.k = k
self.X_shape = self.X.shape
self.X... | the_stack_v2_python_sparse | 25-刘杰-北京/第三周/pca.py | Yang-chen205/badou-Turing | train | 1 |
44ab080409a0baddac6e71cc84accb4bf5592c7f | [
"def preorder(root):\n return [root.val] + preorder(root.left) + preorder(root.right) if root else ['None']\nreturn ','.join(map(str, preorder(root)))",
"data = data.split(',')\n\ndef constructor(data):\n val = int(data.pop(0))\n if val == 'None':\n return None\n root = TreeNode(val)\n root.... | <|body_start_0|>
def preorder(root):
return [root.val] + preorder(root.left) + preorder(root.right) if root else ['None']
return ','.join(map(str, preorder(root)))
<|end_body_0|>
<|body_start_1|>
data = data.split(',')
def constructor(data):
val = int(data.pop(0... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_029069 | 4,106 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_018793 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 56047a5058c6a20b356ab20e52eacb425ad45762 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def preorder(root):
return [root.val] + preorder(root.left) + preorder(root.right) if root else ['None']
return ','.join(map(str, preorder(root)))
def deserializ... | the_stack_v2_python_sparse | Python/BinaryTree/297. Serialize and Deserialize Binary Tree.py | Leahxuliu/Data-Structure-And-Algorithm | train | 2 | |
bbcf95df1df4d99e8d443e752c948d01e5cbf50a | [
"self._request = request\nif isinstance(request.body, str):\n self._body = PresignedURLRequestBody(**json.loads(str(request.body)))\nelse:\n self._body = PresignedURLRequestBody(**request.body)",
"if self._body.dependent_artifacts is None:\n return False\nif len(self._body.dependent_artifacts) == 0:\n ... | <|body_start_0|>
self._request = request
if isinstance(request.body, str):
self._body = PresignedURLRequestBody(**json.loads(str(request.body)))
else:
self._body = PresignedURLRequestBody(**request.body)
<|end_body_0|>
<|body_start_1|>
if self._body.dependent_art... | Methods to handle PresignedURLRequest Validation | PresignedURLRequestValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresignedURLRequestValidator:
"""Methods to handle PresignedURLRequest Validation"""
def __init__(self, request: PresignedURLRequest):
"""init"""
<|body_0|>
def is_self_dependent(self) -> bool:
"""does dependent_artifacts array include this artifact arn?"""
... | stack_v2_sparse_classes_36k_train_029070 | 1,788 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, request: PresignedURLRequest)"
},
{
"docstring": "does dependent_artifacts array include this artifact arn?",
"name": "is_self_dependent",
"signature": "def is_self_dependent(self) -> bool"
},
{
"docstrin... | 3 | null | Implement the Python class `PresignedURLRequestValidator` described below.
Class description:
Methods to handle PresignedURLRequest Validation
Method signatures and docstrings:
- def __init__(self, request: PresignedURLRequest): init
- def is_self_dependent(self) -> bool: does dependent_artifacts array include this a... | Implement the Python class `PresignedURLRequestValidator` described below.
Class description:
Methods to handle PresignedURLRequest Validation
Method signatures and docstrings:
- def __init__(self, request: PresignedURLRequest): init
- def is_self_dependent(self) -> bool: does dependent_artifacts array include this a... | 2c992d0c8f5acd3a3ce6d2365f1bfca09bdc1e33 | <|skeleton|>
class PresignedURLRequestValidator:
"""Methods to handle PresignedURLRequest Validation"""
def __init__(self, request: PresignedURLRequest):
"""init"""
<|body_0|>
def is_self_dependent(self) -> bool:
"""does dependent_artifacts array include this artifact arn?"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PresignedURLRequestValidator:
"""Methods to handle PresignedURLRequest Validation"""
def __init__(self, request: PresignedURLRequest):
"""init"""
self._request = request
if isinstance(request.body, str):
self._body = PresignedURLRequestBody(**json.loads(str(request.bod... | the_stack_v2_python_sparse | ec-artifact-registry/temp/artifact_registry/presigned_url_validator.py | BrutalSimplicity/python-serverless | train | 0 |
2bb148bb1f649c687f528846d6d21a2766ac8a84 | [
"engine = models.LoaderEngine.objects.get(mnemo='asco', active=True)\nhandler = leh.ASCOUploadHandler(engine, **{k: v for k, v in engine.config.__dict__.iteritems()})\nhandler.process()",
"engine = models.LoaderEngine.objects.get(mnemo='hopkinsmedicine', active=True)\nhandler = leh.HopkinsMedicineUploadHandler(en... | <|body_start_0|>
engine = models.LoaderEngine.objects.get(mnemo='asco', active=True)
handler = leh.ASCOUploadHandler(engine, **{k: v for k, v in engine.config.__dict__.iteritems()})
handler.process()
<|end_body_0|>
<|body_start_1|>
engine = models.LoaderEngine.objects.get(mnemo='hopkins... | ExpertsLoadedStorageAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpertsLoadedStorageAdmin:
def start_asco_load_engine(self, request, queryset):
"""Load data from asco.org"""
<|body_0|>
def start_hopkins_load_engine(self, request, queryset=[]):
"""Load data from hopkinsmedicine.org"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_029071 | 2,421 | no_license | [
{
"docstring": "Load data from asco.org",
"name": "start_asco_load_engine",
"signature": "def start_asco_load_engine(self, request, queryset)"
},
{
"docstring": "Load data from hopkinsmedicine.org",
"name": "start_hopkins_load_engine",
"signature": "def start_hopkins_load_engine(self, re... | 2 | stack_v2_sparse_classes_30k_train_001557 | Implement the Python class `ExpertsLoadedStorageAdmin` described below.
Class description:
Implement the ExpertsLoadedStorageAdmin class.
Method signatures and docstrings:
- def start_asco_load_engine(self, request, queryset): Load data from asco.org
- def start_hopkins_load_engine(self, request, queryset=[]): Load d... | Implement the Python class `ExpertsLoadedStorageAdmin` described below.
Class description:
Implement the ExpertsLoadedStorageAdmin class.
Method signatures and docstrings:
- def start_asco_load_engine(self, request, queryset): Load data from asco.org
- def start_hopkins_load_engine(self, request, queryset=[]): Load d... | 6e4ec18fd987f70345f93335fd49e7f27899324c | <|skeleton|>
class ExpertsLoadedStorageAdmin:
def start_asco_load_engine(self, request, queryset):
"""Load data from asco.org"""
<|body_0|>
def start_hopkins_load_engine(self, request, queryset=[]):
"""Load data from hopkinsmedicine.org"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpertsLoadedStorageAdmin:
def start_asco_load_engine(self, request, queryset):
"""Load data from asco.org"""
engine = models.LoaderEngine.objects.get(mnemo='asco', active=True)
handler = leh.ASCOUploadHandler(engine, **{k: v for k, v in engine.config.__dict__.iteritems()})
han... | the_stack_v2_python_sparse | loaders/admin.py | powerdev1212/Dev | train | 0 | |
7f5d534e8973139f250336e277d91a4a86f10334 | [
"self.batch_client = SentinelHubBatch(config=config)\nif batch_request is None:\n if request_id is None:\n raise ValueError('One of the parameters request_id and batch_request has to be given')\n batch_request = self.batch_client.get_request(request_id)\nself.batch_request = batch_request\nself.tile_si... | <|body_start_0|>
self.batch_client = SentinelHubBatch(config=config)
if batch_request is None:
if request_id is None:
raise ValueError('One of the parameters request_id and batch_request has to be given')
batch_request = self.batch_client.get_request(request_id)
... | A splitter that obtains split bounding boxes from Sentinel Hub Batch API | BatchSplitter | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchSplitter:
"""A splitter that obtains split bounding boxes from Sentinel Hub Batch API"""
def __init__(self, *, request_id: Optional[str]=None, batch_request: Optional[BatchRequest]=None, config: Optional[SHConfig]=None):
""":param request_id: An ID of a batch request :param batc... | stack_v2_sparse_classes_36k_train_029072 | 32,015 | permissive | [
{
"docstring": ":param request_id: An ID of a batch request :param batch_request: A batch request object. It is an alternative to the `request_id` parameter :param config: A configuration object with credentials and information about which service deployment to use.",
"name": "__init__",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_008688 | Implement the Python class `BatchSplitter` described below.
Class description:
A splitter that obtains split bounding boxes from Sentinel Hub Batch API
Method signatures and docstrings:
- def __init__(self, *, request_id: Optional[str]=None, batch_request: Optional[BatchRequest]=None, config: Optional[SHConfig]=None)... | Implement the Python class `BatchSplitter` described below.
Class description:
A splitter that obtains split bounding boxes from Sentinel Hub Batch API
Method signatures and docstrings:
- def __init__(self, *, request_id: Optional[str]=None, batch_request: Optional[BatchRequest]=None, config: Optional[SHConfig]=None)... | 98d0327e3929999ec07645f77b16fceb7f9c88b9 | <|skeleton|>
class BatchSplitter:
"""A splitter that obtains split bounding boxes from Sentinel Hub Batch API"""
def __init__(self, *, request_id: Optional[str]=None, batch_request: Optional[BatchRequest]=None, config: Optional[SHConfig]=None):
""":param request_id: An ID of a batch request :param batc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchSplitter:
"""A splitter that obtains split bounding boxes from Sentinel Hub Batch API"""
def __init__(self, *, request_id: Optional[str]=None, batch_request: Optional[BatchRequest]=None, config: Optional[SHConfig]=None):
""":param request_id: An ID of a batch request :param batch_request: A ... | the_stack_v2_python_sparse | sentinelhub/areas.py | sentinel-hub/sentinelhub-py | train | 704 |
3c3f6a27224c40abf98bdb64034754a9725023fd | [
"for i in ProjectInfo.objects.filter(type=1):\n i_type2 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=2)\n self.assertEqual(i.output_configs(), i_type2.output_configs())\n i_type3 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=3)\n self.assertEqual(i.output_confi... | <|body_start_0|>
for i in ProjectInfo.objects.filter(type=1):
i_type2 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=2)
self.assertEqual(i.output_configs(), i_type2.output_configs())
i_type3 = ProjectInfo.objects.get(items=i.items, platform=i.platform, typ... | ProjectInfoTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectInfoTests:
def test_configs_equal(self):
"""测试type 1 类型配置文件一致"""
<|body_0|>
def test_configs_exist(self):
"""测试配置文件是否存在"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in ProjectInfo.objects.filter(type=1):
i_type2 = Proje... | stack_v2_sparse_classes_36k_train_029073 | 925 | no_license | [
{
"docstring": "测试type 1\u0002\u0003 类型配置文件一致",
"name": "test_configs_equal",
"signature": "def test_configs_equal(self)"
},
{
"docstring": "测试配置文件是否存在",
"name": "test_configs_exist",
"signature": "def test_configs_exist(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009416 | Implement the Python class `ProjectInfoTests` described below.
Class description:
Implement the ProjectInfoTests class.
Method signatures and docstrings:
- def test_configs_equal(self): 测试type 1 类型配置文件一致
- def test_configs_exist(self): 测试配置文件是否存在 | Implement the Python class `ProjectInfoTests` described below.
Class description:
Implement the ProjectInfoTests class.
Method signatures and docstrings:
- def test_configs_equal(self): 测试type 1 类型配置文件一致
- def test_configs_exist(self): 测试配置文件是否存在
<|skeleton|>
class ProjectInfoTests:
def test_configs_equal(sel... | 87cebc5fbc52bfa50a3e457772c48a5fc74c446f | <|skeleton|>
class ProjectInfoTests:
def test_configs_equal(self):
"""测试type 1 类型配置文件一致"""
<|body_0|>
def test_configs_exist(self):
"""测试配置文件是否存在"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectInfoTests:
def test_configs_equal(self):
"""测试type 1 类型配置文件一致"""
for i in ProjectInfo.objects.filter(type=1):
i_type2 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=2)
self.assertEqual(i.output_configs(), i_type2.output_configs())
... | the_stack_v2_python_sparse | cmdb/tests.py | chuan-yk/deployment | train | 0 | |
d93e52b938e92581f84088a120183edbc2297265 | [
"super().__init__()\nself.device = device\nself.hidden_dim = hidden_dim\nself.rgb_dim = rgb_dim\nself.name_prefix = name_prefix\n_out_dim = input_dim\nnetwork = []\nfor i in range(hidden_layers):\n _in_dim = _out_dim\n _out_dim = hidden_dim\n network.append(nn.Linear(in_features=_in_dim, out_features=_out_... | <|body_start_0|>
super().__init__()
self.device = device
self.hidden_dim = hidden_dim
self.rgb_dim = rgb_dim
self.name_prefix = name_prefix
_out_dim = input_dim
network = []
for i in range(hidden_layers):
_in_dim = _out_dim
_out_dim... | FCNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCNet:
def __init__(self, input_dim, hidden_dim, hidden_layers, rgb_dim=3, device=None, name_prefix='fc', **kwargs):
""":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:"""
<|body_0|>
def forward(self, input, **kwargs):
""":param input: p... | stack_v2_sparse_classes_36k_train_029074 | 2,296 | permissive | [
{
"docstring": ":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dim, hidden_layers, rgb_dim=3, device=None, name_prefix='fc', **kwargs)"
},
{
"docstring": ":param input: points xyz, (b, num_po... | 2 | null | Implement the Python class `FCNet` described below.
Class description:
Implement the FCNet class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, hidden_layers, rgb_dim=3, device=None, name_prefix='fc', **kwargs): :param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwa... | Implement the Python class `FCNet` described below.
Class description:
Implement the FCNet class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, hidden_layers, rgb_dim=3, device=None, name_prefix='fc', **kwargs): :param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwa... | 9244193048c73f55270d2df28fb160f42d5953ad | <|skeleton|>
class FCNet:
def __init__(self, input_dim, hidden_dim, hidden_layers, rgb_dim=3, device=None, name_prefix='fc', **kwargs):
""":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:"""
<|body_0|>
def forward(self, input, **kwargs):
""":param input: p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FCNet:
def __init__(self, input_dim, hidden_dim, hidden_layers, rgb_dim=3, device=None, name_prefix='fc', **kwargs):
""":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:"""
super().__init__()
self.device = device
self.hidden_dim = hidden_dim
... | the_stack_v2_python_sparse | exp/comm/models/fc_net.py | tonywork/CIPS-3D | train | 0 | |
c6f6718f430458dd4ecec5b1535bcb1415365ce8 | [
"if self.github_slug:\n return f'https://github.com/{self.github_slug}'\nelse:\n return None",
"if os.getenv('GITHUB_ACTIONS'):\n return cls.for_github_actions()\nelif os.getenv('TRAVIS') == 'true':\n return cls.for_travis()\nelse:\n return cls()",
"github_ref = os.getenv('GITHUB_REF')\nrun_id = ... | <|body_start_0|>
if self.github_slug:
return f'https://github.com/{self.github_slug}'
else:
return None
<|end_body_0|>
<|body_start_1|>
if os.getenv('GITHUB_ACTIONS'):
return cls.for_github_actions()
elif os.getenv('TRAVIS') == 'true':
ret... | Metadata gathered from CI platform environment variables. | CiMetadata | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CiMetadata:
"""Metadata gathered from CI platform environment variables."""
def github_repository(self) -> Optional[str]:
"""URL of the GitHub repository homepage."""
<|body_0|>
def create(cls) -> CiMetadata:
"""Gather CI metadata, automatically inferring the CI ... | stack_v2_sparse_classes_36k_train_029075 | 4,366 | permissive | [
{
"docstring": "URL of the GitHub repository homepage.",
"name": "github_repository",
"signature": "def github_repository(self) -> Optional[str]"
},
{
"docstring": "Gather CI metadata, automatically inferring the CI platform.",
"name": "create",
"signature": "def create(cls) -> CiMetadat... | 4 | stack_v2_sparse_classes_30k_train_017558 | Implement the Python class `CiMetadata` described below.
Class description:
Metadata gathered from CI platform environment variables.
Method signatures and docstrings:
- def github_repository(self) -> Optional[str]: URL of the GitHub repository homepage.
- def create(cls) -> CiMetadata: Gather CI metadata, automatica... | Implement the Python class `CiMetadata` described below.
Class description:
Metadata gathered from CI platform environment variables.
Method signatures and docstrings:
- def github_repository(self) -> Optional[str]: URL of the GitHub repository homepage.
- def create(cls) -> CiMetadata: Gather CI metadata, automatica... | cb92f71b49c3f33d85154dee1acdb56c6e5eb2b6 | <|skeleton|>
class CiMetadata:
"""Metadata gathered from CI platform environment variables."""
def github_repository(self) -> Optional[str]:
"""URL of the GitHub repository homepage."""
<|body_0|>
def create(cls) -> CiMetadata:
"""Gather CI metadata, automatically inferring the CI ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CiMetadata:
"""Metadata gathered from CI platform environment variables."""
def github_repository(self) -> Optional[str]:
"""URL of the GitHub repository homepage."""
if self.github_slug:
return f'https://github.com/{self.github_slug}'
else:
return None
... | the_stack_v2_python_sparse | src/lander/ext/parser/_cidata.py | lsst-sqre/lander | train | 3 |
3a754b82220eb94771f27991941af6a495af0881 | [
"super(GenderedSMPL, self).__init__()\nassert 'gender' not in kwargs, self.__class__.__name__ + \"does not need 'gender' for initialization.\"\nself.smpl_neutral = SMPL(*args, gender='neutral', keypoint_src=keypoint_src, keypoint_dst=keypoint_dst, keypoint_approximate=keypoint_approximate, joints_regressor=joints_r... | <|body_start_0|>
super(GenderedSMPL, self).__init__()
assert 'gender' not in kwargs, self.__class__.__name__ + "does not need 'gender' for initialization."
self.smpl_neutral = SMPL(*args, gender='neutral', keypoint_src=keypoint_src, keypoint_dst=keypoint_dst, keypoint_approximate=keypoint_approx... | A wrapper of SMPL to handle gendered inputs. | GenderedSMPL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenderedSMPL:
"""A wrapper of SMPL to handle gendered inputs."""
def __init__(self, *args, keypoint_src: str='smpl_45', keypoint_dst: str='human_data', keypoint_approximate: bool=False, joints_regressor: str=None, extra_joints_regressor: str=None, **kwargs) -> None:
"""Args: *args: e... | stack_v2_sparse_classes_36k_train_029076 | 26,273 | permissive | [
{
"docstring": "Args: *args: extra arguments for SMPL initialization. keypoint_src: source convention of keypoints. This convention is used for keypoints obtained from joint regressors. Keypoints then undergo conversion into keypoint_dst convention. keypoint_dst: destination convention of keypoints. This conven... | 2 | null | Implement the Python class `GenderedSMPL` described below.
Class description:
A wrapper of SMPL to handle gendered inputs.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='smpl_45', keypoint_dst: str='human_data', keypoint_approximate: bool=False, joints_regressor: str=None, extra_join... | Implement the Python class `GenderedSMPL` described below.
Class description:
A wrapper of SMPL to handle gendered inputs.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='smpl_45', keypoint_dst: str='human_data', keypoint_approximate: bool=False, joints_regressor: str=None, extra_join... | 9431addec32f7fbeffa1786927a854c0ab79d9ea | <|skeleton|>
class GenderedSMPL:
"""A wrapper of SMPL to handle gendered inputs."""
def __init__(self, *args, keypoint_src: str='smpl_45', keypoint_dst: str='human_data', keypoint_approximate: bool=False, joints_regressor: str=None, extra_joints_regressor: str=None, **kwargs) -> None:
"""Args: *args: e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenderedSMPL:
"""A wrapper of SMPL to handle gendered inputs."""
def __init__(self, *args, keypoint_src: str='smpl_45', keypoint_dst: str='human_data', keypoint_approximate: bool=False, joints_regressor: str=None, extra_joints_regressor: str=None, **kwargs) -> None:
"""Args: *args: extra argument... | the_stack_v2_python_sparse | mmhuman3d/models/body_models/smpl.py | open-mmlab/mmhuman3d | train | 966 |
bd4680d7fa468afedb1bfc02b27b239021ada23b | [
"line = line.split()\nself.nbins2d = int(line[1])\nself.nbins1d = int(line[2])\nself.rho_min = float(line[3])\nself.rho_max = float(line[4])\nself.rho2d = np.zeros((nsteps, self.nbins2d, self.nbins2d))\nself.xedges = 0\nself.yedges = 0\nself.hist_rho = np.zeros((nsteps, self.nbins1d))\nself.edges1d = 0\nreturn",
... | <|body_start_0|>
line = line.split()
self.nbins2d = int(line[1])
self.nbins1d = int(line[2])
self.rho_min = float(line[3])
self.rho_max = float(line[4])
self.rho2d = np.zeros((nsteps, self.nbins2d, self.nbins2d))
self.xedges = 0
self.yedges = 0
sel... | Density | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Density:
def __init__(self, nsteps, line):
"""initialize: allocate density array"""
<|body_0|>
def compute(self, step, x, y, lx, ly, natoms, plot='False'):
"""compute a density distribution and a histogram of the density distribution"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_029077 | 2,051 | no_license | [
{
"docstring": "initialize: allocate density array",
"name": "__init__",
"signature": "def __init__(self, nsteps, line)"
},
{
"docstring": "compute a density distribution and a histogram of the density distribution",
"name": "compute",
"signature": "def compute(self, step, x, y, lx, ly, ... | 2 | null | Implement the Python class `Density` described below.
Class description:
Implement the Density class.
Method signatures and docstrings:
- def __init__(self, nsteps, line): initialize: allocate density array
- def compute(self, step, x, y, lx, ly, natoms, plot='False'): compute a density distribution and a histogram o... | Implement the Python class `Density` described below.
Class description:
Implement the Density class.
Method signatures and docstrings:
- def __init__(self, nsteps, line): initialize: allocate density array
- def compute(self, step, x, y, lx, ly, natoms, plot='False'): compute a density distribution and a histogram o... | 7d2659bee85c955c680eda019cbff6e2b93ecff2 | <|skeleton|>
class Density:
def __init__(self, nsteps, line):
"""initialize: allocate density array"""
<|body_0|>
def compute(self, step, x, y, lx, ly, natoms, plot='False'):
"""compute a density distribution and a histogram of the density distribution"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Density:
def __init__(self, nsteps, line):
"""initialize: allocate density array"""
line = line.split()
self.nbins2d = int(line[1])
self.nbins1d = int(line[2])
self.rho_min = float(line[3])
self.rho_max = float(line[4])
self.rho2d = np.zeros((nsteps, sel... | the_stack_v2_python_sparse | analyse_collective/density.py | melampyge/CollectiveFilament | train | 0 | |
2d6d1211751bdaa27439e9d456f0e05c68c56a1e | [
"super(Generator, self).__init__()\nself.num_gpu = num_gpu\nself.layer = nn.Sequential(nn.ConvTranspose2d(z_dim, conv_dim * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(conv_dim * 8), nn.ReLU(True), nn.ConvTranspose2d(conv_dim * 8, conv_dim * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(conv_dim * 4), nn.ReLU(True), nn.ConvT... | <|body_start_0|>
super(Generator, self).__init__()
self.num_gpu = num_gpu
self.layer = nn.Sequential(nn.ConvTranspose2d(z_dim, conv_dim * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(conv_dim * 8), nn.ReLU(True), nn.ConvTranspose2d(conv_dim * 8, conv_dim * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(conv... | Model for Generator. | Generator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Model for Generator."""
def __init__(self, num_channels, z_dim, conv_dim, num_gpu):
"""Init for Generator model."""
<|body_0|>
def forward(self, input):
"""Forward step for Generator model."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_029078 | 4,479 | permissive | [
{
"docstring": "Init for Generator model.",
"name": "__init__",
"signature": "def __init__(self, num_channels, z_dim, conv_dim, num_gpu)"
},
{
"docstring": "Forward step for Generator model.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002468 | Implement the Python class `Generator` described below.
Class description:
Model for Generator.
Method signatures and docstrings:
- def __init__(self, num_channels, z_dim, conv_dim, num_gpu): Init for Generator model.
- def forward(self, input): Forward step for Generator model. | Implement the Python class `Generator` described below.
Class description:
Model for Generator.
Method signatures and docstrings:
- def __init__(self, num_channels, z_dim, conv_dim, num_gpu): Init for Generator model.
- def forward(self, input): Forward step for Generator model.
<|skeleton|>
class Generator:
"""... | fd4498da35ace5a3d1696ff4fbec3568eddbe6a1 | <|skeleton|>
class Generator:
"""Model for Generator."""
def __init__(self, num_channels, z_dim, conv_dim, num_gpu):
"""Init for Generator model."""
<|body_0|>
def forward(self, input):
"""Forward step for Generator model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Model for Generator."""
def __init__(self, num_channels, z_dim, conv_dim, num_gpu):
"""Init for Generator model."""
super(Generator, self).__init__()
self.num_gpu = num_gpu
self.layer = nn.Sequential(nn.ConvTranspose2d(z_dim, conv_dim * 8, 4, 1, 0, bias=False... | the_stack_v2_python_sparse | DCGAN/models.py | corenel/GAN-Zoo | train | 10 |
715af39e3858a3b3ef60d4ce4d977c2f13bfcf89 | [
"if not os.path.exists(path):\n raise CertificateNotFoundError(_('The SSL/TLS CA bundle was not found.'))\ntry:\n with open(path, 'rb') as fp:\n data = fp.read()\nexcept IOError as e:\n error_id = str(uuid4())\n logger.error('[%s] Error reading SSL/TLS CA bundle file \"%s\": %s', error_id, path, ... | <|body_start_0|>
if not os.path.exists(path):
raise CertificateNotFoundError(_('The SSL/TLS CA bundle was not found.'))
try:
with open(path, 'rb') as fp:
data = fp.read()
except IOError as e:
error_id = str(uuid4())
logger.error('[%... | A bundle of root and intermediary certificates. This represents a "CA bundle," which specifies a root certificate and any necessary intermediary certificates used to validate other certificates, including those signed using an in-house certificate authority. Consumers should take care not to modify any certificate data... | CertificateBundle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CertificateBundle:
"""A bundle of root and intermediary certificates. This represents a "CA bundle," which specifies a root certificate and any necessary intermediary certificates used to validate other certificates, including those signed using an in-house certificate authority. Consumers should... | stack_v2_sparse_classes_36k_train_029079 | 29,327 | permissive | [
{
"docstring": "Return an instance parsed from a PEM bundle file. Args: name (str): The name of this bundle file. This must be in :term:`slug` format. path (str): The path to the file. Raises: reviewboard.certs.errors.CertificateStorageError: There was an error loading the CA bundle. Details are in the error me... | 3 | null | Implement the Python class `CertificateBundle` described below.
Class description:
A bundle of root and intermediary certificates. This represents a "CA bundle," which specifies a root certificate and any necessary intermediary certificates used to validate other certificates, including those signed using an in-house ... | Implement the Python class `CertificateBundle` described below.
Class description:
A bundle of root and intermediary certificates. This represents a "CA bundle," which specifies a root certificate and any necessary intermediary certificates used to validate other certificates, including those signed using an in-house ... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class CertificateBundle:
"""A bundle of root and intermediary certificates. This represents a "CA bundle," which specifies a root certificate and any necessary intermediary certificates used to validate other certificates, including those signed using an in-house certificate authority. Consumers should... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CertificateBundle:
"""A bundle of root and intermediary certificates. This represents a "CA bundle," which specifies a root certificate and any necessary intermediary certificates used to validate other certificates, including those signed using an in-house certificate authority. Consumers should take care no... | the_stack_v2_python_sparse | reviewboard/certs/cert.py | reviewboard/reviewboard | train | 1,141 |
33f8363ce5b1bafaf6c830e8665c80f834104607 | [
"try:\n quantity.Concentration(1.0, 'm^-3')\n self.fail('Allowed invalid unit type \"m^-3\".')\nexcept quantity.QuantityError:\n pass",
"q = quantity.Concentration(1.0, 'mol/m^3')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'mo... | <|body_start_0|>
try:
quantity.Concentration(1.0, 'm^-3')
self.fail('Allowed invalid unit type "m^-3".')
except quantity.QuantityError:
pass
<|end_body_0|>
<|body_start_1|>
q = quantity.Concentration(1.0, 'mol/m^3')
self.assertAlmostEqual(q.value, 1.0... | Contains unit tests of the Concentration unit type object. | TestConcentration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConcentration:
"""Contains unit tests of the Concentration unit type object."""
def test_perm3(self):
"""Test the creation of an concentration quantity with units of m^-3."""
<|body_0|>
def test_molperm3(self):
"""Test the creation of an concentration quantit... | stack_v2_sparse_classes_36k_train_029080 | 49,563 | permissive | [
{
"docstring": "Test the creation of an concentration quantity with units of m^-3.",
"name": "test_perm3",
"signature": "def test_perm3(self)"
},
{
"docstring": "Test the creation of an concentration quantity with units of mol/m^3.",
"name": "test_molperm3",
"signature": "def test_molper... | 3 | null | Implement the Python class `TestConcentration` described below.
Class description:
Contains unit tests of the Concentration unit type object.
Method signatures and docstrings:
- def test_perm3(self): Test the creation of an concentration quantity with units of m^-3.
- def test_molperm3(self): Test the creation of an ... | Implement the Python class `TestConcentration` described below.
Class description:
Contains unit tests of the Concentration unit type object.
Method signatures and docstrings:
- def test_perm3(self): Test the creation of an concentration quantity with units of m^-3.
- def test_molperm3(self): Test the creation of an ... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestConcentration:
"""Contains unit tests of the Concentration unit type object."""
def test_perm3(self):
"""Test the creation of an concentration quantity with units of m^-3."""
<|body_0|>
def test_molperm3(self):
"""Test the creation of an concentration quantit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestConcentration:
"""Contains unit tests of the Concentration unit type object."""
def test_perm3(self):
"""Test the creation of an concentration quantity with units of m^-3."""
try:
quantity.Concentration(1.0, 'm^-3')
self.fail('Allowed invalid unit type "m^-3".'... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
81f2f06cd37acd3176cf8dd173fa265850e292cd | [
"super().__init__(**kwargs)\nself.dx = dx\nself.dy = dy",
"if self.dx is None or self.dy is None:\n raise Exception('dx or dy not set')\nif self.dx + self.dy != X.shape[0]:\n raise Exception('Dimension mismatch')\n_, E_yx, E_yy = util.split_edges(E, self.dx, self.dy)\nreturn self.regress_conditional(X[:self... | <|body_start_0|>
super().__init__(**kwargs)
self.dx = dx
self.dy = dy
<|end_body_0|>
<|body_start_1|>
if self.dx is None or self.dy is None:
raise Exception('dx or dy not set')
if self.dx + self.dy != X.shape[0]:
raise Exception('Dimension mismatch')
... | Base class for dense regressors, which can be used both as a joint and a conditional regressor. | DenseConditionalRegressorBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseConditionalRegressorBase:
"""Base class for dense regressors, which can be used both as a joint and a conditional regressor."""
def __init__(self, dx=None, dy=None, **kwargs):
"""Initializes the regressor. :param dx: Number of features. Can be None when used as a conditional reg... | stack_v2_sparse_classes_36k_train_029081 | 6,981 | no_license | [
{
"docstring": "Initializes the regressor. :param dx: Number of features. Can be None when used as a conditional regressor. :param dy: Number of targets. Can be None when used as a conditional regressor.",
"name": "__init__",
"signature": "def __init__(self, dx=None, dy=None, **kwargs)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_020822 | Implement the Python class `DenseConditionalRegressorBase` described below.
Class description:
Base class for dense regressors, which can be used both as a joint and a conditional regressor.
Method signatures and docstrings:
- def __init__(self, dx=None, dy=None, **kwargs): Initializes the regressor. :param dx: Numbe... | Implement the Python class `DenseConditionalRegressorBase` described below.
Class description:
Base class for dense regressors, which can be used both as a joint and a conditional regressor.
Method signatures and docstrings:
- def __init__(self, dx=None, dy=None, **kwargs): Initializes the regressor. :param dx: Numbe... | 3f641277653338184afd41d5e1c6650c0b46632a | <|skeleton|>
class DenseConditionalRegressorBase:
"""Base class for dense regressors, which can be used both as a joint and a conditional regressor."""
def __init__(self, dx=None, dy=None, **kwargs):
"""Initializes the regressor. :param dx: Number of features. Can be None when used as a conditional reg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DenseConditionalRegressorBase:
"""Base class for dense regressors, which can be used both as a joint and a conditional regressor."""
def __init__(self, dx=None, dy=None, **kwargs):
"""Initializes the regressor. :param dx: Number of features. Can be None when used as a conditional regressor. :para... | the_stack_v2_python_sparse | regressors/common/dense.py | nonocodebox/robust-regression-elliptical | train | 0 |
fccf0a093fabd4960d36d194df00087e15c6b8d7 | [
"self.layer_configs = OrderedDict()\nself.supported_layers = supported_layers\nself.layer_counter = 0",
"with open(cfg_file_path) as cfg_file:\n remainder = cfg_file.read()\n while remainder is not None:\n layer_dict, layer_name, remainder = self._next_layer(remainder)\n if layer_dict is not N... | <|body_start_0|>
self.layer_configs = OrderedDict()
self.supported_layers = supported_layers
self.layer_counter = 0
<|end_body_0|>
<|body_start_1|>
with open(cfg_file_path) as cfg_file:
remainder = cfg_file.read()
while remainder is not None:
laye... | Definition of a parser for DarkNet-based YOLOv3-608 (only tested for this topology). | DarkNetParser | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarkNetParser:
"""Definition of a parser for DarkNet-based YOLOv3-608 (only tested for this topology)."""
def __init__(self, supported_layers):
"""Initializes a DarkNetParser object. Keyword argument: supported_layers -- a string list of supported layers in DarkNet naming convention,... | stack_v2_sparse_classes_36k_train_029082 | 29,876 | permissive | [
{
"docstring": "Initializes a DarkNetParser object. Keyword argument: supported_layers -- a string list of supported layers in DarkNet naming convention, parameters are only added to the class dictionary if a parsed layer is included.",
"name": "__init__",
"signature": "def __init__(self, supported_laye... | 4 | stack_v2_sparse_classes_30k_train_016284 | Implement the Python class `DarkNetParser` described below.
Class description:
Definition of a parser for DarkNet-based YOLOv3-608 (only tested for this topology).
Method signatures and docstrings:
- def __init__(self, supported_layers): Initializes a DarkNetParser object. Keyword argument: supported_layers -- a stri... | Implement the Python class `DarkNetParser` described below.
Class description:
Definition of a parser for DarkNet-based YOLOv3-608 (only tested for this topology).
Method signatures and docstrings:
- def __init__(self, supported_layers): Initializes a DarkNetParser object. Keyword argument: supported_layers -- a stri... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class DarkNetParser:
"""Definition of a parser for DarkNet-based YOLOv3-608 (only tested for this topology)."""
def __init__(self, supported_layers):
"""Initializes a DarkNetParser object. Keyword argument: supported_layers -- a string list of supported layers in DarkNet naming convention,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DarkNetParser:
"""Definition of a parser for DarkNet-based YOLOv3-608 (only tested for this topology)."""
def __init__(self, supported_layers):
"""Initializes a DarkNetParser object. Keyword argument: supported_layers -- a string list of supported layers in DarkNet naming convention, parameters a... | the_stack_v2_python_sparse | samples/python/yolov3_onnx/yolov3_to_onnx.py | NVIDIA/TensorRT | train | 8,026 |
954993e214f2bd498405f9fcafb85502e1872d01 | [
"if aspect is None:\n src_width, src_height = self.GetBestSize()\n try:\n aspect = (src_width / float(src_height), 1)\n except ZeroDivisionError:\n aspect = (4, 3)\nsize = self._calculate_size(slot_size, aspect)\nself.SetMinSize(size)\nself.SetSize(size)",
"slot_width, slot_height = slot_si... | <|body_start_0|>
if aspect is None:
src_width, src_height = self.GetBestSize()
try:
aspect = (src_width / float(src_height), 1)
except ZeroDivisionError:
aspect = (4, 3)
size = self._calculate_size(slot_size, aspect)
self.SetMin... | Customization of MediaCtrl widget. | VideoWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoWidget:
"""Customization of MediaCtrl widget."""
def SetAspectRatio(self, aspect, slot_size):
"""Sets video widget size in according to a selected aspect ratio. :param tuple aspect: Aspect ratio value :param tuple slot_size: Maximum size available for a widget"""
<|body_... | stack_v2_sparse_classes_36k_train_029083 | 5,982 | no_license | [
{
"docstring": "Sets video widget size in according to a selected aspect ratio. :param tuple aspect: Aspect ratio value :param tuple slot_size: Maximum size available for a widget",
"name": "SetAspectRatio",
"signature": "def SetAspectRatio(self, aspect, slot_size)"
},
{
"docstring": "Calculates... | 2 | stack_v2_sparse_classes_30k_train_006611 | Implement the Python class `VideoWidget` described below.
Class description:
Customization of MediaCtrl widget.
Method signatures and docstrings:
- def SetAspectRatio(self, aspect, slot_size): Sets video widget size in according to a selected aspect ratio. :param tuple aspect: Aspect ratio value :param tuple slot_siz... | Implement the Python class `VideoWidget` described below.
Class description:
Customization of MediaCtrl widget.
Method signatures and docstrings:
- def SetAspectRatio(self, aspect, slot_size): Sets video widget size in according to a selected aspect ratio. :param tuple aspect: Aspect ratio value :param tuple slot_siz... | b8194f082a29d75dac27a4021d9607045a04855a | <|skeleton|>
class VideoWidget:
"""Customization of MediaCtrl widget."""
def SetAspectRatio(self, aspect, slot_size):
"""Sets video widget size in according to a selected aspect ratio. :param tuple aspect: Aspect ratio value :param tuple slot_size: Maximum size available for a widget"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoWidget:
"""Customization of MediaCtrl widget."""
def SetAspectRatio(self, aspect, slot_size):
"""Sets video widget size in according to a selected aspect ratio. :param tuple aspect: Aspect ratio value :param tuple slot_size: Maximum size available for a widget"""
if aspect is None:
... | the_stack_v2_python_sparse | steno/widgets.py | antonkonyshev/steno | train | 1 |
bf0b1422d15ebe8c48221d55aaab887a3da43790 | [
"j.builder.buildenv.install()\nif self.tools.isUbuntu:\n j.builder.system.package.ensure('g++')\nurl = 'https://capnproto.org/capnproto-c++-0.7.0.tar.gz'\nself.tools.file_download(url, to='{}/capnproto'.format(self.DIR_BUILD), overwrite=False, retry=3, expand=True, minsizekb=900, removeTopDir=True, deletedest=Tr... | <|body_start_0|>
j.builder.buildenv.install()
if self.tools.isUbuntu:
j.builder.system.package.ensure('g++')
url = 'https://capnproto.org/capnproto-c++-0.7.0.tar.gz'
self.tools.file_download(url, to='{}/capnproto'.format(self.DIR_BUILD), overwrite=False, retry=3, expand=True,... | BuilderCapnp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuilderCapnp:
def build(self):
"""install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'"""
<|body_0|>
def install(self):
"""install capnp kosmos 'j.builder.libs.capnp.install()'"""
<|body_1|>
def test(self):
... | stack_v2_sparse_classes_36k_train_029084 | 1,668 | permissive | [
{
"docstring": "install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "install capnp kosmos 'j.builder.libs.capnp.install()'",
"name": "install",
"signature": "def install(se... | 3 | stack_v2_sparse_classes_30k_train_014286 | Implement the Python class `BuilderCapnp` described below.
Class description:
Implement the BuilderCapnp class.
Method signatures and docstrings:
- def build(self): install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'
- def install(self): install capnp kosmos 'j.builder.... | Implement the Python class `BuilderCapnp` described below.
Class description:
Implement the BuilderCapnp class.
Method signatures and docstrings:
- def build(self): install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'
- def install(self): install capnp kosmos 'j.builder.... | 7fff1c40fcd226d33a1df8c89ee35677d62efb22 | <|skeleton|>
class BuilderCapnp:
def build(self):
"""install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'"""
<|body_0|>
def install(self):
"""install capnp kosmos 'j.builder.libs.capnp.install()'"""
<|body_1|>
def test(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuilderCapnp:
def build(self):
"""install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'"""
j.builder.buildenv.install()
if self.tools.isUbuntu:
j.builder.system.package.ensure('g++')
url = 'https://capnproto.org/capnprot... | the_stack_v2_python_sparse | Jumpscale/builder/libs/BuilderCapnp.py | Pishoy/jumpscaleX | train | 0 | |
2738a587cdebd824e5a118e99e4aefeb834e1e21 | [
"super(MBConv, self).__init__()\nif norm_layer is None:\n norm_layer = nn.BatchNorm2d\nif act_layer is None:\n act_layer = nn.ReLU6\nif kernel_size == 3:\n conv_dw = conv3x3\nelif kernel_size == 5:\n conv_dw = conv5x5\nelse:\n raise ValueError('MBConv class only supports kernel size 3x3, 5x5')\nself.... | <|body_start_0|>
super(MBConv, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if act_layer is None:
act_layer = nn.ReLU6
if kernel_size == 3:
conv_dw = conv3x3
elif kernel_size == 5:
conv_dw = conv5x5
el... | mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K: input channels; K': output channe... | MBConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBConv:
"""mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K:... | stack_v2_sparse_classes_36k_train_029085 | 20,656 | no_license | [
{
"docstring": "Constructor Args: inplanes: (int) number of input channels outplanes: (int) number of output channels expansion: (int) expansion factor for inverted residuals kernel_size: (int) 3x3 or 5x5 conv-dw filter stride: (int) stride for conv-dw filter dropout: (float) p = dropout; default = 0 (no dropou... | 2 | stack_v2_sparse_classes_30k_train_011905 | Implement the Python class `MBConv` described below.
Class description:
mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s ... | Implement the Python class `MBConv` described below.
Class description:
mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s ... | a0c51824b9c4c458918ef9a40a925cd576137d75 | <|skeleton|>
class MBConv:
"""mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MBConv:
"""mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K: input channe... | the_stack_v2_python_sparse | model/mnasnet.py | baihuaxie/ConvLab | train | 0 |
f2bea8af40db8f098d2b53cdcf76fd00ce4388a1 | [
"super(BidirectionalLanguageModel, self).__init__()\nself.lstms = nn.ModuleList([nn.LSTM(emb_dim, hid_dim, bidirectional=True, dropout=dropout, batch_first=True), nn.LSTM(prj_emb, hid_dim, bidirectional=True, dropout=dropout, batch_first=True)])\nself.projection_layer = nn.Linear(2 * hid_dim, prj_emb)",
"first_ou... | <|body_start_0|>
super(BidirectionalLanguageModel, self).__init__()
self.lstms = nn.ModuleList([nn.LSTM(emb_dim, hid_dim, bidirectional=True, dropout=dropout, batch_first=True), nn.LSTM(prj_emb, hid_dim, bidirectional=True, dropout=dropout, batch_first=True)])
self.projection_layer = nn.Linear(2... | BidirectionalLanguageModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalLanguageModel:
def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None:
"""> We use dropout before and after evert LSTM layer"""
<|body_0|>
def forward(self, x: torch.Tensor, hidden: Tuple[torch.Tensor]=None):
"""Paramete... | stack_v2_sparse_classes_36k_train_029086 | 4,549 | no_license | [
{
"docstring": "> We use dropout before and after evert LSTM layer",
"name": "__init__",
"signature": "def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None"
},
{
"docstring": "Parameters: x: A sentence tensor that embeded hidden: tuple of hidden and cell. The ... | 2 | stack_v2_sparse_classes_30k_train_009814 | Implement the Python class `BidirectionalLanguageModel` described below.
Class description:
Implement the BidirectionalLanguageModel class.
Method signatures and docstrings:
- def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None: > We use dropout before and after evert LSTM layer
-... | Implement the Python class `BidirectionalLanguageModel` described below.
Class description:
Implement the BidirectionalLanguageModel class.
Method signatures and docstrings:
- def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None: > We use dropout before and after evert LSTM layer
-... | ca033284850147b334d3771df8235a1135eba76c | <|skeleton|>
class BidirectionalLanguageModel:
def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None:
"""> We use dropout before and after evert LSTM layer"""
<|body_0|>
def forward(self, x: torch.Tensor, hidden: Tuple[torch.Tensor]=None):
"""Paramete... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BidirectionalLanguageModel:
def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None:
"""> We use dropout before and after evert LSTM layer"""
super(BidirectionalLanguageModel, self).__init__()
self.lstms = nn.ModuleList([nn.LSTM(emb_dim, hid_dim, bidire... | the_stack_v2_python_sparse | papers/4.ELMo/elmo.py | euhkim/NLP | train | 0 | |
05e2f567979bf508420c132ef60645d1403dcff3 | [
"if 0 <= row < M and 0 <= col < N and (board[row][col] == 'O'):\n board[row][col] = 'P'\n self.recursive_flip(board, row + 1, col, M, N)\n self.recursive_flip(board, row - 1, col, M, N)\n self.recursive_flip(board, row, col + 1, M, N)\n self.recursive_flip(board, row, col - 1, M, N)",
"if not board... | <|body_start_0|>
if 0 <= row < M and 0 <= col < N and (board[row][col] == 'O'):
board[row][col] = 'P'
self.recursive_flip(board, row + 1, col, M, N)
self.recursive_flip(board, row - 1, col, M, N)
self.recursive_flip(board, row, col + 1, M, N)
self.recu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recursive_flip(self, board, row, col, M, N):
"""Changes an O here to a P and recurse to all four adjacent tiles. Otherwise stop. M and N are board rows and cols, respectively"""
<|body_0|>
def solve(self, board):
""":type board: List[List[str]] :rtype: ... | stack_v2_sparse_classes_36k_train_029087 | 2,719 | no_license | [
{
"docstring": "Changes an O here to a P and recurse to all four adjacent tiles. Otherwise stop. M and N are board rows and cols, respectively",
"name": "recursive_flip",
"signature": "def recursive_flip(self, board, row, col, M, N)"
},
{
"docstring": ":type board: List[List[str]] :rtype: None D... | 2 | stack_v2_sparse_classes_30k_train_020146 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursive_flip(self, board, row, col, M, N): Changes an O here to a P and recurse to all four adjacent tiles. Otherwise stop. M and N are board rows and cols, respectively
- ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursive_flip(self, board, row, col, M, N): Changes an O here to a P and recurse to all four adjacent tiles. Otherwise stop. M and N are board rows and cols, respectively
- ... | 3a2e75238a333843987c6413ab674a7e985c8c01 | <|skeleton|>
class Solution:
def recursive_flip(self, board, row, col, M, N):
"""Changes an O here to a P and recurse to all four adjacent tiles. Otherwise stop. M and N are board rows and cols, respectively"""
<|body_0|>
def solve(self, board):
""":type board: List[List[str]] :rtype: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recursive_flip(self, board, row, col, M, N):
"""Changes an O here to a P and recurse to all four adjacent tiles. Otherwise stop. M and N are board rows and cols, respectively"""
if 0 <= row < M and 0 <= col < N and (board[row][col] == 'O'):
board[row][col] = 'P'
... | the_stack_v2_python_sparse | coding_practice/recursion/surrounded_regions.py | daveboat/interview_prep | train | 2 | |
d278a5e47cf280bb5ad5cbd8c8306ad3e6541332 | [
"super().__init__()\nself._images_map = images_map\nself._scale_factor = scale_factor\nself._center_crop_factor = center_crop_factor",
"example = generate_image_triplet_example(triplet_dict, self._scale_factor, self._center_crop_factor)\nif example:\n return [example.SerializeToString()]\nelse:\n return []"... | <|body_start_0|>
super().__init__()
self._images_map = images_map
self._scale_factor = scale_factor
self._center_crop_factor = center_crop_factor
<|end_body_0|>
<|body_start_1|>
example = generate_image_triplet_example(triplet_dict, self._scale_factor, self._center_crop_factor)
... | Generate a tf.train.Example per input image triplet filepaths. | ExampleGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleGenerator:
"""Generate a tf.train.Example per input image triplet filepaths."""
def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1):
"""Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from ima... | stack_v2_sparse_classes_36k_train_029088 | 7,599 | permissive | [
{
"docstring": "Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from image key to image filepath. scale_factor: A scale factor to downsample frames. center_crop_factor: A factor to centercrop and downsize frames.",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_005460 | Implement the Python class `ExampleGenerator` described below.
Class description:
Generate a tf.train.Example per input image triplet filepaths.
Method signatures and docstrings:
- def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1): Initializes the map of 3 images to add... | Implement the Python class `ExampleGenerator` described below.
Class description:
Generate a tf.train.Example per input image triplet filepaths.
Method signatures and docstrings:
- def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1): Initializes the map of 3 images to add... | 4108849dc72ad5ea4a91bb13463860bec3b181d7 | <|skeleton|>
class ExampleGenerator:
"""Generate a tf.train.Example per input image triplet filepaths."""
def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1):
"""Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from ima... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExampleGenerator:
"""Generate a tf.train.Example per input image triplet filepaths."""
def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1):
"""Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from image key to ima... | the_stack_v2_python_sparse | docker/frame-interpolation/src/datasets/util.py | sbetzin/neural-style-azure | train | 4 |
4f4a0af05157f4f5ce13914aa271b4f0d025ca89 | [
"self.dataloader = dataloader\nself.length = len(self.dataloader)\nlogger.get_log().info('dataloader length is {}'.format(self.length))",
"self.dataset = dataset\nlength = len(self.dataset)\nbatch_size, drop_last = (dataloader_info.get('batch_size'), dataloader_info.get('drop_last'))\nif not drop_last:\n if le... | <|body_start_0|>
self.dataloader = dataloader
self.length = len(self.dataloader)
logger.get_log().info('dataloader length is {}'.format(self.length))
<|end_body_0|>
<|body_start_1|>
self.dataset = dataset
length = len(self.dataset)
batch_size, drop_last = (dataloader_inf... | test DataLoader class | TestDataLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDataLoader:
"""test DataLoader class"""
def __init__(self, dataloader):
"""init"""
<|body_0|>
def run(self, dataset, dataloader_info):
"""run"""
<|body_1|>
def _obo_check(self, info):
"""check data one by one"""
<|body_2|>
de... | stack_v2_sparse_classes_36k_train_029089 | 7,560 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, dataloader)"
},
{
"docstring": "run",
"name": "run",
"signature": "def run(self, dataset, dataloader_info)"
},
{
"docstring": "check data one by one",
"name": "_obo_check",
"signature": "def _obo_... | 4 | stack_v2_sparse_classes_30k_train_011126 | Implement the Python class `TestDataLoader` described below.
Class description:
test DataLoader class
Method signatures and docstrings:
- def __init__(self, dataloader): init
- def run(self, dataset, dataloader_info): run
- def _obo_check(self, info): check data one by one
- def _skip_check(self, info): check data sk... | Implement the Python class `TestDataLoader` described below.
Class description:
test DataLoader class
Method signatures and docstrings:
- def __init__(self, dataloader): init
- def run(self, dataset, dataloader_info): run
- def _obo_check(self, info): check data one by one
- def _skip_check(self, info): check data sk... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestDataLoader:
"""test DataLoader class"""
def __init__(self, dataloader):
"""init"""
<|body_0|>
def run(self, dataset, dataloader_info):
"""run"""
<|body_1|>
def _obo_check(self, info):
"""check data one by one"""
<|body_2|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDataLoader:
"""test DataLoader class"""
def __init__(self, dataloader):
"""init"""
self.dataloader = dataloader
self.length = len(self.dataloader)
logger.get_log().info('dataloader length is {}'.format(self.length))
def run(self, dataset, dataloader_info):
... | the_stack_v2_python_sparse | framework/e2e/io/io_test.py | PaddlePaddle/PaddleTest | train | 42 |
bb0342287ef95e0fe6e85b91b5cfac4993d3814d | [
"import mxnet\nsuper().__init__(size=size, batch_size=batch_size)\nif not isinstance(iterator, mxnet.gluon.data.DataLoader):\n raise TypeError(f'Expected instance of Gluon `DataLoader, received {type(iterator)} instead.`')\nself._iterator = iterator\nself._current = iter(self.iterator)",
"try:\n batch = lis... | <|body_start_0|>
import mxnet
super().__init__(size=size, batch_size=batch_size)
if not isinstance(iterator, mxnet.gluon.data.DataLoader):
raise TypeError(f'Expected instance of Gluon `DataLoader, received {type(iterator)} instead.`')
self._iterator = iterator
self._c... | Wrapper class on top of the MXNet/Gluon native data loader :class:`mxnet.gluon.data.DataLoader`. | MXDataGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MXDataGenerator:
"""Wrapper class on top of the MXNet/Gluon native data loader :class:`mxnet.gluon.data.DataLoader`."""
def __init__(self, iterator: 'mxnet.gluon.data.DataLoader', size: int, batch_size: int) -> None:
"""Create a data generator wrapper on top of an MXNet :class:`DataL... | stack_v2_sparse_classes_36k_train_029090 | 15,829 | permissive | [
{
"docstring": "Create a data generator wrapper on top of an MXNet :class:`DataLoader`. :param iterator: A MXNet DataLoader instance. :param size: Total size of the dataset. :param batch_size: Size of the minibatches.",
"name": "__init__",
"signature": "def __init__(self, iterator: 'mxnet.gluon.data.Dat... | 2 | stack_v2_sparse_classes_30k_val_000179 | Implement the Python class `MXDataGenerator` described below.
Class description:
Wrapper class on top of the MXNet/Gluon native data loader :class:`mxnet.gluon.data.DataLoader`.
Method signatures and docstrings:
- def __init__(self, iterator: 'mxnet.gluon.data.DataLoader', size: int, batch_size: int) -> None: Create ... | Implement the Python class `MXDataGenerator` described below.
Class description:
Wrapper class on top of the MXNet/Gluon native data loader :class:`mxnet.gluon.data.DataLoader`.
Method signatures and docstrings:
- def __init__(self, iterator: 'mxnet.gluon.data.DataLoader', size: int, batch_size: int) -> None: Create ... | 6b424dadac60631c126e864551bd7202c2e19478 | <|skeleton|>
class MXDataGenerator:
"""Wrapper class on top of the MXNet/Gluon native data loader :class:`mxnet.gluon.data.DataLoader`."""
def __init__(self, iterator: 'mxnet.gluon.data.DataLoader', size: int, batch_size: int) -> None:
"""Create a data generator wrapper on top of an MXNet :class:`DataL... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MXDataGenerator:
"""Wrapper class on top of the MXNet/Gluon native data loader :class:`mxnet.gluon.data.DataLoader`."""
def __init__(self, iterator: 'mxnet.gluon.data.DataLoader', size: int, batch_size: int) -> None:
"""Create a data generator wrapper on top of an MXNet :class:`DataLoader`. :para... | the_stack_v2_python_sparse | art/data_generators.py | kztakemoto/adversarial-robustness-toolbox | train | 0 |
9fef5c33b0e15df0a4cb2767206a8954ae6220b0 | [
"N = len(scores)\nsa = sorted(zip(scores, ages), key=lambda sa: (sa[1], sa[0]))\n\n@lru_cache(None)\ndef dfs(i, threshold):\n if i == N:\n return 0\n ret = dfs(i + 1, threshold)\n if sa[i][0] >= threshold:\n ret = max(ret, sa[i][0] + dfs(i + 1, sa[i][0]))\n return ret\nreturn dfs(0, -float... | <|body_start_0|>
N = len(scores)
sa = sorted(zip(scores, ages), key=lambda sa: (sa[1], sa[0]))
@lru_cache(None)
def dfs(i, threshold):
if i == N:
return 0
ret = dfs(i + 1, threshold)
if sa[i][0] >= threshold:
ret = max(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
"""Mar 18, 2023 13:31 TLE, Maximum recursion depth exceeded"""
<|body_0|>
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
"""Mar 18, 2023 13:58"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_029091 | 10,866 | no_license | [
{
"docstring": "Mar 18, 2023 13:31 TLE, Maximum recursion depth exceeded",
"name": "bestTeamScore",
"signature": "def bestTeamScore(self, scores: List[int], ages: List[int]) -> int"
},
{
"docstring": "Mar 18, 2023 13:58",
"name": "bestTeamScore",
"signature": "def bestTeamScore(self, sco... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: Mar 18, 2023 13:31 TLE, Maximum recursion depth exceeded
- def bestTeamScore(self, scores: List[int], ages: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: Mar 18, 2023 13:31 TLE, Maximum recursion depth exceeded
- def bestTeamScore(self, scores: List[int], ages: Li... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
"""Mar 18, 2023 13:31 TLE, Maximum recursion depth exceeded"""
<|body_0|>
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
"""Mar 18, 2023 13:58"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
"""Mar 18, 2023 13:31 TLE, Maximum recursion depth exceeded"""
N = len(scores)
sa = sorted(zip(scores, ages), key=lambda sa: (sa[1], sa[0]))
@lru_cache(None)
def dfs(i, threshold):
... | the_stack_v2_python_sparse | leetcode/solved/1748_Best_Team_With_No_Conflicts/solution.py | sungminoh/algorithms | train | 0 | |
ba558d64aeefa21daae8d5fa9813438c4bfa0f18 | [
"super(fx.GraphModule, self).__init__()\nself.__class__.__name__ = class_name\nself.train_graph = train_graph\nself.eval_graph = eval_graph\nfor node in chain(iter(train_graph.nodes), iter(eval_graph.nodes)):\n if node.op in ['get_attr', 'call_module']:\n if not isinstance(node.target, str):\n ... | <|body_start_0|>
super(fx.GraphModule, self).__init__()
self.__class__.__name__ = class_name
self.train_graph = train_graph
self.eval_graph = eval_graph
for node in chain(iter(train_graph.nodes), iter(eval_graph.nodes)):
if node.op in ['get_attr', 'call_module']:
... | A derivative of `fx.GraphModule`. Differs in the following ways: - Requires a train and eval version of the underlying graph - Copies submodules according to the nodes of both train and eval graphs. - Calling train(mode) switches between train graph and eval graph. | DualGraphModule | [
"BSD-3-Clause",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualGraphModule:
"""A derivative of `fx.GraphModule`. Differs in the following ways: - Requires a train and eval version of the underlying graph - Copies submodules according to the nodes of both train and eval graphs. - Calling train(mode) switches between train graph and eval graph."""
def... | stack_v2_sparse_classes_36k_train_029092 | 25,577 | permissive | [
{
"docstring": "Args: root (nn.Module): module from which the copied module hierarchy is built train_graph (fx.Graph): the graph that should be used in train mode eval_graph (fx.Graph): the graph that should be used in eval mode",
"name": "__init__",
"signature": "def __init__(self, root: torch.nn.Modul... | 2 | null | Implement the Python class `DualGraphModule` described below.
Class description:
A derivative of `fx.GraphModule`. Differs in the following ways: - Requires a train and eval version of the underlying graph - Copies submodules according to the nodes of both train and eval graphs. - Calling train(mode) switches between ... | Implement the Python class `DualGraphModule` described below.
Class description:
A derivative of `fx.GraphModule`. Differs in the following ways: - Requires a train and eval version of the underlying graph - Copies submodules according to the nodes of both train and eval graphs. - Calling train(mode) switches between ... | 1f94320d8db8d102214a7dc02c22fa65ee9ac58a | <|skeleton|>
class DualGraphModule:
"""A derivative of `fx.GraphModule`. Differs in the following ways: - Requires a train and eval version of the underlying graph - Copies submodules according to the nodes of both train and eval graphs. - Calling train(mode) switches between train graph and eval graph."""
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DualGraphModule:
"""A derivative of `fx.GraphModule`. Differs in the following ways: - Requires a train and eval version of the underlying graph - Copies submodules according to the nodes of both train and eval graphs. - Calling train(mode) switches between train graph and eval graph."""
def __init__(sel... | the_stack_v2_python_sparse | torchvision/models/feature_extraction.py | pytorch/vision | train | 15,620 |
21d742e41aa04052e1d11888dab2f2ae0d5976ea | [
"device_obj = Device(context=context, type=self.type, vendor=self.vendor, model=self.model, hostname=host)\nif hasattr(self, 'std_board_info'):\n device_obj.std_board_info = self.std_board_info\nif hasattr(self, 'vendor_board_info'):\n device_obj.vendor_board_info = self.vendor_board_info\ndevice_obj.create(c... | <|body_start_0|>
device_obj = Device(context=context, type=self.type, vendor=self.vendor, model=self.model, hostname=host)
if hasattr(self, 'std_board_info'):
device_obj.std_board_info = self.std_board_info
if hasattr(self, 'vendor_board_info'):
device_obj.vendor_board_in... | DriverDevice | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverDevice:
def create(self, context, host):
"""Create a driver-side Device Object into DB. This object will be stored in many db tables: device, deployable, attach_handle, controlpath_id etc. by calling related Object."""
<|body_0|>
def destroy(self, context, host):
... | stack_v2_sparse_classes_36k_train_029093 | 7,119 | permissive | [
{
"docstring": "Create a driver-side Device Object into DB. This object will be stored in many db tables: device, deployable, attach_handle, controlpath_id etc. by calling related Object.",
"name": "create",
"signature": "def create(self, context, host)"
},
{
"docstring": "Delete a driver-side D... | 5 | stack_v2_sparse_classes_30k_train_016474 | Implement the Python class `DriverDevice` described below.
Class description:
Implement the DriverDevice class.
Method signatures and docstrings:
- def create(self, context, host): Create a driver-side Device Object into DB. This object will be stored in many db tables: device, deployable, attach_handle, controlpath_... | Implement the Python class `DriverDevice` described below.
Class description:
Implement the DriverDevice class.
Method signatures and docstrings:
- def create(self, context, host): Create a driver-side Device Object into DB. This object will be stored in many db tables: device, deployable, attach_handle, controlpath_... | ab8b8514242895b8adc2ec3dfbbb63a49f02c89e | <|skeleton|>
class DriverDevice:
def create(self, context, host):
"""Create a driver-side Device Object into DB. This object will be stored in many db tables: device, deployable, attach_handle, controlpath_id etc. by calling related Object."""
<|body_0|>
def destroy(self, context, host):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DriverDevice:
def create(self, context, host):
"""Create a driver-side Device Object into DB. This object will be stored in many db tables: device, deployable, attach_handle, controlpath_id etc. by calling related Object."""
device_obj = Device(context=context, type=self.type, vendor=self.vend... | the_stack_v2_python_sparse | cyborg/objects/driver_objects/driver_device.py | openstack/cyborg | train | 41 | |
4465bedab331f4fc1378cddb2d4933ed199d76f4 | [
"super(SuperRes, self).__init__()\nself.gf_dim = ngf\nself.n_residuals = n_residuals\nself.nc = nc\nself.define_module()",
"layers = []\nfor i in range(self.n_residuals):\n layers.append(block(in_channels))\nreturn nn.Sequential(*layers)",
"ngf = self.gf_dim\nself.encoder = nn.Sequential(nn.Conv2d(self.nc, n... | <|body_start_0|>
super(SuperRes, self).__init__()
self.gf_dim = ngf
self.n_residuals = n_residuals
self.nc = nc
self.define_module()
<|end_body_0|>
<|body_start_1|>
layers = []
for i in range(self.n_residuals):
layers.append(block(in_channels))
... | Super resolution stage class. Args: - ngf (int): dimension of the generators filters - n_residuals (int, optional): number of residual blocks used (Default: 5) - nc (int, optional): number of channels (Default: 3) | SuperRes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperRes:
"""Super resolution stage class. Args: - ngf (int): dimension of the generators filters - n_residuals (int, optional): number of residual blocks used (Default: 5) - nc (int, optional): number of channels (Default: 3)"""
def __init__(self, ngf, n_residuals=5, nc=3):
"""Initi... | stack_v2_sparse_classes_36k_train_029094 | 22,492 | no_license | [
{
"docstring": "Initialize the Super Resolution stage.",
"name": "__init__",
"signature": "def __init__(self, ngf, n_residuals=5, nc=3)"
},
{
"docstring": "Create a sequential model of <n_residuals> <block>.",
"name": "_make_layer",
"signature": "def _make_layer(self, block, in_channels)... | 4 | stack_v2_sparse_classes_30k_train_016276 | Implement the Python class `SuperRes` described below.
Class description:
Super resolution stage class. Args: - ngf (int): dimension of the generators filters - n_residuals (int, optional): number of residual blocks used (Default: 5) - nc (int, optional): number of channels (Default: 3)
Method signatures and docstrin... | Implement the Python class `SuperRes` described below.
Class description:
Super resolution stage class. Args: - ngf (int): dimension of the generators filters - n_residuals (int, optional): number of residual blocks used (Default: 5) - nc (int, optional): number of channels (Default: 3)
Method signatures and docstrin... | 70d344d80425e7bbcc7984737dbe50a6638293c9 | <|skeleton|>
class SuperRes:
"""Super resolution stage class. Args: - ngf (int): dimension of the generators filters - n_residuals (int, optional): number of residual blocks used (Default: 5) - nc (int, optional): number of channels (Default: 3)"""
def __init__(self, ngf, n_residuals=5, nc=3):
"""Initi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperRes:
"""Super resolution stage class. Args: - ngf (int): dimension of the generators filters - n_residuals (int, optional): number of residual blocks used (Default: 5) - nc (int, optional): number of channels (Default: 3)"""
def __init__(self, ngf, n_residuals=5, nc=3):
"""Initialize the Sup... | the_stack_v2_python_sparse | TeleGAN/model.py | ails-lab/teleGAN | train | 1 |
765f41b4953076d60696f39ed97239d2fe446025 | [
"input_tensor = tf.ones([1, 4, 4, 2])\noutput_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))\nself.assertAllEqual(output_tensor.shape, [1, 2, 2, 2])\nexpected = tf.constant([[[[-0.02436768, -0.27847868], [-0.0774256, -0.5111736]], [[0.50436425, -0.1713084], [0.2803106, -... | <|body_start_0|>
input_tensor = tf.ones([1, 4, 4, 2])
output_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))
self.assertAllEqual(output_tensor.shape, [1, 2, 2, 2])
expected = tf.constant([[[[-0.02436768, -0.27847868], [-0.0774256, -0.5111736]],... | CNNAutoencoderModelTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
<|body_0|>
def test_encoder_pool_list_values(self):
"""Tests encoder with default inputs."""
<|body_1|>
def test_encoder_batch_norm_all(self):
"""Te... | stack_v2_sparse_classes_36k_train_029095 | 4,774 | permissive | [
{
"docstring": "Tests encoder with default inputs.",
"name": "test_encoder_default",
"signature": "def test_encoder_default(self)"
},
{
"docstring": "Tests encoder with default inputs.",
"name": "test_encoder_pool_list_values",
"signature": "def test_encoder_pool_list_values(self)"
},
... | 5 | stack_v2_sparse_classes_30k_train_011008 | Implement the Python class `CNNAutoencoderModelTest` described below.
Class description:
Implement the CNNAutoencoderModelTest class.
Method signatures and docstrings:
- def test_encoder_default(self): Tests encoder with default inputs.
- def test_encoder_pool_list_values(self): Tests encoder with default inputs.
- d... | Implement the Python class `CNNAutoencoderModelTest` described below.
Class description:
Implement the CNNAutoencoderModelTest class.
Method signatures and docstrings:
- def test_encoder_default(self): Tests encoder with default inputs.
- def test_encoder_pool_list_values(self): Tests encoder with default inputs.
- d... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
<|body_0|>
def test_encoder_pool_list_values(self):
"""Tests encoder with default inputs."""
<|body_1|>
def test_encoder_batch_norm_all(self):
"""Te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
input_tensor = tf.ones([1, 4, 4, 2])
output_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))
self.assertAllEqual(output_tensor.shape, [1,... | the_stack_v2_python_sparse | simulation_research/next_day_wildfire_spread/models/cnn_autoencoder_model_test.py | Jimmy-INL/google-research | train | 1 | |
54aec544a87aca0ce9584dd00f0169e4737c4968 | [
"valList = []\n\ndef recur(node):\n if node:\n valList.append(str(node.val))\n recur(node.left)\n recur(node.right)\n else:\n valList.append('#')\nrecur(root)\nreturn ','.join(valList)",
"value = iter(data.split(','))\n\ndef recur():\n val = next(value)\n if val == '#':\n ... | <|body_start_0|>
valList = []
def recur(node):
if node:
valList.append(str(node.val))
recur(node.left)
recur(node.right)
else:
valList.append('#')
recur(root)
return ','.join(valList)
<|end_body_0|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_029096 | 10,317 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006747 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | c784832fbc98aad6fdda5beabb04b416d761b5b1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
valList = []
def recur(node):
if node:
valList.append(str(node.val))
recur(node.left)
recur(node.right)
e... | the_stack_v2_python_sparse | 06-树 二叉树 二叉搜索树/binary-tree.py | hhiccup/algorithom-python | train | 0 | |
17f66a5820fb08adfedbed7f5624f89fa0cd72cc | [
"endpoint = url_path_join(RESOURCES_RESOURCE_URL, self.owner, LS_RESOURCE_URL, *path.split('/'))\nwith self.request('get', endpoint, stream=True) as ls_stream:\n self.check_and_raise(ls_stream)\n if ls_stream.encoding is None:\n ls_stream.encoding = 'utf-8'\n for chunk in ls_stream.iter_lines(decode... | <|body_start_0|>
endpoint = url_path_join(RESOURCES_RESOURCE_URL, self.owner, LS_RESOURCE_URL, *path.split('/'))
with self.request('get', endpoint, stream=True) as ls_stream:
self.check_and_raise(ls_stream)
if ls_stream.encoding is None:
ls_stream.encoding = 'utf-... | ResourcesClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourcesClient:
def get_ls(self, path):
"""Get file list from Spell. Keyword arguments: path -- the path to list the contents of Returns: a generator for file details"""
<|body_0|>
def tar_of_path(self, path):
"""Get a tar of the resource path. Keyword arguments: so... | stack_v2_sparse_classes_36k_train_029097 | 2,756 | no_license | [
{
"docstring": "Get file list from Spell. Keyword arguments: path -- the path to list the contents of Returns: a generator for file details",
"name": "get_ls",
"signature": "def get_ls(self, path)"
},
{
"docstring": "Get a tar of the resource path. Keyword arguments: source_path -- a single file... | 2 | null | Implement the Python class `ResourcesClient` described below.
Class description:
Implement the ResourcesClient class.
Method signatures and docstrings:
- def get_ls(self, path): Get file list from Spell. Keyword arguments: path -- the path to list the contents of Returns: a generator for file details
- def tar_of_pat... | Implement the Python class `ResourcesClient` described below.
Class description:
Implement the ResourcesClient class.
Method signatures and docstrings:
- def get_ls(self, path): Get file list from Spell. Keyword arguments: path -- the path to list the contents of Returns: a generator for file details
- def tar_of_pat... | 3aa64414c47534534bc6063185e3e6692a97e8a5 | <|skeleton|>
class ResourcesClient:
def get_ls(self, path):
"""Get file list from Spell. Keyword arguments: path -- the path to list the contents of Returns: a generator for file details"""
<|body_0|>
def tar_of_path(self, path):
"""Get a tar of the resource path. Keyword arguments: so... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourcesClient:
def get_ls(self, path):
"""Get file list from Spell. Keyword arguments: path -- the path to list the contents of Returns: a generator for file details"""
endpoint = url_path_join(RESOURCES_RESOURCE_URL, self.owner, LS_RESOURCE_URL, *path.split('/'))
with self.request('... | the_stack_v2_python_sparse | env/Lib/site-packages/spell/api/resources_client.py | Kendubu1/NLP-Flask-Website | train | 0 | |
3332f40223004e1be18d1012f79910850736edf9 | [
"defined_fields = self.form.used_field_names\nrequired_fields = self.form.get_required_field_names()\nmissing_fields = []\nfor field in required_fields:\n if field not in defined_fields:\n missing_fields.append(field)\nif len(missing_fields) > 0:\n raise ValidationError('The save instance handler can o... | <|body_start_0|>
defined_fields = self.form.used_field_names
required_fields = self.form.get_required_field_names()
missing_fields = []
for field in required_fields:
if field not in defined_fields:
missing_fields.append(field)
if len(missing_fields) > ... | Handler for saving the form instance | OmniFormSaveInstanceHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OmniFormSaveInstanceHandler:
"""Handler for saving the form instance"""
def assert_has_all_required_fields(self):
"""Property that determines whether or not the associated form defines all of the required fields :raises: ValidationError"""
<|body_0|>
def clean(self):
... | stack_v2_sparse_classes_36k_train_029098 | 47,532 | permissive | [
{
"docstring": "Property that determines whether or not the associated form defines all of the required fields :raises: ValidationError",
"name": "assert_has_all_required_fields",
"signature": "def assert_has_all_required_fields(self)"
},
{
"docstring": "Cleans the handler for saving a model ins... | 3 | stack_v2_sparse_classes_30k_val_000949 | Implement the Python class `OmniFormSaveInstanceHandler` described below.
Class description:
Handler for saving the form instance
Method signatures and docstrings:
- def assert_has_all_required_fields(self): Property that determines whether or not the associated form defines all of the required fields :raises: Valida... | Implement the Python class `OmniFormSaveInstanceHandler` described below.
Class description:
Handler for saving the form instance
Method signatures and docstrings:
- def assert_has_all_required_fields(self): Property that determines whether or not the associated form defines all of the required fields :raises: Valida... | 0c96162445f8b5ddf7f326f6b0a2e6ec239c4bd5 | <|skeleton|>
class OmniFormSaveInstanceHandler:
"""Handler for saving the form instance"""
def assert_has_all_required_fields(self):
"""Property that determines whether or not the associated form defines all of the required fields :raises: ValidationError"""
<|body_0|>
def clean(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OmniFormSaveInstanceHandler:
"""Handler for saving the form instance"""
def assert_has_all_required_fields(self):
"""Property that determines whether or not the associated form defines all of the required fields :raises: ValidationError"""
defined_fields = self.form.used_field_names
... | the_stack_v2_python_sparse | omniforms/models.py | omni-digital/omni-forms | train | 6 |
23885620ff0ef8f70d2d8bc5d8f2e0f0c21f5447 | [
"try:\n user = await get_data_from_req(self.request).administrators.get(user_id)\nexcept ResourceNotFoundError:\n raise NotFound()\nreturn json_response(user)",
"if not await check_can_edit_user(get_authorization_client_from_req(self.request), self.request['client'].user_id, user_id):\n raise HTTPForbidd... | <|body_start_0|>
try:
user = await get_data_from_req(self.request).administrators.get(user_id)
except ResourceNotFoundError:
raise NotFound()
return json_response(user)
<|end_body_0|>
<|body_start_1|>
if not await check_can_edit_user(get_authorization_client_from... | AdminUserView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminUserView:
async def get(self, user_id: str, /) -> Union[r200[UserResponse], r404]:
"""Get a user. Fetches the details of a user. Status Codes: 200: Successful operation 404: User not found"""
<|body_0|>
async def patch(self, user_id: str, /, data: UpdateUserRequest) -> ... | stack_v2_sparse_classes_36k_train_029099 | 6,189 | permissive | [
{
"docstring": "Get a user. Fetches the details of a user. Status Codes: 200: Successful operation 404: User not found",
"name": "get",
"signature": "async def get(self, user_id: str, /) -> Union[r200[UserResponse], r404]"
},
{
"docstring": "Update a user. Status Codes: 200: Successful operation... | 2 | stack_v2_sparse_classes_30k_train_003278 | Implement the Python class `AdminUserView` described below.
Class description:
Implement the AdminUserView class.
Method signatures and docstrings:
- async def get(self, user_id: str, /) -> Union[r200[UserResponse], r404]: Get a user. Fetches the details of a user. Status Codes: 200: Successful operation 404: User no... | Implement the Python class `AdminUserView` described below.
Class description:
Implement the AdminUserView class.
Method signatures and docstrings:
- async def get(self, user_id: str, /) -> Union[r200[UserResponse], r404]: Get a user. Fetches the details of a user. Status Codes: 200: Successful operation 404: User no... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class AdminUserView:
async def get(self, user_id: str, /) -> Union[r200[UserResponse], r404]:
"""Get a user. Fetches the details of a user. Status Codes: 200: Successful operation 404: User not found"""
<|body_0|>
async def patch(self, user_id: str, /, data: UpdateUserRequest) -> ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminUserView:
async def get(self, user_id: str, /) -> Union[r200[UserResponse], r404]:
"""Get a user. Fetches the details of a user. Status Codes: 200: Successful operation 404: User not found"""
try:
user = await get_data_from_req(self.request).administrators.get(user_id)
... | the_stack_v2_python_sparse | virtool/administrators/api.py | virtool/virtool | train | 45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.