blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
78e6856f3e071d788aee7aafa65209f7fc0fb112 | [
"if not isinstance(two_qudit_gate, Gate):\n raise TypeError('Expected gate for two_qudit_gate, got %s.' % type(two_qudit_gate))\nif two_qudit_gate.num_qudits != 2:\n raise ValueError('Expected two-qudit gate, got a gate that acts on %d qudits.' % two_qudit_gate.num_qudits)\nif not isinstance(single_qudit_gate... | <|body_start_0|>
if not isinstance(two_qudit_gate, Gate):
raise TypeError('Expected gate for two_qudit_gate, got %s.' % type(two_qudit_gate))
if two_qudit_gate.num_qudits != 2:
raise ValueError('Expected two-qudit gate, got a gate that acts on %d qudits.' % two_qudit_gate.num_qud... | The SimpleLayerGenerator class. Starts a circuit by placing a single-qudit gate on each qudit. Expands a circuit by placing a two-qudit building block on all valid links. Each building block is composed of a two-qudit gate followed by two single-qudit gates. | SimpleLayerGenerator | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleLayerGenerator:
"""The SimpleLayerGenerator class. Starts a circuit by placing a single-qudit gate on each qudit. Expands a circuit by placing a two-qudit building block on all valid links. Each building block is composed of a two-qudit gate followed by two single-qudit gates."""
def _... | stack_v2_sparse_classes_75kplus_train_073300 | 7,161 | permissive | [
{
"docstring": "Construct a SimpleLayerGenerator. Args: two_qudit_gate (Gate): A two-qudit gate that starts this layer generator's building block. (Default: CNOTGate()) single_qudit_gate_1 (Gate): A single-qudit gate that follows `two_qudit_gate` in the building block. (Default: U3Gate()) single_qudit_gate_2 (G... | 3 | stack_v2_sparse_classes_30k_train_013538 | Implement the Python class `SimpleLayerGenerator` described below.
Class description:
The SimpleLayerGenerator class. Starts a circuit by placing a single-qudit gate on each qudit. Expands a circuit by placing a two-qudit building block on all valid links. Each building block is composed of a two-qudit gate followed b... | Implement the Python class `SimpleLayerGenerator` described below.
Class description:
The SimpleLayerGenerator class. Starts a circuit by placing a single-qudit gate on each qudit. Expands a circuit by placing a two-qudit building block on all valid links. Each building block is composed of a two-qudit gate followed b... | c89112d15072e8ffffb68cf1757b184e2aeb3dc8 | <|skeleton|>
class SimpleLayerGenerator:
"""The SimpleLayerGenerator class. Starts a circuit by placing a single-qudit gate on each qudit. Expands a circuit by placing a two-qudit building block on all valid links. Each building block is composed of a two-qudit gate followed by two single-qudit gates."""
def _... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleLayerGenerator:
"""The SimpleLayerGenerator class. Starts a circuit by placing a single-qudit gate on each qudit. Expands a circuit by placing a two-qudit building block on all valid links. Each building block is composed of a two-qudit gate followed by two single-qudit gates."""
def __init__(self,... | the_stack_v2_python_sparse | bqskit/passes/search/generators/simple.py | BQSKit/bqskit | train | 54 |
093cb63b9bbe69ba7e87c92ff6cdc3111d86a772 | [
"fields = list(super().get_fields(request, model_instance))\nordered_field_names = reversed(['notes', 'type', 'title', 'slug', 'summary', 'certainty', 'elaboration'])\nfor field_name in ordered_field_names:\n if field_name in fields:\n fields.remove(field_name)\n fields.insert(0, field_name)\nretur... | <|body_start_0|>
fields = list(super().get_fields(request, model_instance))
ordered_field_names = reversed(['notes', 'type', 'title', 'slug', 'summary', 'certainty', 'elaboration'])
for field_name in ordered_field_names:
if field_name in fields:
fields.remove(field_na... | Model admin for searchable models. | SearchableModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchableModelAdmin:
"""Model admin for searchable models."""
def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]:
"""Return reordered fields to be displayed in the admin."""
<|body_0|>
def get_fieldsets(self, requ... | stack_v2_sparse_classes_75kplus_train_073301 | 4,473 | no_license | [
{
"docstring": "Return reordered fields to be displayed in the admin.",
"name": "get_fields",
"signature": "def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]"
},
{
"docstring": "Return the fieldsets to be displayed in the admin form.",
... | 3 | stack_v2_sparse_classes_30k_train_053483 | Implement the Python class `SearchableModelAdmin` described below.
Class description:
Model admin for searchable models.
Method signatures and docstrings:
- def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]: Return reordered fields to be displayed in the admin... | Implement the Python class `SearchableModelAdmin` described below.
Class description:
Model admin for searchable models.
Method signatures and docstrings:
- def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]: Return reordered fields to be displayed in the admin... | 8bbdc8eec3622af22c17214051c34e36bea8e05a | <|skeleton|>
class SearchableModelAdmin:
"""Model admin for searchable models."""
def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]:
"""Return reordered fields to be displayed in the admin."""
<|body_0|>
def get_fieldsets(self, requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchableModelAdmin:
"""Model admin for searchable models."""
def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]:
"""Return reordered fields to be displayed in the admin."""
fields = list(super().get_fields(request, model_instance)... | the_stack_v2_python_sparse | apps/search/admin.py | abdulwahed-mansour/modularhistory | train | 1 |
cd3de1c65c71755ea5ee5cca6f3a441f5c7fc391 | [
"self.tc = tc\nself.tau = tau\nself._fwhm = tau * 2.3548200450309493\nself.sigma = tau\nself.omegac = omegac\nself.unit = 'au'\nself.amplitude = amplitude\nself.cep = cep\nself.bandwidth = 1.0 / tau\nself.duration = 2.0 * tau\nself.beta = beta\nself.ndim = 1",
"omegac = self.omegac\nt0 = self.tc\na = self.amplitu... | <|body_start_0|>
self.tc = tc
self.tau = tau
self._fwhm = tau * 2.3548200450309493
self.sigma = tau
self.omegac = omegac
self.unit = 'au'
self.amplitude = amplitude
self.cep = cep
self.bandwidth = 1.0 / tau
self.duration = 2.0 * tau
... | ChirpedPulse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChirpedPulse:
def __init__(self, omegac=3.0 / au2ev, tau=5.0 / au2fs, tc=0, amplitude=0.001, cep=0.0, beta=0):
"""(linearly chirped) Gaussian pulse The positive frequency component reads E = A/2 * exp(-(t-t0)^2/2/T^2) * exp[-i w (t-t0)(1 + beta (t-t0)/T)] A: electric field amplitude T: t... | stack_v2_sparse_classes_75kplus_train_073302 | 20,723 | permissive | [
{
"docstring": "(linearly chirped) Gaussian pulse The positive frequency component reads E = A/2 * exp(-(t-t0)^2/2/T^2) * exp[-i w (t-t0)(1 + beta (t-t0)/T)] A: electric field amplitude T: time delay sigma: duration",
"name": "__init__",
"signature": "def __init__(self, omegac=3.0 / au2ev, tau=5.0 / au2... | 3 | null | Implement the Python class `ChirpedPulse` described below.
Class description:
Implement the ChirpedPulse class.
Method signatures and docstrings:
- def __init__(self, omegac=3.0 / au2ev, tau=5.0 / au2fs, tc=0, amplitude=0.001, cep=0.0, beta=0): (linearly chirped) Gaussian pulse The positive frequency component reads ... | Implement the Python class `ChirpedPulse` described below.
Class description:
Implement the ChirpedPulse class.
Method signatures and docstrings:
- def __init__(self, omegac=3.0 / au2ev, tau=5.0 / au2fs, tc=0, amplitude=0.001, cep=0.0, beta=0): (linearly chirped) Gaussian pulse The positive frequency component reads ... | 3f7ce3d8411a23186c73f1bb87a8778e039fbd0b | <|skeleton|>
class ChirpedPulse:
def __init__(self, omegac=3.0 / au2ev, tau=5.0 / au2fs, tc=0, amplitude=0.001, cep=0.0, beta=0):
"""(linearly chirped) Gaussian pulse The positive frequency component reads E = A/2 * exp(-(t-t0)^2/2/T^2) * exp[-i w (t-t0)(1 + beta (t-t0)/T)] A: electric field amplitude T: t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChirpedPulse:
def __init__(self, omegac=3.0 / au2ev, tau=5.0 / au2fs, tc=0, amplitude=0.001, cep=0.0, beta=0):
"""(linearly chirped) Gaussian pulse The positive frequency component reads E = A/2 * exp(-(t-t0)^2/2/T^2) * exp[-i w (t-t0)(1 + beta (t-t0)/T)] A: electric field amplitude T: time delay sigm... | the_stack_v2_python_sparse | lime/optics.py | binggu56/lime | train | 7 | |
c6de360bf41c9355f40b473e272c90d6450a3203 | [
"self.options = options\nself.arguments = arguments\nself.start_arguments = start_arguments\nsuper().__init__(**kwargs)",
"content = self.dumps_content()\nif not content.strip() and self.omit_if_empty:\n return ''\nstring = ''\nif self.arguments is None:\n extra_arguments = Arguments()\nelse:\n extra_arg... | <|body_start_0|>
self.options = options
self.arguments = arguments
self.start_arguments = start_arguments
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
content = self.dumps_content()
if not content.strip() and self.omit_if_empty:
return ''
... | A base class for LaTeX environments. This class implements the basics of a LaTeX environment. A LaTeX environment looks like this: .. code-block:: latex \\begin{environment_name} Some content that is in the environment \\end{environment_name} The text that is used in the place of environment_name is by default the name... | Environment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Environment:
"""A base class for LaTeX environments. This class implements the basics of a LaTeX environment. A LaTeX environment looks like this: .. code-block:: latex \\begin{environment_name} Some content that is in the environment \\end{environment_name} The text that is used in the place of ... | stack_v2_sparse_classes_75kplus_train_073303 | 7,535 | permissive | [
{
"docstring": "Args ---- options: str or list or `~.Options` Options to be added to the ``\\\\begin`` command arguments: str or list or `~.Arguments` Arguments to be added to the ``\\\\begin`` command start_arguments: str or list or `~.Arguments` Arguments to be added before the options",
"name": "__init__... | 2 | null | Implement the Python class `Environment` described below.
Class description:
A base class for LaTeX environments. This class implements the basics of a LaTeX environment. A LaTeX environment looks like this: .. code-block:: latex \\begin{environment_name} Some content that is in the environment \\end{environment_name}... | Implement the Python class `Environment` described below.
Class description:
A base class for LaTeX environments. This class implements the basics of a LaTeX environment. A LaTeX environment looks like this: .. code-block:: latex \\begin{environment_name} Some content that is in the environment \\end{environment_name}... | 2050b14d8d7ed4fe788c769afec6816e2b703355 | <|skeleton|>
class Environment:
"""A base class for LaTeX environments. This class implements the basics of a LaTeX environment. A LaTeX environment looks like this: .. code-block:: latex \\begin{environment_name} Some content that is in the environment \\end{environment_name} The text that is used in the place of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Environment:
"""A base class for LaTeX environments. This class implements the basics of a LaTeX environment. A LaTeX environment looks like this: .. code-block:: latex \\begin{environment_name} Some content that is in the environment \\end{environment_name} The text that is used in the place of environment_n... | the_stack_v2_python_sparse | pylatex/base_classes/containers.py | JelteF/PyLaTeX | train | 2,104 |
339e68390dc14fea4990647f1f9ddeb6d0aee584 | [
"if not email:\n raise ValueError(_('The Email must be set'))\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_staff', True)\nextra_fields.setdefault('is_superuser', True)\nextra_fields.set... | <|body_start_0|>
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
extra_fi... | Custom user model manager where email is the unique identifiers for authentication instead of usernames. | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus_train_073304 | 3,185 | no_license | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password, **extra_fields)"
},
{
"docstring": "Create and save a SuperUser with the given email and password.",
"name": "create_superuser",
"signat... | 2 | null | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | 96b77a81c6ac8b70e3c10fcb65c041bab0ce43e9 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueEr... | the_stack_v2_python_sparse | tlog_app/models.py | a007k/myProject | train | 1 |
e0824c73db8b23c8218c1951193e344ce18110ad | [
"provider = get_provider()\nif provider.PROVIDER_NAME != ONPREM:\n return provider.get_func_region()\nraise ProviderException('no region defined')",
"dbg = 'false'\nif settings.SSM_CONFIG is None:\n return dbg\ntry:\n DEBUG_LOG = settings.SSM_CONFIG.get_param('DEBUG_LOG')\n dbg = DEBUG_LOG['val']\n ... | <|body_start_0|>
provider = get_provider()
if provider.PROVIDER_NAME != ONPREM:
return provider.get_func_region()
raise ProviderException('no region defined')
<|end_body_0|>
<|body_start_1|>
dbg = 'false'
if settings.SSM_CONFIG is None:
return dbg
... | ProviderUtil | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProviderUtil:
def get_func_region():
""":return:"""
<|body_0|>
def get_debug_param():
""":return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
provider = get_provider()
if provider.PROVIDER_NAME != ONPREM:
return provider.get_... | stack_v2_sparse_classes_75kplus_train_073305 | 1,288 | permissive | [
{
"docstring": ":return:",
"name": "get_func_region",
"signature": "def get_func_region()"
},
{
"docstring": ":return:",
"name": "get_debug_param",
"signature": "def get_debug_param()"
}
] | 2 | stack_v2_sparse_classes_30k_test_001024 | Implement the Python class `ProviderUtil` described below.
Class description:
Implement the ProviderUtil class.
Method signatures and docstrings:
- def get_func_region(): :return:
- def get_debug_param(): :return: | Implement the Python class `ProviderUtil` described below.
Class description:
Implement the ProviderUtil class.
Method signatures and docstrings:
- def get_func_region(): :return:
- def get_debug_param(): :return:
<|skeleton|>
class ProviderUtil:
def get_func_region():
""":return:"""
<|body_0|>
... | 98e057b2f433d97d903589ac75a6c2544174bac8 | <|skeleton|>
class ProviderUtil:
def get_func_region():
""":return:"""
<|body_0|>
def get_debug_param():
""":return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProviderUtil:
def get_func_region():
""":return:"""
provider = get_provider()
if provider.PROVIDER_NAME != ONPREM:
return provider.get_func_region()
raise ProviderException('no region defined')
def get_debug_param():
""":return:"""
dbg = 'false'... | the_stack_v2_python_sparse | halo_app/infra/providers/util.py | halo-framework/halo-app | train | 0 | |
0f8df2cb216af96101232d2d9192d337726afab7 | [
"super().__init__()\nself.redis_conn_id = redis_conn_id\nself.redis = None\nself.host = None\nself.port = None\nself.password = None\nself.db = None",
"conn = self.get_connection(self.redis_conn_id)\nself.host = conn.host\nself.port = conn.port\nself.password = None if str(conn.password).lower() in ['none', 'fals... | <|body_start_0|>
super().__init__()
self.redis_conn_id = redis_conn_id
self.redis = None
self.host = None
self.port = None
self.password = None
self.db = None
<|end_body_0|>
<|body_start_1|>
conn = self.get_connection(self.redis_conn_id)
self.host... | Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``. | RedisHook | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisHook:
"""Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``."""
... | stack_v2_sparse_classes_75kplus_train_073306 | 2,945 | permissive | [
{
"docstring": "Prepares hook to connect to a Redis database. :param conn_id: the name of the connection that has the parameters we need to connect to Redis.",
"name": "__init__",
"signature": "def __init__(self, redis_conn_id: str=default_conn_name) -> None"
},
{
"docstring": "Returns a Redis c... | 2 | stack_v2_sparse_classes_30k_val_001725 | Implement the Python class `RedisHook` described below.
Class description:
Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_... | Implement the Python class `RedisHook` described below.
Class description:
Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_... | 1b122c15030e99cef9d4ff26d3781a7a9d6949bc | <|skeleton|>
class RedisHook:
"""Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedisHook:
"""Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``."""
def __in... | the_stack_v2_python_sparse | airflow/providers/redis/hooks/redis.py | apache/airflow | train | 22,756 |
bd671bf6179843cf56ca9470dcd96742782a27a2 | [
"ioc = GreaseContainer()\nif configuration.get('hour'):\n if datetime.datetime.utcnow().hour != int(configuration.get('hour')):\n return True\nif configuration.get('minute'):\n if datetime.datetime.utcnow().minute != int(configuration.get('minute')):\n return True\nif configuration.get('type') !... | <|body_start_0|>
ioc = GreaseContainer()
if configuration.get('hour'):
if datetime.datetime.utcnow().hour != int(configuration.get('hour')):
return True
if configuration.get('minute'):
if datetime.datetime.utcnow().minute != int(configuration.get('minute')... | Source data from a SQL Database This Source is designed to query a SQL Server for data. A generic configuration looks like this for a sql_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run 'exe_env': 'general', # <-- Selected execution environment; Can be anything! 'so... | SQLSource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLSource:
"""Source data from a SQL Database This Source is designed to query a SQL Server for data. A generic configuration looks like this for a sql_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run 'exe_env': 'general', # <-- Selected execut... | stack_v2_sparse_classes_75kplus_train_073307 | 5,172 | permissive | [
{
"docstring": "This will Query the SQL Server to find data Args: configuration (dict): Configuration of Source. See Class Documentation above for more info Returns: bool: If True data will be scheduled for ingestion after deduplication. If False the engine will bail out",
"name": "parse_source",
"signa... | 2 | stack_v2_sparse_classes_30k_train_024561 | Implement the Python class `SQLSource` described below.
Class description:
Source data from a SQL Database This Source is designed to query a SQL Server for data. A generic configuration looks like this for a sql_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run 'exe... | Implement the Python class `SQLSource` described below.
Class description:
Source data from a SQL Database This Source is designed to query a SQL Server for data. A generic configuration looks like this for a sql_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run 'exe... | 7ebf3df71d5c80a8ed9df44d9b64b735a9d0f899 | <|skeleton|>
class SQLSource:
"""Source data from a SQL Database This Source is designed to query a SQL Server for data. A generic configuration looks like this for a sql_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run 'exe_env': 'general', # <-- Selected execut... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SQLSource:
"""Source data from a SQL Database This Source is designed to query a SQL Server for data. A generic configuration looks like this for a sql_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run 'exe_env': 'general', # <-- Selected execution environme... | the_stack_v2_python_sparse | tgt_grease/enterprise/Sources/SQLSearch.py | target/grease | train | 46 |
a58b1024820dfe93db8a0816b54892ba8303acc8 | [
"interactive_interface.InteractiveInterface.__init__(self, default_rule_blacklist, default_rules, all_targets)\nself.pulled = self.active\nself.pull_all = self.add_all\nself.unpull_all = self.remove_all",
"pulled = utils.create_empty_connection_type_dictionary()\nnew_pulls = utils.create_empty_connection_type_dic... | <|body_start_0|>
interactive_interface.InteractiveInterface.__init__(self, default_rule_blacklist, default_rules, all_targets)
self.pulled = self.active
self.pull_all = self.add_all
self.unpull_all = self.remove_all
<|end_body_0|>
<|body_start_1|>
pulled = utils.create_empty_con... | The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways. | PulledInterface | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PulledInterface:
"""The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways."""
def __init__(self, default_rule_blacklist, default_rules, all_targets):
"""Initialises the pulled interface. @param default_rule_blacklist : u... | stack_v2_sparse_classes_75kplus_train_073308 | 7,732 | permissive | [
{
"docstring": "Initialises the pulled interface. @param default_rule_blacklist : used when in flip all mode @type dictionary of gateway @param default_rules : static rules to pull on startup @type gateway_msgs.msg.RemoteRule[] @param all_targets : static pull all targets to pull to on startup @type string[]",
... | 4 | stack_v2_sparse_classes_30k_train_011442 | Implement the Python class `PulledInterface` described below.
Class description:
The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways.
Method signatures and docstrings:
- def __init__(self, default_rule_blacklist, default_rules, all_targets): Initialise... | Implement the Python class `PulledInterface` described below.
Class description:
The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways.
Method signatures and docstrings:
- def __init__(self, default_rule_blacklist, default_rules, all_targets): Initialise... | 4a835a04b469360b11243405d4d1f19b706c510d | <|skeleton|>
class PulledInterface:
"""The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways."""
def __init__(self, default_rule_blacklist, default_rules, all_targets):
"""Initialises the pulled interface. @param default_rule_blacklist : u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PulledInterface:
"""The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways."""
def __init__(self, default_rule_blacklist, default_rules, all_targets):
"""Initialises the pulled interface. @param default_rule_blacklist : used when in f... | the_stack_v2_python_sparse | rocon_multimaster/rocon_gateway/src/rocon_gateway/pulled_interface.py | Playfish/cafe_demo | train | 0 |
e0076ffc2e5a25011085118bd93a86122f31dbdd | [
"super(AsymmetricSimilarityLoss2D, self).__init__()\nself.beta = beta\nself.weight = weight\nself.ignore_index = ignore_index",
"eps = 1e-08\nbeta = self.beta ** 2\npredictions = F.softmax(predictions, dim=1)\nencoded_target = predictions.detach() * 0\nmask = None\nif self.ignore_index is not None:\n mask = ta... | <|body_start_0|>
super(AsymmetricSimilarityLoss2D, self).__init__()
self.beta = beta
self.weight = weight
self.ignore_index = ignore_index
<|end_body_0|>
<|body_start_1|>
eps = 1e-08
beta = self.beta ** 2
predictions = F.softmax(predictions, dim=1)
encode... | AsymmetricSimilarityLoss2D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsymmetricSimilarityLoss2D:
def __init__(self, beta=0.6, weight=None, ignore_index=-100):
"""Tversky Loss for Semantic Segmentation :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optional> A manual rescaling weight given to each class. If given... | stack_v2_sparse_classes_75kplus_train_073309 | 35,592 | permissive | [
{
"docstring": "Tversky Loss for Semantic Segmentation :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optional> A manual rescaling weight given to each class. If given, has to be a Tensor of size C, where C = number of classes. :param ignore_index: <int, optional> Spe... | 2 | stack_v2_sparse_classes_30k_train_017367 | Implement the Python class `AsymmetricSimilarityLoss2D` described below.
Class description:
Implement the AsymmetricSimilarityLoss2D class.
Method signatures and docstrings:
- def __init__(self, beta=0.6, weight=None, ignore_index=-100): Tversky Loss for Semantic Segmentation :param beta: <int> Parameter to control p... | Implement the Python class `AsymmetricSimilarityLoss2D` described below.
Class description:
Implement the AsymmetricSimilarityLoss2D class.
Method signatures and docstrings:
- def __init__(self, beta=0.6, weight=None, ignore_index=-100): Tversky Loss for Semantic Segmentation :param beta: <int> Parameter to control p... | ed226e5454b2144063a6d8132b07c90e6a64e2d3 | <|skeleton|>
class AsymmetricSimilarityLoss2D:
def __init__(self, beta=0.6, weight=None, ignore_index=-100):
"""Tversky Loss for Semantic Segmentation :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optional> A manual rescaling weight given to each class. If given... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AsymmetricSimilarityLoss2D:
def __init__(self, beta=0.6, weight=None, ignore_index=-100):
"""Tversky Loss for Semantic Segmentation :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optional> A manual rescaling weight given to each class. If given, has to be a ... | the_stack_v2_python_sparse | utils/losses.py | tansyab1/LightNetPlus | train | 0 | |
8816d12a683a130d59ef1d4f21b526dedb704167 | [
"super(DecoderRNN, self).__init__()\nself.embed = nn.Embedding(vocab_size, embed_size)\nself.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)\nself.linear = nn.Linear(hidden_size, vocab_size)\nself.max_seg_length = max_seq_length",
"embeddings = self.embed(captions)\nembeddings = torch.cat((f... | <|body_start_0|>
super(DecoderRNN, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
self.linear = nn.Linear(hidden_size, vocab_size)
self.max_seg_length = max_seq_length
<|end_body_0|>
<... | DecoderRNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderRNN:
def __init__(self, embed_size=256, hidden_size=512, vocab_size=len(vocab), num_layers=1, max_seq_length=20):
"""Set the hyper-parameters and build the layers."""
<|body_0|>
def forward(self, features, captions, lengths):
"""Decode image feature vectors an... | stack_v2_sparse_classes_75kplus_train_073310 | 12,981 | no_license | [
{
"docstring": "Set the hyper-parameters and build the layers.",
"name": "__init__",
"signature": "def __init__(self, embed_size=256, hidden_size=512, vocab_size=len(vocab), num_layers=1, max_seq_length=20)"
},
{
"docstring": "Decode image feature vectors and generates captions.",
"name": "f... | 3 | stack_v2_sparse_classes_30k_train_013399 | Implement the Python class `DecoderRNN` described below.
Class description:
Implement the DecoderRNN class.
Method signatures and docstrings:
- def __init__(self, embed_size=256, hidden_size=512, vocab_size=len(vocab), num_layers=1, max_seq_length=20): Set the hyper-parameters and build the layers.
- def forward(self... | Implement the Python class `DecoderRNN` described below.
Class description:
Implement the DecoderRNN class.
Method signatures and docstrings:
- def __init__(self, embed_size=256, hidden_size=512, vocab_size=len(vocab), num_layers=1, max_seq_length=20): Set the hyper-parameters and build the layers.
- def forward(self... | 016dde83b2e7045615739670bdf5b5cc468fd63d | <|skeleton|>
class DecoderRNN:
def __init__(self, embed_size=256, hidden_size=512, vocab_size=len(vocab), num_layers=1, max_seq_length=20):
"""Set the hyper-parameters and build the layers."""
<|body_0|>
def forward(self, features, captions, lengths):
"""Decode image feature vectors an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderRNN:
def __init__(self, embed_size=256, hidden_size=512, vocab_size=len(vocab), num_layers=1, max_seq_length=20):
"""Set the hyper-parameters and build the layers."""
super(DecoderRNN, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM... | the_stack_v2_python_sparse | Image_captioning/get_datasets.py | nileshpd1211/CSE253_DeepLearning | train | 0 | |
40814c796e0ccffa976ed6474946ca42a0b00e20 | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"query = s_prev\nvalues = hidden_states\nquery_with_time_axis = tf.expand_dims(query, 1)\nscore = self.V(tf.nn.tanh(self.W(query_with_time_axis) + self.U(values... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
query = s_prev
values = hidden_states
query_with_time_axis = tf.ex... | This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf | SelfAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf"""
def __init__(self, units):
"""All begins here"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""This method call SelfAttention"""
... | stack_v2_sparse_classes_75kplus_train_073311 | 1,730 | permissive | [
{
"docstring": "All begins here",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "This method call SelfAttention",
"name": "call",
"signature": "def call(self, s_prev, hidden_states)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035358 | Implement the Python class `SelfAttention` described below.
Class description:
This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf
Method signatures and docstrings:
- def __init__(self, units): All begins here
- def call(self, s_prev, hidden_states): This method ca... | Implement the Python class `SelfAttention` described below.
Class description:
This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf
Method signatures and docstrings:
- def __init__(self, units): All begins here
- def call(self, s_prev, hidden_states): This method ca... | 58c367f3014919f95157426121093b9fe14d4035 | <|skeleton|>
class SelfAttention:
"""This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf"""
def __init__(self, units):
"""All begins here"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""This method call SelfAttention"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
"""This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf"""
def __init__(self, units):
"""All begins here"""
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.laye... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | linkem97/holbertonschool-machine_learning | train | 0 |
98c5c5c7f259c1c0fbb5170bbeb34e08b6b3181f | [
"sleep(2)\ntype_string = os.path.join(os.getcwd(), TESTDATA[section1][u'data_folder'], TESTDATA[section2][u'tsa_cert_file_name'])\nprint(type_string)\nself.common_lib.type_file_name_pyautogui(type_string)\nprint('done upload')\nsleep(2)",
"self.cs_time_stamping_services.click_button_id_tsp_add()\nself.cs_time_sta... | <|body_start_0|>
sleep(2)
type_string = os.path.join(os.getcwd(), TESTDATA[section1][u'data_folder'], TESTDATA[section2][u'tsa_cert_file_name'])
print(type_string)
self.common_lib.type_file_name_pyautogui(type_string)
print('done upload')
sleep(2)
<|end_body_0|>
<|body_s... | Components common to central server timestamping services view Changelog: * 11.07.2017 | Documentation updated | Component_cs_tsp_services | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Component_cs_tsp_services:
"""Components common to central server timestamping services view Changelog: * 11.07.2017 | Documentation updated"""
def upload_tsa_certificate(self, section1=u'paths', section2=u'cs_url'):
"""Upload tsa certificate :param section1: Test data section name :... | stack_v2_sparse_classes_75kplus_train_073312 | 1,951 | permissive | [
{
"docstring": "Upload tsa certificate :param section1: Test data section name :param section2: Test data section name",
"name": "upload_tsa_certificate",
"signature": "def upload_tsa_certificate(self, section1=u'paths', section2=u'cs_url')"
},
{
"docstring": "Add timestamping service to central... | 2 | stack_v2_sparse_classes_30k_train_047175 | Implement the Python class `Component_cs_tsp_services` described below.
Class description:
Components common to central server timestamping services view Changelog: * 11.07.2017 | Documentation updated
Method signatures and docstrings:
- def upload_tsa_certificate(self, section1=u'paths', section2=u'cs_url'): Upload ... | Implement the Python class `Component_cs_tsp_services` described below.
Class description:
Components common to central server timestamping services view Changelog: * 11.07.2017 | Documentation updated
Method signatures and docstrings:
- def upload_tsa_certificate(self, section1=u'paths', section2=u'cs_url'): Upload ... | e030661a0ad8ceab74dd8122b751e88025a3474a | <|skeleton|>
class Component_cs_tsp_services:
"""Components common to central server timestamping services view Changelog: * 11.07.2017 | Documentation updated"""
def upload_tsa_certificate(self, section1=u'paths', section2=u'cs_url'):
"""Upload tsa certificate :param section1: Test data section name :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Component_cs_tsp_services:
"""Components common to central server timestamping services view Changelog: * 11.07.2017 | Documentation updated"""
def upload_tsa_certificate(self, section1=u'paths', section2=u'cs_url'):
"""Upload tsa certificate :param section1: Test data section name :param section... | the_stack_v2_python_sparse | common/xrd-ui-tests-qautomate/common_lib/component_cs_tsp_services.py | nordic-institute/X-Road-tests | train | 2 |
0f62933246114deed5623f7496d381796a012ae7 | [
"super().__init__(parent)\nself.other_sources = other_sources\nself.item = None\nself.name = None\nself.source = None\nbutton = tkinter.Button(self, text='Open file...', command=self.on_select_file)\nbutton.pack(fill='both', expand=True)\nif self.other_sources:\n tkinter.Label(self, text='Other Sources:').pack(f... | <|body_start_0|>
super().__init__(parent)
self.other_sources = other_sources
self.item = None
self.name = None
self.source = None
button = tkinter.Button(self, text='Open file...', command=self.on_select_file)
button.pack(fill='both', expand=True)
if self.... | tkSourceSelect | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tkSourceSelect:
def __init__(self, parent, other_sources=None):
"""TODO: add docstring"""
<|body_0|>
def on_select_file(self):
"""TODO: add docstring"""
<|body_1|>
def on_select_other(self, item):
"""TODO: add docstring"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus_train_073313 | 5,415 | no_license | [
{
"docstring": "TODO: add docstring",
"name": "__init__",
"signature": "def __init__(self, parent, other_sources=None)"
},
{
"docstring": "TODO: add docstring",
"name": "on_select_file",
"signature": "def on_select_file(self)"
},
{
"docstring": "TODO: add docstring",
"name": ... | 3 | stack_v2_sparse_classes_30k_test_000486 | Implement the Python class `tkSourceSelect` described below.
Class description:
Implement the tkSourceSelect class.
Method signatures and docstrings:
- def __init__(self, parent, other_sources=None): TODO: add docstring
- def on_select_file(self): TODO: add docstring
- def on_select_other(self, item): TODO: add docst... | Implement the Python class `tkSourceSelect` described below.
Class description:
Implement the tkSourceSelect class.
Method signatures and docstrings:
- def __init__(self, parent, other_sources=None): TODO: add docstring
- def on_select_file(self): TODO: add docstring
- def on_select_other(self, item): TODO: add docst... | 237cb3c74ff193557addcf5bb43af4b87cb8df4e | <|skeleton|>
class tkSourceSelect:
def __init__(self, parent, other_sources=None):
"""TODO: add docstring"""
<|body_0|>
def on_select_file(self):
"""TODO: add docstring"""
<|body_1|>
def on_select_other(self, item):
"""TODO: add docstring"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class tkSourceSelect:
def __init__(self, parent, other_sources=None):
"""TODO: add docstring"""
super().__init__(parent)
self.other_sources = other_sources
self.item = None
self.name = None
self.source = None
button = tkinter.Button(self, text='Open file...', ... | the_stack_v2_python_sparse | test03/tkCamera.py | ss820938ss/pythonProject | train | 0 | |
6cc8ccd9e2f4936eb138c7d8c93245f0091d4c1b | [
"super(Cifar10CNN, self).__init__()\nself.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.... | <|body_start_0|>
super(Cifar10CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(ke... | CNN for the CIFAR-10 Datset | Cifar10CNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cifar10CNN:
"""CNN for the CIFAR-10 Datset"""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Cifar10CNN, self).__init__()
self.conv_layer ... | stack_v2_sparse_classes_75kplus_train_073314 | 9,353 | permissive | [
{
"docstring": "CNN Builder.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040405 | Implement the Python class `Cifar10CNN` described below.
Class description:
CNN for the CIFAR-10 Datset
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward. | Implement the Python class `Cifar10CNN` described below.
Class description:
CNN for the CIFAR-10 Datset
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward.
<|skeleton|>
class Cifar10CNN:
"""CNN for the CIFAR-10 Datset"""
def __init__(self):
"... | 7f3003d8c55c44dbf95717f9d046eb242360ae87 | <|skeleton|>
class Cifar10CNN:
"""CNN for the CIFAR-10 Datset"""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cifar10CNN:
"""CNN for the CIFAR-10 Datset"""
def __init__(self):
"""CNN Builder."""
super(Cifar10CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_chan... | the_stack_v2_python_sparse | code/arc/Asaf/My_Models.py | Asafgendler/Thesis | train | 0 |
3e3ccfefbe0e4902fbe893dc89289071ffacd5a8 | [
"cd = self.cleaned_data\nif cd['password'] != cd['password2']:\n raise forms.ValidationError(\"Passwords don't match.\")\nreturn cd['password2']",
"cd = self.cleaned_data\ntry:\n player = Player.objects.get(name_excel=cd['username'])\n if player.user:\n raise forms.ValidationError(\"There's a user... | <|body_start_0|>
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError("Passwords don't match.")
return cd['password2']
<|end_body_0|>
<|body_start_1|>
cd = self.cleaned_data
try:
player = Player.objects.get(name_excel=c... | UserRegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegistrationForm:
def clean_password2(self):
"""Validates that the passwords are the same :return: The password or raise a Validation Error with message"""
<|body_0|>
def clean_username(self):
"""Validate that a new user doesn't register with a name that is alrea... | stack_v2_sparse_classes_75kplus_train_073315 | 2,533 | no_license | [
{
"docstring": "Validates that the passwords are the same :return: The password or raise a Validation Error with message",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Validate that a new user doesn't register with a name that is already in use by anothe... | 2 | stack_v2_sparse_classes_30k_train_000680 | Implement the Python class `UserRegistrationForm` described below.
Class description:
Implement the UserRegistrationForm class.
Method signatures and docstrings:
- def clean_password2(self): Validates that the passwords are the same :return: The password or raise a Validation Error with message
- def clean_username(s... | Implement the Python class `UserRegistrationForm` described below.
Class description:
Implement the UserRegistrationForm class.
Method signatures and docstrings:
- def clean_password2(self): Validates that the passwords are the same :return: The password or raise a Validation Error with message
- def clean_username(s... | 5c326f324e2f8e8278ec536017e309e1a970062d | <|skeleton|>
class UserRegistrationForm:
def clean_password2(self):
"""Validates that the passwords are the same :return: The password or raise a Validation Error with message"""
<|body_0|>
def clean_username(self):
"""Validate that a new user doesn't register with a name that is alrea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRegistrationForm:
def clean_password2(self):
"""Validates that the passwords are the same :return: The password or raise a Validation Error with message"""
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError("Passwords don't match.")... | the_stack_v2_python_sparse | stats/forms.py | carlosds730/Football | train | 1 | |
beb38cc997755610caf12d1abca076ead5e0cf6b | [
"super().__init__()\nself.blocks = ModuleList()\nfor in_feat_os in in_feature_output_strides:\n num_upsample = int(math.log2(int(in_feat_os))) - int(math.log2(int(out_feature_output_stride)))\n num_layers = num_upsample if num_upsample != 0 else 1\n self.blocks.append(Sequential(*[Sequential(Conv2d(in_chan... | <|body_start_0|>
super().__init__()
self.blocks = ModuleList()
for in_feat_os in in_feature_output_strides:
num_upsample = int(math.log2(int(in_feat_os))) - int(math.log2(int(out_feature_output_stride)))
num_layers = num_upsample if num_upsample != 0 else 1
se... | Light Weight Decoder. | _LightWeightDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LightWeightDecoder:
"""Light Weight Decoder."""
def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None:
"""Initialize the _LightWeightDecoder module. Args: in_channels: ... | stack_v2_sparse_classes_75kplus_train_073316 | 8,033 | permissive | [
{
"docstring": "Initialize the _LightWeightDecoder module. Args: in_channels: number of channels of input feature maps out_channels: number of channels of output feature maps num_classes: number of output segmentation classes in_feature_output_strides: output stride of input feature maps at different levels out... | 2 | stack_v2_sparse_classes_30k_train_011995 | Implement the Python class `_LightWeightDecoder` described below.
Class description:
Light Weight Decoder.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None: Initi... | Implement the Python class `_LightWeightDecoder` described below.
Class description:
Light Weight Decoder.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None: Initi... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class _LightWeightDecoder:
"""Light Weight Decoder."""
def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None:
"""Initialize the _LightWeightDecoder module. Args: in_channels: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _LightWeightDecoder:
"""Light Weight Decoder."""
def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None:
"""Initialize the _LightWeightDecoder module. Args: in_channels: number of cha... | the_stack_v2_python_sparse | torchgeo/models/farseg.py | microsoft/torchgeo | train | 1,724 |
03ffbfa0de3ec63b03a1a7b9f9545ab078637dec | [
"def adjmul(arr, i):\n ret = arr[i]\n if 0 < i:\n ret *= arr[i - 1]\n if i < len(arr) - 1:\n ret *= arr[i + 1]\n return ret\n\n@lru_cache(None)\ndef dp(nums):\n ret = 0\n for i in range(len(nums)):\n cur = adjmul(nums, i)\n sub = dp(tuple(nums[:i] + nums[i + 1:]))\n ... | <|body_start_0|>
def adjmul(arr, i):
ret = arr[i]
if 0 < i:
ret *= arr[i - 1]
if i < len(arr) - 1:
ret *= arr[i + 1]
return ret
@lru_cache(None)
def dp(nums):
ret = 0
for i in range(len(nums)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxCoins(self, nums: List[int]) -> int:
"""Brute-force TLE"""
<|body_0|>
def maxCoins(self, nums: List[int]) -> int:
"""Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)"""
<|body_1|>
def maxCoins(self, nums: List[int]... | stack_v2_sparse_classes_75kplus_train_073317 | 3,846 | no_license | [
{
"docstring": "Brute-force TLE",
"name": "maxCoins",
"signature": "def maxCoins(self, nums: List[int]) -> int"
},
{
"docstring": "Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)",
"name": "maxCoins",
"signature": "def maxCoins(self, nums: List[int]) -> int"
},
... | 4 | stack_v2_sparse_classes_30k_train_013965 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxCoins(self, nums: List[int]) -> int: Brute-force TLE
- def maxCoins(self, nums: List[int]) -> int: Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)
... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxCoins(self, nums: List[int]) -> int: Brute-force TLE
- def maxCoins(self, nums: List[int]) -> int: Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxCoins(self, nums: List[int]) -> int:
"""Brute-force TLE"""
<|body_0|>
def maxCoins(self, nums: List[int]) -> int:
"""Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)"""
<|body_1|>
def maxCoins(self, nums: List[int]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxCoins(self, nums: List[int]) -> int:
"""Brute-force TLE"""
def adjmul(arr, i):
ret = arr[i]
if 0 < i:
ret *= arr[i - 1]
if i < len(arr) - 1:
ret *= arr[i + 1]
return ret
@lru_cache(None)
... | the_stack_v2_python_sparse | leetcode/solved/312_Burst_Balloons/solution.py | sungminoh/algorithms | train | 0 | |
ec7dcdc73368210918834435dcfd21b2a202686f | [
"json_data = data()\nargs = ['scope', 'name', 'data_type', 'status', 'granularity_type', 'granularity_level', 'priority', 'request_meta']\ntry:\n parameters = {}\n json_data = json.loads(json_data)\n for key, value in json_data.items():\n if key in args:\n parameters[key] = value\nexcept ... | <|body_start_0|>
json_data = data()
args = ['scope', 'name', 'data_type', 'status', 'granularity_type', 'granularity_level', 'priority', 'request_meta']
try:
parameters = {}
json_data = json.loads(json_data)
for key, value in json_data.items():
... | Update, get and delete Request. | Request | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
"""Update, get and delete Request."""
def PUT(self, request_id):
"""Update Request properties with a given id. HTTP Success: 200 OK HTTP Error: 400 Bad request 404 Not Found 500 Internal Error"""
<|body_0|>
def GET(self, request_id):
"""Get details about... | stack_v2_sparse_classes_75kplus_train_073318 | 7,467 | no_license | [
{
"docstring": "Update Request properties with a given id. HTTP Success: 200 OK HTTP Error: 400 Bad request 404 Not Found 500 Internal Error",
"name": "PUT",
"signature": "def PUT(self, request_id)"
},
{
"docstring": "Get details about a specific Request with given id. HTTP Success: 200 OK HTTP ... | 3 | stack_v2_sparse_classes_30k_train_047277 | Implement the Python class `Request` described below.
Class description:
Update, get and delete Request.
Method signatures and docstrings:
- def PUT(self, request_id): Update Request properties with a given id. HTTP Success: 200 OK HTTP Error: 400 Bad request 404 Not Found 500 Internal Error
- def GET(self, request_i... | Implement the Python class `Request` described below.
Class description:
Update, get and delete Request.
Method signatures and docstrings:
- def PUT(self, request_id): Update Request properties with a given id. HTTP Success: 200 OK HTTP Error: 400 Bad request 404 Not Found 500 Internal Error
- def GET(self, request_i... | 383ddcebec31bda993d91e2aab7c0602f0a452d2 | <|skeleton|>
class Request:
"""Update, get and delete Request."""
def PUT(self, request_id):
"""Update Request properties with a given id. HTTP Success: 200 OK HTTP Error: 400 Bad request 404 Not Found 500 Internal Error"""
<|body_0|>
def GET(self, request_id):
"""Get details about... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Request:
"""Update, get and delete Request."""
def PUT(self, request_id):
"""Update Request properties with a given id. HTTP Success: 200 OK HTTP Error: 400 Bad request 404 Not Found 500 Internal Error"""
json_data = data()
args = ['scope', 'name', 'data_type', 'status', 'granular... | the_stack_v2_python_sparse | lib/ess/rest/v1/requests.py | PanDAWMS/ESS | train | 0 |
1f8b2e45df09e4e4955ccc3ae05a1e6788ab3a70 | [
"ret = []\ncheck = []\nuser_id = kwargs['user']['user_id']\nuser = User.objects(pk=user_id).first()\nif not user:\n return (response_message(ENOENT, 'User not found'), 404)\norganizations = Organization.objects(owner=user)\nfor organization in organizations:\n ret.append({'label': organization.name, 'owner': ... | <|body_start_0|>
ret = []
check = []
user_id = kwargs['user']['user_id']
user = User.objects(pk=user_id).first()
if not user:
return (response_message(ENOENT, 'User not found'), 404)
organizations = Organization.objects(owner=user)
for organization in ... | OrganizationList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationList:
def get(self, **kwargs):
"""List all organizations joined by the logged in user"""
<|body_0|>
def post(self, **kwargs):
"""Create a new organization Note: The logged in user performing the operation will become the owner of the organization"""
... | stack_v2_sparse_classes_75kplus_train_073319 | 16,046 | permissive | [
{
"docstring": "List all organizations joined by the logged in user",
"name": "get",
"signature": "def get(self, **kwargs)"
},
{
"docstring": "Create a new organization Note: The logged in user performing the operation will become the owner of the organization",
"name": "post",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_041507 | Implement the Python class `OrganizationList` described below.
Class description:
Implement the OrganizationList class.
Method signatures and docstrings:
- def get(self, **kwargs): List all organizations joined by the logged in user
- def post(self, **kwargs): Create a new organization Note: The logged in user perfor... | Implement the Python class `OrganizationList` described below.
Class description:
Implement the OrganizationList class.
Method signatures and docstrings:
- def get(self, **kwargs): List all organizations joined by the logged in user
- def post(self, **kwargs): Create a new organization Note: The logged in user perfor... | e865758241beee3bd0c56a120f3986b0c4aa7253 | <|skeleton|>
class OrganizationList:
def get(self, **kwargs):
"""List all organizations joined by the logged in user"""
<|body_0|>
def post(self, **kwargs):
"""Create a new organization Note: The logged in user performing the operation will become the owner of the organization"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationList:
def get(self, **kwargs):
"""List all organizations joined by the logged in user"""
ret = []
check = []
user_id = kwargs['user']['user_id']
user = User.objects(pk=user_id).first()
if not user:
return (response_message(ENOENT, 'User n... | the_stack_v2_python_sparse | webserver/app/main/controller/organization_controller.py | Remoterwls/Auto-Test-System | train | 0 | |
914424bcae3623f25b0c31ccd906c74a0851e9e3 | [
"cls.custom = True\ncls.User = get_user_model()\ncls.user = cls.User.objects.create_user(username='Test1', email='Test1@example.com', password='12345')\nif cls.custom:\n cls.practical = Practical.objects.create()\n cls.group = Group.objects.create(name='group1', practical=cls.practical)\n cls.user.group = ... | <|body_start_0|>
cls.custom = True
cls.User = get_user_model()
cls.user = cls.User.objects.create_user(username='Test1', email='Test1@example.com', password='12345')
if cls.custom:
cls.practical = Practical.objects.create()
cls.group = Group.objects.create(name='g... | Logout Tests. | LogoutTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogoutTest:
"""Logout Tests."""
def setUpTestData(cls):
"""Run once before the tests."""
<|body_0|>
def test_valid_logout(self):
"""If the authentication credential (token) matches that of a registered user, the user's authentication token is deleted and http_200... | stack_v2_sparse_classes_75kplus_train_073320 | 9,175 | permissive | [
{
"docstring": "Run once before the tests.",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "If the authentication credential (token) matches that of a registered user, the user's authentication token is deleted and http_200_ok is returned in the response.",
... | 3 | stack_v2_sparse_classes_30k_train_051068 | Implement the Python class `LogoutTest` described below.
Class description:
Logout Tests.
Method signatures and docstrings:
- def setUpTestData(cls): Run once before the tests.
- def test_valid_logout(self): If the authentication credential (token) matches that of a registered user, the user's authentication token is... | Implement the Python class `LogoutTest` described below.
Class description:
Logout Tests.
Method signatures and docstrings:
- def setUpTestData(cls): Run once before the tests.
- def test_valid_logout(self): If the authentication credential (token) matches that of a registered user, the user's authentication token is... | ac03b03c1bb029eaadc34aee21fac692500b23d0 | <|skeleton|>
class LogoutTest:
"""Logout Tests."""
def setUpTestData(cls):
"""Run once before the tests."""
<|body_0|>
def test_valid_logout(self):
"""If the authentication credential (token) matches that of a registered user, the user's authentication token is deleted and http_200... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogoutTest:
"""Logout Tests."""
def setUpTestData(cls):
"""Run once before the tests."""
cls.custom = True
cls.User = get_user_model()
cls.user = cls.User.objects.create_user(username='Test1', email='Test1@example.com', password='12345')
if cls.custom:
... | the_stack_v2_python_sparse | src/vm-django/authentication/tests.py | utmandrew/virtual-mystery | train | 2 |
32f9fc211415533ba735afb2c85b8ad32838755c | [
"options = {'name': placeholders_data['recipient_name'], 'action_url': placeholders_data['action_url'], 'support_email': placeholders_data['support_email'], 'login_url': placeholders_data['login_url']}\ncontext = Context(options)\ntemplate = Template(email_template)\nemailContent = template.render(context)\nreturn ... | <|body_start_0|>
options = {'name': placeholders_data['recipient_name'], 'action_url': placeholders_data['action_url'], 'support_email': placeholders_data['support_email'], 'login_url': placeholders_data['login_url']}
context = Context(options)
template = Template(email_template)
emailCo... | SendEmailUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmailUtil:
def _get_html_content_for_email(self, email_template, placeholders_data):
"""Preparing email content"""
<|body_0|>
def sending_mail(self, user, email_template, subject):
"""sending email"""
<|body_1|>
def generate_reset_password_link(self,... | stack_v2_sparse_classes_75kplus_train_073321 | 3,262 | no_license | [
{
"docstring": "Preparing email content",
"name": "_get_html_content_for_email",
"signature": "def _get_html_content_for_email(self, email_template, placeholders_data)"
},
{
"docstring": "sending email",
"name": "sending_mail",
"signature": "def sending_mail(self, user, email_template, s... | 3 | stack_v2_sparse_classes_30k_train_020221 | Implement the Python class `SendEmailUtil` described below.
Class description:
Implement the SendEmailUtil class.
Method signatures and docstrings:
- def _get_html_content_for_email(self, email_template, placeholders_data): Preparing email content
- def sending_mail(self, user, email_template, subject): sending email... | Implement the Python class `SendEmailUtil` described below.
Class description:
Implement the SendEmailUtil class.
Method signatures and docstrings:
- def _get_html_content_for_email(self, email_template, placeholders_data): Preparing email content
- def sending_mail(self, user, email_template, subject): sending email... | 5d5bc4c1eecbf627d38260e4d314d8451d67a4f5 | <|skeleton|>
class SendEmailUtil:
def _get_html_content_for_email(self, email_template, placeholders_data):
"""Preparing email content"""
<|body_0|>
def sending_mail(self, user, email_template, subject):
"""sending email"""
<|body_1|>
def generate_reset_password_link(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SendEmailUtil:
def _get_html_content_for_email(self, email_template, placeholders_data):
"""Preparing email content"""
options = {'name': placeholders_data['recipient_name'], 'action_url': placeholders_data['action_url'], 'support_email': placeholders_data['support_email'], 'login_url': placeh... | the_stack_v2_python_sparse | curation-api/src/users/utils.py | mohanj1919/django_app_test | train | 0 | |
91d1f8dc0e7fce04464f9483554b4622474b3d78 | [
"st = StudyFile.query.get(kf_id)\nif st is None:\n abort(404, 'could not find {} `{}`'.format('study_file', kf_id))\nreturn StudyFileSchema(many=False).jsonify(st)",
"body = request.get_json(force=True)\nst = StudyFile.query.get(kf_id)\nif st is None:\n abort(404, 'could not find {} `{}`'.format('study_file... | <|body_start_0|>
st = StudyFile.query.get(kf_id)
if st is None:
abort(404, 'could not find {} `{}`'.format('study_file', kf_id))
return StudyFileSchema(many=False).jsonify(st)
<|end_body_0|>
<|body_start_1|>
body = request.get_json(force=True)
st = StudyFile.query.ge... | StudyFile API | StudyFileAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudyFileAPI:
"""StudyFile API"""
def get(self, kf_id):
"""Get a study_file by id --- template: path: get_by_id.yml properties: resource: StudyFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing study_file. Allows partial update of resource --- templ... | stack_v2_sparse_classes_75kplus_train_073322 | 4,298 | permissive | [
{
"docstring": "Get a study_file by id --- template: path: get_by_id.yml properties: resource: StudyFile",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing study_file. Allows partial update of resource --- template: path: update_by_id.yml properties: resou... | 3 | stack_v2_sparse_classes_30k_train_049807 | Implement the Python class `StudyFileAPI` described below.
Class description:
StudyFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a study_file by id --- template: path: get_by_id.yml properties: resource: StudyFile
- def patch(self, kf_id): Update an existing study_file. Allows partial update ... | Implement the Python class `StudyFileAPI` described below.
Class description:
StudyFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a study_file by id --- template: path: get_by_id.yml properties: resource: StudyFile
- def patch(self, kf_id): Update an existing study_file. Allows partial update ... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class StudyFileAPI:
"""StudyFile API"""
def get(self, kf_id):
"""Get a study_file by id --- template: path: get_by_id.yml properties: resource: StudyFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing study_file. Allows partial update of resource --- templ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StudyFileAPI:
"""StudyFile API"""
def get(self, kf_id):
"""Get a study_file by id --- template: path: get_by_id.yml properties: resource: StudyFile"""
st = StudyFile.query.get(kf_id)
if st is None:
abort(404, 'could not find {} `{}`'.format('study_file', kf_id))
... | the_stack_v2_python_sparse | dataservice/api/study_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
0639d7360af6c05cc10d65b4ccec3193aa26f183 | [
"self.bars = bars\nself.symbol_list = self.bars.symbol_list\nself.events = events\nself.portfolio = port",
"bought = {}\nfree_cash = self.portfolio.current_holdings['cash']\nfor s in self.symbol_list:\n bought[s] = False\n bars = self.bars.get_latest_bars(s, N=1)\n cost = bars[0][5] * self.portfolio.buy_... | <|body_start_0|>
self.bars = bars
self.symbol_list = self.bars.symbol_list
self.events = events
self.portfolio = port
<|end_body_0|>
<|body_start_1|>
bought = {}
free_cash = self.portfolio.current_holdings['cash']
for s in self.symbol_list:
bought[s] ... | Крайне простая стратегия, которая входит в длинную позициию при полуении бара и никогда из нее не выходит. Используется в качестве механизма тестирования класса Strategy и бенчмарка для сравнения разных стратегий. | BuyAndHoldStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuyAndHoldStrategy:
"""Крайне простая стратегия, которая входит в длинную позициию при полуении бара и никогда из нее не выходит. Используется в качестве механизма тестирования класса Strategy и бенчмарка для сравнения разных стратегий."""
def __init__(self, bars, events, port):
"""И... | stack_v2_sparse_classes_75kplus_train_073323 | 4,426 | no_license | [
{
"docstring": "Инициализирует стратегию buy and hold. Параметры: bars - Объект DataHandler, который предоставляет информацию о барах events - Объект очереди событий.",
"name": "__init__",
"signature": "def __init__(self, bars, events, port)"
},
{
"docstring": "Функия возвращает словарь, разреща... | 3 | stack_v2_sparse_classes_30k_train_020214 | Implement the Python class `BuyAndHoldStrategy` described below.
Class description:
Крайне простая стратегия, которая входит в длинную позициию при полуении бара и никогда из нее не выходит. Используется в качестве механизма тестирования класса Strategy и бенчмарка для сравнения разных стратегий.
Method signatures an... | Implement the Python class `BuyAndHoldStrategy` described below.
Class description:
Крайне простая стратегия, которая входит в длинную позициию при полуении бара и никогда из нее не выходит. Используется в качестве механизма тестирования класса Strategy и бенчмарка для сравнения разных стратегий.
Method signatures an... | 68c2534faf53cca7f3b1b258c72b3e15c23f810e | <|skeleton|>
class BuyAndHoldStrategy:
"""Крайне простая стратегия, которая входит в длинную позициию при полуении бара и никогда из нее не выходит. Используется в качестве механизма тестирования класса Strategy и бенчмарка для сравнения разных стратегий."""
def __init__(self, bars, events, port):
"""И... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuyAndHoldStrategy:
"""Крайне простая стратегия, которая входит в длинную позициию при полуении бара и никогда из нее не выходит. Используется в качестве механизма тестирования класса Strategy и бенчмарка для сравнения разных стратегий."""
def __init__(self, bars, events, port):
"""Инициализирует... | the_stack_v2_python_sparse | project_file/strategy.py | SchamanGrin/Portfolio_backtest_v_1 | train | 0 |
a3e920255d5f799064803e7f1d1f43869648e130 | [
"if not nums:\n return None\nspring = nums\nself.count = [None] * len(spring)\nself.count[0] = spring[0]\nfor k in range(1, len(spring)):\n self.count[k] = self.count[k - 1] + spring[k]",
"if i == 0:\n return self.count[j]\nelse:\n return self.count[j] - self.count[i - 1]"
] | <|body_start_0|>
if not nums:
return None
spring = nums
self.count = [None] * len(spring)
self.count[0] = spring[0]
for k in range(1, len(spring)):
self.count[k] = self.count[k - 1] + spring[k]
<|end_body_0|>
<|body_start_1|>
if i == 0:
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return None
spring = nums
... | stack_v2_sparse_classes_75kplus_train_073324 | 882 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035123 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 769d89efc97e43b85b8b36d80dfb75f2fcf173fc | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if not nums:
return None
spring = nums
self.count = [None] * len(spring)
self.count[0] = spring[0]
for k in range(1, len(spring)):
self.count[k] = self.count[k - 1] + spring[... | the_stack_v2_python_sparse | 303_range_sum_query_immutable.py | Rainphix/LeetCode | train | 0 | |
4b987b565ac62c1348c8c78db0e507ca138a68c4 | [
"self.x += x\nself.y += y\nself.z += z\nreturn self",
"self.x = x\nself.y = y\nself.z = z\nreturn self",
"self.x *= sX\nself.y *= sY\nself.z *= sZ\nreturn self"
] | <|body_start_0|>
self.x += x
self.y += y
self.z += z
return self
<|end_body_0|>
<|body_start_1|>
self.x = x
self.y = y
self.z = z
return self
<|end_body_1|>
<|body_start_2|>
self.x *= sX
self.y *= sY
self.z *= sZ
return se... | Base class for a triplet of integer values | Coordinate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coordinate:
"""Base class for a triplet of integer values"""
def add(self, x, y, z):
"""change position relative to current position"""
<|body_0|>
def set(self, x, y, z):
"""set position absolutely on world space"""
<|body_1|>
def scale(self, sX, sY,... | stack_v2_sparse_classes_75kplus_train_073325 | 539 | no_license | [
{
"docstring": "change position relative to current position",
"name": "add",
"signature": "def add(self, x, y, z)"
},
{
"docstring": "set position absolutely on world space",
"name": "set",
"signature": "def set(self, x, y, z)"
},
{
"docstring": "scale position relative to the o... | 3 | stack_v2_sparse_classes_30k_train_010752 | Implement the Python class `Coordinate` described below.
Class description:
Base class for a triplet of integer values
Method signatures and docstrings:
- def add(self, x, y, z): change position relative to current position
- def set(self, x, y, z): set position absolutely on world space
- def scale(self, sX, sY, sZ)... | Implement the Python class `Coordinate` described below.
Class description:
Base class for a triplet of integer values
Method signatures and docstrings:
- def add(self, x, y, z): change position relative to current position
- def set(self, x, y, z): set position absolutely on world space
- def scale(self, sX, sY, sZ)... | 05483312c3b5025009c634c4dc2f5eeeb3fee7cb | <|skeleton|>
class Coordinate:
"""Base class for a triplet of integer values"""
def add(self, x, y, z):
"""change position relative to current position"""
<|body_0|>
def set(self, x, y, z):
"""set position absolutely on world space"""
<|body_1|>
def scale(self, sX, sY,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Coordinate:
"""Base class for a triplet of integer values"""
def add(self, x, y, z):
"""change position relative to current position"""
self.x += x
self.y += y
self.z += z
return self
def set(self, x, y, z):
"""set position absolutely on world space"""... | the_stack_v2_python_sparse | component/coordinate.py | FaideWW/perseus | train | 0 |
33d52e03bc3c5eb4a79c2eb29633ab783f1ae7dd | [
"try:\n self.__string = args[0]\nexcept IndexError:\n self.__string = ''\nself.__reformat = kwargs.get('reformat', True)",
"if self.__string:\n if self.__reformat:\n return textwrap.fill(self.__string, initial_indent='# ', subsequent_indent='# ', width=70)\n else:\n return re.sub('^', '#... | <|body_start_0|>
try:
self.__string = args[0]
except IndexError:
self.__string = ''
self.__reformat = kwargs.get('reformat', True)
<|end_body_0|>
<|body_start_1|>
if self.__string:
if self.__reformat:
return textwrap.fill(self.__string... | The `comment` primitive inserts a comment into the corresponding place in the container specification file. # Parameters reformat: Boolean flag to specify whether the comment string should be wrapped to fit into lines not exceeding 80 characters. The default is True. # Examples ```python comment('libfoo version X.Y') `... | comment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class comment:
"""The `comment` primitive inserts a comment into the corresponding place in the container specification file. # Parameters reformat: Boolean flag to specify whether the comment string should be wrapped to fit into lines not exceeding 80 characters. The default is True. # Examples ```pyt... | stack_v2_sparse_classes_75kplus_train_073326 | 2,124 | permissive | [
{
"docstring": "Initialize primitive",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "String representation of the primitive",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009634 | Implement the Python class `comment` described below.
Class description:
The `comment` primitive inserts a comment into the corresponding place in the container specification file. # Parameters reformat: Boolean flag to specify whether the comment string should be wrapped to fit into lines not exceeding 80 characters.... | Implement the Python class `comment` described below.
Class description:
The `comment` primitive inserts a comment into the corresponding place in the container specification file. # Parameters reformat: Boolean flag to specify whether the comment string should be wrapped to fit into lines not exceeding 80 characters.... | 555093c0a5c98bd2b0114831b8c676c0c3c50dd7 | <|skeleton|>
class comment:
"""The `comment` primitive inserts a comment into the corresponding place in the container specification file. # Parameters reformat: Boolean flag to specify whether the comment string should be wrapped to fit into lines not exceeding 80 characters. The default is True. # Examples ```pyt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class comment:
"""The `comment` primitive inserts a comment into the corresponding place in the container specification file. # Parameters reformat: Boolean flag to specify whether the comment string should be wrapped to fit into lines not exceeding 80 characters. The default is True. # Examples ```python comment('... | the_stack_v2_python_sparse | hpccm/primitives/comment.py | DalavanCloud/hpc-container-maker | train | 1 |
0cb7177eb6db88d49cb5c4e74f853ee9c041edb1 | [
"self.body = body\nif notif_type not in ['Error', 'Feedback', 'Misc']:\n self.notif_type = 'Invalid'\nelse:\n self.notif_type = notif_type\nself.guild, self.channel, self.user = (guild, channel, user)\nself.time = time_module.strftime('%D %T PST')",
"embed = discord.Embed()\nif self.notif_type == 'Error':\n... | <|body_start_0|>
self.body = body
if notif_type not in ['Error', 'Feedback', 'Misc']:
self.notif_type = 'Invalid'
else:
self.notif_type = notif_type
self.guild, self.channel, self.user = (guild, channel, user)
self.time = time_module.strftime('%D %T PST')
... | DevNotif | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DevNotif:
def __init__(self, body, notif_type, guild, channel, user):
"""Creates a DevNotif class. Params: body: str notif_type: str guild: discord.Guild() channel: discord.Channel() user: discord.User() time: int DevNotif() -> None"""
<|body_0|>
def format_into_embed(self):... | stack_v2_sparse_classes_75kplus_train_073327 | 2,135 | no_license | [
{
"docstring": "Creates a DevNotif class. Params: body: str notif_type: str guild: discord.Guild() channel: discord.Channel() user: discord.User() time: int DevNotif() -> None",
"name": "__init__",
"signature": "def __init__(self, body, notif_type, guild, channel, user)"
},
{
"docstring": "Forma... | 2 | stack_v2_sparse_classes_30k_train_032302 | Implement the Python class `DevNotif` described below.
Class description:
Implement the DevNotif class.
Method signatures and docstrings:
- def __init__(self, body, notif_type, guild, channel, user): Creates a DevNotif class. Params: body: str notif_type: str guild: discord.Guild() channel: discord.Channel() user: di... | Implement the Python class `DevNotif` described below.
Class description:
Implement the DevNotif class.
Method signatures and docstrings:
- def __init__(self, body, notif_type, guild, channel, user): Creates a DevNotif class. Params: body: str notif_type: str guild: discord.Guild() channel: discord.Channel() user: di... | 8b1fb4bb4aff32685c989626f551cae3b97c3120 | <|skeleton|>
class DevNotif:
def __init__(self, body, notif_type, guild, channel, user):
"""Creates a DevNotif class. Params: body: str notif_type: str guild: discord.Guild() channel: discord.Channel() user: discord.User() time: int DevNotif() -> None"""
<|body_0|>
def format_into_embed(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DevNotif:
def __init__(self, body, notif_type, guild, channel, user):
"""Creates a DevNotif class. Params: body: str notif_type: str guild: discord.Guild() channel: discord.Channel() user: discord.User() time: int DevNotif() -> None"""
self.body = body
if notif_type not in ['Error', 'F... | the_stack_v2_python_sparse | cogs/util/devnotif.py | GeoffreyWesthoff/lilac-mirror | train | 0 | |
81d908f7c54c24e20bd364b396613cd8862d8403 | [
"resource = f'/luban-glxx-user/auth/info'\nresponse = item_fixture.request('GET', resource)\nreturn response",
"resource = f'/luban-glxx-user/auth/jsgl_redirect_login'\nquery_params = {'jsgl_token': jsgl_token}\nresponse = item_fixture.request('GET', resource, params=query_params)\nreturn response",
"resource =... | <|body_start_0|>
resource = f'/luban-glxx-user/auth/info'
response = item_fixture.request('GET', resource)
return response
<|end_body_0|>
<|body_start_1|>
resource = f'/luban-glxx-user/auth/jsgl_redirect_login'
query_params = {'jsgl_token': jsgl_token}
response = item_fi... | 鉴权模块 | Auth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auth:
"""鉴权模块"""
def getUserInfoUsingGET(self, item_fixture):
"""登录信息查询接口 :param item_fixture: item fixture,"""
<|body_0|>
def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None):
"""建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token"... | stack_v2_sparse_classes_75kplus_train_073328 | 1,514 | no_license | [
{
"docstring": "登录信息查询接口 :param item_fixture: item fixture,",
"name": "getUserInfoUsingGET",
"signature": "def getUserInfoUsingGET(self, item_fixture)"
},
{
"docstring": "建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token",
"name": "loginFromJsglUsingGET",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_038715 | Implement the Python class `Auth` described below.
Class description:
鉴权模块
Method signatures and docstrings:
- def getUserInfoUsingGET(self, item_fixture): 登录信息查询接口 :param item_fixture: item fixture,
- def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None): 建管跳转登录接口 :param item_fixture: item fixture, :param j... | Implement the Python class `Auth` described below.
Class description:
鉴权模块
Method signatures and docstrings:
- def getUserInfoUsingGET(self, item_fixture): 登录信息查询接口 :param item_fixture: item fixture,
- def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None): 建管跳转登录接口 :param item_fixture: item fixture, :param j... | f875de62f7f505c596ea5567e1fc2c8a64010f87 | <|skeleton|>
class Auth:
"""鉴权模块"""
def getUserInfoUsingGET(self, item_fixture):
"""登录信息查询接口 :param item_fixture: item fixture,"""
<|body_0|>
def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None):
"""建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Auth:
"""鉴权模块"""
def getUserInfoUsingGET(self, item_fixture):
"""登录信息查询接口 :param item_fixture: item fixture,"""
resource = f'/luban-glxx-user/auth/info'
response = item_fixture.request('GET', resource)
return response
def loginFromJsglUsingGET(self, item_fixture, jsgl... | the_stack_v2_python_sparse | swagger/api/luban_glxx_user/auth.py | zhangjingwen198817/pytest-api-allure | train | 1 |
5cf47dd35f6f2dfe3512306a62d4a1bafcbfbbaf | [
"user = users.get_current_user()\nif user:\n user_account = user_info.get_user_account()\n self.response.out.write(json.dumps(account_info(user_account)))\nelse:\n self.response.out.write(json.dumps(error_obj('User not logged in.')))",
"user = users.get_current_user()\nif not user:\n self.response.out... | <|body_start_0|>
user = users.get_current_user()
if user:
user_account = user_info.get_user_account()
self.response.out.write(json.dumps(account_info(user_account)))
else:
self.response.out.write(json.dumps(error_obj('User not logged in.')))
<|end_body_0|>
<|... | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def get(self):
"""Get your status and blurb."""
<|body_0|>
def put(self):
"""Set your status and blurb."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = users.get_current_user()
if user:
user_account = user_info.get_u... | stack_v2_sparse_classes_75kplus_train_073329 | 2,376 | no_license | [
{
"docstring": "Get your status and blurb.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Set your status and blurb.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011232 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def get(self): Get your status and blurb.
- def put(self): Set your status and blurb. | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def get(self): Get your status and blurb.
- def put(self): Set your status and blurb.
<|skeleton|>
class User:
def get(self):
"""Get your status and blurb."""
<|bod... | 0f121a58617131c01ff76ccca0e46a41aae76db6 | <|skeleton|>
class User:
def get(self):
"""Get your status and blurb."""
<|body_0|>
def put(self):
"""Set your status and blurb."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class User:
def get(self):
"""Get your status and blurb."""
user = users.get_current_user()
if user:
user_account = user_info.get_user_account()
self.response.out.write(json.dumps(account_info(user_account)))
else:
self.response.out.write(json.dump... | the_stack_v2_python_sparse | controllers/user.py | ShelleyGoldberg/golight | train | 0 | |
218d0db19092fcc02f5fe259aa268c0e713883d9 | [
"super(BatchNormalization, self).__init__(layer_type='batch_normalization')\nself.decay = decay\nself.running_mean = None\nself.running_var = None\nself.gamma = None\nself.beta = None\nself.param_shape = None\nself.cache_std = None\nself.cache_xc = None\nself.cache_xn = None\nself.optimizer = optimizer_dict[optimiz... | <|body_start_0|>
super(BatchNormalization, self).__init__(layer_type='batch_normalization')
self.decay = decay
self.running_mean = None
self.running_var = None
self.gamma = None
self.beta = None
self.param_shape = None
self.cache_std = None
self.ca... | 全连接神经网络类 | BatchNormalization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchNormalization:
"""全连接神经网络类"""
def __init__(self, decay=0.9, optimizer='sgd', **k_args):
""":param momentum: 计算全局均值标准差时的冲量"""
<|body_0|>
def build(self, input_shape):
"""根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_073330 | 3,818 | no_license | [
{
"docstring": ":param momentum: 计算全局均值标准差时的冲量",
"name": "__init__",
"signature": "def __init__(self, decay=0.9, optimizer='sgd', **k_args)"
},
{
"docstring": "根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值",
"name": "build",
"signature": "def build(self, input_shape)"
}... | 5 | stack_v2_sparse_classes_30k_train_049816 | Implement the Python class `BatchNormalization` described below.
Class description:
全连接神经网络类
Method signatures and docstrings:
- def __init__(self, decay=0.9, optimizer='sgd', **k_args): :param momentum: 计算全局均值标准差时的冲量
- def build(self, input_shape): 根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值
- def ... | Implement the Python class `BatchNormalization` described below.
Class description:
全连接神经网络类
Method signatures and docstrings:
- def __init__(self, decay=0.9, optimizer='sgd', **k_args): :param momentum: 计算全局均值标准差时的冲量
- def build(self, input_shape): 根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值
- def ... | 9f234a996b99c8e94d8259cd875e69af8ffa9a5c | <|skeleton|>
class BatchNormalization:
"""全连接神经网络类"""
def __init__(self, decay=0.9, optimizer='sgd', **k_args):
""":param momentum: 计算全局均值标准差时的冲量"""
<|body_0|>
def build(self, input_shape):
"""根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchNormalization:
"""全连接神经网络类"""
def __init__(self, decay=0.9, optimizer='sgd', **k_args):
""":param momentum: 计算全局均值标准差时的冲量"""
super(BatchNormalization, self).__init__(layer_type='batch_normalization')
self.decay = decay
self.running_mean = None
self.running_var... | the_stack_v2_python_sparse | enet/layers/batch_normalization.py | bighead-123/neural_network | train | 0 |
917c32520057c54b8c26508d63f6751885636dce | [
"test = App4Pyro()\nresult = test.sendURI()\nself.assertTrue(result)",
"test = App4Pyro()\ntest.sendURI()\nresult = test.getPayload()\nself.assertTrue(result)"
] | <|body_start_0|>
test = App4Pyro()
result = test.sendURI()
self.assertTrue(result)
<|end_body_0|>
<|body_start_1|>
test = App4Pyro()
test.sendURI()
result = test.getPayload()
self.assertTrue(result)
<|end_body_1|>
| Test methods for Pyro ORB | App4PyroTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App4PyroTest:
"""Test methods for Pyro ORB"""
def test_sendURI(self):
"""Test method for sendURI Compares boolean value True to the actual boolean value"""
<|body_0|>
def test_getPayload(self):
"""Test method for getPayload Compares boolean value True to the actu... | stack_v2_sparse_classes_75kplus_train_073331 | 710 | no_license | [
{
"docstring": "Test method for sendURI Compares boolean value True to the actual boolean value",
"name": "test_sendURI",
"signature": "def test_sendURI(self)"
},
{
"docstring": "Test method for getPayload Compares boolean value True to the actual boolean value",
"name": "test_getPayload",
... | 2 | stack_v2_sparse_classes_30k_train_024345 | Implement the Python class `App4PyroTest` described below.
Class description:
Test methods for Pyro ORB
Method signatures and docstrings:
- def test_sendURI(self): Test method for sendURI Compares boolean value True to the actual boolean value
- def test_getPayload(self): Test method for getPayload Compares boolean v... | Implement the Python class `App4PyroTest` described below.
Class description:
Test methods for Pyro ORB
Method signatures and docstrings:
- def test_sendURI(self): Test method for sendURI Compares boolean value True to the actual boolean value
- def test_getPayload(self): Test method for getPayload Compares boolean v... | d2029629a3fbcacd1e0322d96d12adf636ab9d61 | <|skeleton|>
class App4PyroTest:
"""Test methods for Pyro ORB"""
def test_sendURI(self):
"""Test method for sendURI Compares boolean value True to the actual boolean value"""
<|body_0|>
def test_getPayload(self):
"""Test method for getPayload Compares boolean value True to the actu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class App4PyroTest:
"""Test methods for Pyro ORB"""
def test_sendURI(self):
"""Test method for sendURI Compares boolean value True to the actual boolean value"""
test = App4Pyro()
result = test.sendURI()
self.assertTrue(result)
def test_getPayload(self):
"""Test met... | the_stack_v2_python_sparse | IST411_Distributed_Object_Computing/Project_Diamond/App4/test_app4Pyro.py | riz5034/PSU | train | 1 |
20166f62bae4e167f07b62580060bd4c0c425bfc | [
"try:\n return self.BookSource()\nexcept AttributeError:\n url = self.getPublication_url()\n source = 'Webpublished'\n if url:\n source += ', %s' % url\n if source and source[-1] not in '.!?':\n source += '.'\n return source",
"coinsData = BaseEntry.getCoinsDict(self)\ncoinsData['r... | <|body_start_0|>
try:
return self.BookSource()
except AttributeError:
url = self.getPublication_url()
source = 'Webpublished'
if url:
source += ', %s' % url
if source and source[-1] not in '.!?':
source += '.'
... | Content type to make reference to a webpublished (only) document. | WebpublishedReference | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebpublishedReference:
"""Content type to make reference to a webpublished (only) document."""
def Source(self):
"""the default webpublished source format"""
<|body_0|>
def getCoinsDict(self):
"""Select which values to display in the COinS tag for this item"""
... | stack_v2_sparse_classes_75kplus_train_073332 | 2,612 | no_license | [
{
"docstring": "the default webpublished source format",
"name": "Source",
"signature": "def Source(self)"
},
{
"docstring": "Select which values to display in the COinS tag for this item",
"name": "getCoinsDict",
"signature": "def getCoinsDict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001839 | Implement the Python class `WebpublishedReference` described below.
Class description:
Content type to make reference to a webpublished (only) document.
Method signatures and docstrings:
- def Source(self): the default webpublished source format
- def getCoinsDict(self): Select which values to display in the COinS ta... | Implement the Python class `WebpublishedReference` described below.
Class description:
Content type to make reference to a webpublished (only) document.
Method signatures and docstrings:
- def Source(self): the default webpublished source format
- def getCoinsDict(self): Select which values to display in the COinS ta... | f9e9f973765ae2bbfd02baee0bcfb2927b48b4f5 | <|skeleton|>
class WebpublishedReference:
"""Content type to make reference to a webpublished (only) document."""
def Source(self):
"""the default webpublished source format"""
<|body_0|>
def getCoinsDict(self):
"""Select which values to display in the COinS tag for this item"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebpublishedReference:
"""Content type to make reference to a webpublished (only) document."""
def Source(self):
"""the default webpublished source format"""
try:
return self.BookSource()
except AttributeError:
url = self.getPublication_url()
so... | the_stack_v2_python_sparse | Products/CMFBibliographyAT/content/webpublished.py | collective/Products.CMFBibliographyAT | train | 1 |
20b95b78af0aef7699c4365042db1c054ebb09c9 | [
"background = Background(color, image, elements, mode=mode, finish=False)\nbackground.finish()\nreturn background",
"super(Background, self).__init__('', elements, normal_params, finish=False)\nW, H = functions.get_screen_size()\nif image:\n painter = ImageFrame(image, mode=mode)\nelif color:\n painter = Ba... | <|body_start_0|>
background = Background(color, image, elements, mode=mode, finish=False)
background.finish()
return background
<|end_body_0|>
<|body_start_1|>
super(Background, self).__init__('', elements, normal_params, finish=False)
W, H = functions.get_screen_size()
... | Background element for another element or menu. | Background | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Background:
"""Background element for another element or menu."""
def make(color=None, image=None, elements=None, mode='scale to screen'):
"""Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the im... | stack_v2_sparse_classes_75kplus_train_073333 | 2,483 | permissive | [
{
"docstring": "Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the image of the background. <Mode>: None : if an image is passed, its original size is kept. Otherwise, a <color> (white by default) rect of the size of the sc... | 2 | stack_v2_sparse_classes_30k_train_049207 | Implement the Python class `Background` described below.
Class description:
Background element for another element or menu.
Method signatures and docstrings:
- def make(color=None, image=None, elements=None, mode='scale to screen'): Background element for another element or menu. <color>: if not None, define the colo... | Implement the Python class `Background` described below.
Class description:
Background element for another element or menu.
Method signatures and docstrings:
- def make(color=None, image=None, elements=None, mode='scale to screen'): Background element for another element or menu. <color>: if not None, define the colo... | e9dc52ff209f684be578f57a324f5bcf29d536ad | <|skeleton|>
class Background:
"""Background element for another element or menu."""
def make(color=None, image=None, elements=None, mode='scale to screen'):
"""Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the im... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Background:
"""Background element for another element or menu."""
def make(color=None, image=None, elements=None, mode='scale to screen'):
"""Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the image of the ba... | the_stack_v2_python_sparse | elements/background.py | YannThorimbert/Thorpy | train | 32 |
90cabaa9f93af2ad5d58d8927becc001bedcc2a6 | [
"users = UserModel.find_by_id(uid)\nif not users:\n return dict(code=404, msg='not found', data=None)\nelse:\n UserModel.delete(uid)\n return dict(code=200, msg='success', data=None)",
"assert current_user.id == uid\nform = UserForm()\nuser = UserModel.find_by_id(uid)\nuser.update(**form.form)\nreturn di... | <|body_start_0|>
users = UserModel.find_by_id(uid)
if not users:
return dict(code=404, msg='not found', data=None)
else:
UserModel.delete(uid)
return dict(code=200, msg='success', data=None)
<|end_body_0|>
<|body_start_1|>
assert current_user.id == ui... | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def delete(self, uid):
"""删除用户 :return:"""
<|body_0|>
def put(self, uid):
"""更新用户资料"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
users = UserModel.find_by_id(uid)
if not users:
return dict(code=404, msg='not found', data... | stack_v2_sparse_classes_75kplus_train_073334 | 3,594 | no_license | [
{
"docstring": "删除用户 :return:",
"name": "delete",
"signature": "def delete(self, uid)"
},
{
"docstring": "更新用户资料",
"name": "put",
"signature": "def put(self, uid)"
}
] | 2 | null | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def delete(self, uid): 删除用户 :return:
- def put(self, uid): 更新用户资料 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def delete(self, uid): 删除用户 :return:
- def put(self, uid): 更新用户资料
<|skeleton|>
class User:
def delete(self, uid):
"""删除用户 :return:"""
<|body_0|>
def put(self, ... | acbc92dfa7a6e0503dcd1606b480bcbc29118718 | <|skeleton|>
class User:
def delete(self, uid):
"""删除用户 :return:"""
<|body_0|>
def put(self, uid):
"""更新用户资料"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class User:
def delete(self, uid):
"""删除用户 :return:"""
users = UserModel.find_by_id(uid)
if not users:
return dict(code=404, msg='not found', data=None)
else:
UserModel.delete(uid)
return dict(code=200, msg='success', data=None)
def put(self, ... | the_stack_v2_python_sparse | app/route/user.py | zerolingchan/lost-and-found-backend | train | 4 | |
a8a5d89d61693b335e8c4e0a282301c9c3e1e1e2 | [
"context = super(CleanupView, self).get_context_data(**kwargs)\ncontext['expired'] = ExamResponse.objects.filter(expiration_datetime__lt=timezone.now()).filter(submitted__isnull=True)\nreturn context",
"for exam_response in ExamResponse.objects.filter(expiration_datetime__lt=timezone.now()).filter(submitted__isnu... | <|body_start_0|>
context = super(CleanupView, self).get_context_data(**kwargs)
context['expired'] = ExamResponse.objects.filter(expiration_datetime__lt=timezone.now()).filter(submitted__isnull=True)
return context
<|end_body_0|>
<|body_start_1|>
for exam_response in ExamResponse.objects... | A view for staff to manually delete expired, unsubmitted ExamResponses. This cleanup does not happen automatically, but this S.O. post suggests a good design, in case automatic cleanup is desired. http://stackoverflow.com/a/11789141 | CleanupView | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleanupView:
"""A view for staff to manually delete expired, unsubmitted ExamResponses. This cleanup does not happen automatically, but this S.O. post suggests a good design, in case automatic cleanup is desired. http://stackoverflow.com/a/11789141"""
def get_context_data(self, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_073335 | 44,749 | permissive | [
{
"docstring": "Pass the list of expired, unsubmitted ERs to the template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Delete expired, unsubmitted ERs. This also deletes the associated *QuestionResponses.",
"name": "form_valid",
"si... | 2 | stack_v2_sparse_classes_30k_train_046636 | Implement the Python class `CleanupView` described below.
Class description:
A view for staff to manually delete expired, unsubmitted ExamResponses. This cleanup does not happen automatically, but this S.O. post suggests a good design, in case automatic cleanup is desired. http://stackoverflow.com/a/11789141
Method s... | Implement the Python class `CleanupView` described below.
Class description:
A view for staff to manually delete expired, unsubmitted ExamResponses. This cleanup does not happen automatically, but this S.O. post suggests a good design, in case automatic cleanup is desired. http://stackoverflow.com/a/11789141
Method s... | 4f5fec75d1425de28a26eb3297ea5d4b0ed96c16 | <|skeleton|>
class CleanupView:
"""A view for staff to manually delete expired, unsubmitted ExamResponses. This cleanup does not happen automatically, but this S.O. post suggests a good design, in case automatic cleanup is desired. http://stackoverflow.com/a/11789141"""
def get_context_data(self, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CleanupView:
"""A view for staff to manually delete expired, unsubmitted ExamResponses. This cleanup does not happen automatically, but this S.O. post suggests a good design, in case automatic cleanup is desired. http://stackoverflow.com/a/11789141"""
def get_context_data(self, **kwargs):
"""Pass... | the_stack_v2_python_sparse | conceptum/exam/views.py | kevincwebb/conceptum | train | 0 |
6ea67e0f9421c4f31a5a3987e3c0413ae68edc63 | [
"self.board_state = game\nself.depth = depth\nself.passed_piece = passed_piece\nself.all_pieces = dict({str(i): bin(i)[2:].zfill(4) for i in range(2 ** 4)}.items())",
"remaining_spots = self.board_state.get_remaining_spots()\nremaining_pieces = list(self.board_state.pieces.keys())\nroot_nodes = []\nfor i in range... | <|body_start_0|>
self.board_state = game
self.depth = depth
self.passed_piece = passed_piece
self.all_pieces = dict({str(i): bin(i)[2:].zfill(4) for i in range(2 ** 4)}.items())
<|end_body_0|>
<|body_start_1|>
remaining_spots = self.board_state.get_remaining_spots()
rema... | The Minimax algorithm for evaluating different moves Author(s): Viktor Enzell Last-edit-date: 10/02/2019 | Minimax | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Minimax:
"""The Minimax algorithm for evaluating different moves Author(s): Viktor Enzell Last-edit-date: 10/02/2019"""
def __init__(self, game, depth, passed_piece):
"""Initialises the class variables :param game: the game instance :param depth: the depth where the algorithm should ... | stack_v2_sparse_classes_75kplus_train_073336 | 5,217 | no_license | [
{
"docstring": "Initialises the class variables :param game: the game instance :param depth: the depth where the algorithm should stop its search",
"name": "__init__",
"signature": "def __init__(self, game, depth, passed_piece)"
},
{
"docstring": "Builds an evaluation tree for each possible move... | 4 | stack_v2_sparse_classes_30k_train_029902 | Implement the Python class `Minimax` described below.
Class description:
The Minimax algorithm for evaluating different moves Author(s): Viktor Enzell Last-edit-date: 10/02/2019
Method signatures and docstrings:
- def __init__(self, game, depth, passed_piece): Initialises the class variables :param game: the game ins... | Implement the Python class `Minimax` described below.
Class description:
The Minimax algorithm for evaluating different moves Author(s): Viktor Enzell Last-edit-date: 10/02/2019
Method signatures and docstrings:
- def __init__(self, game, depth, passed_piece): Initialises the class variables :param game: the game ins... | 69dcc2fa6be35e4f83b35d9c0c13687fa444babd | <|skeleton|>
class Minimax:
"""The Minimax algorithm for evaluating different moves Author(s): Viktor Enzell Last-edit-date: 10/02/2019"""
def __init__(self, game, depth, passed_piece):
"""Initialises the class variables :param game: the game instance :param depth: the depth where the algorithm should ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Minimax:
"""The Minimax algorithm for evaluating different moves Author(s): Viktor Enzell Last-edit-date: 10/02/2019"""
def __init__(self, game, depth, passed_piece):
"""Initialises the class variables :param game: the game instance :param depth: the depth where the algorithm should stop its sear... | the_stack_v2_python_sparse | game_engine/minimax.py | IG-AI/UU-Game | train | 0 |
bc94e853ec2e61902c51dcb07074586eaea352a8 | [
"if dut_node['type'] == NodeType.DUT:\n pci_address1 = Topology.get_interface_pci_addr(dut_node, dut_if1)\n pci_address2 = Topology.get_interface_pci_addr(dut_node, dut_if2)\n ssh = SSH()\n ssh.connect(dut_node)\n arch = Topology.get_node_arch(dut_node)\n cmd = '{fwdir}/tests/dpdk/dpdk_scripts/ini... | <|body_start_0|>
if dut_node['type'] == NodeType.DUT:
pci_address1 = Topology.get_interface_pci_addr(dut_node, dut_if1)
pci_address2 = Topology.get_interface_pci_addr(dut_node, dut_if2)
ssh = SSH()
ssh.connect(dut_node)
arch = Topology.get_node_arch(du... | This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment. | DPDKTools | [
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_environment(dut_node, dut_if1, dut_if2):
"""Initialize the DPDK test environment on the dut_node. Load the module uio and igb_uio, then bind the test NIC t... | stack_v2_sparse_classes_75kplus_train_073337 | 4,999 | permissive | [
{
"docstring": "Initialize the DPDK test environment on the dut_node. Load the module uio and igb_uio, then bind the test NIC to the igb_uio. :param dut_node: Will init the DPDK on this node. :param dut_if1: DUT interface name. :param dut_if2: DUT interface name. :type dut_node: dict :type dut_if1: str :type du... | 4 | null | Implement the Python class `DPDKTools` described below.
Class description:
This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment.
Method signatures and docstrings:
- def initialize_dpdk_environment(dut_node, dut_if1, dut_if2): Initialize the DPDK test environment on the dut_node. ... | Implement the Python class `DPDKTools` described below.
Class description:
This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment.
Method signatures and docstrings:
- def initialize_dpdk_environment(dut_node, dut_if1, dut_if2): Initialize the DPDK test environment on the dut_node. ... | 3151c98618c78e3782e48bbe4d9c8f906c126f69 | <|skeleton|>
class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_environment(dut_node, dut_if1, dut_if2):
"""Initialize the DPDK test environment on the dut_node. Load the module uio and igb_uio, then bind the test NIC t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_environment(dut_node, dut_if1, dut_if2):
"""Initialize the DPDK test environment on the dut_node. Load the module uio and igb_uio, then bind the test NIC to the igb_uio... | the_stack_v2_python_sparse | resources/libraries/python/DPDK/DPDKTools.py | preym17/csit | train | 0 |
c8f1f9494cb7d8da30568f4cc73f5946c9d9f3db | [
"self.cap = capacity\nself.key_pq = PQ()\nself.val_map = {}\nself.counter = itertools.count()",
"ts = next(self.counter)\nif not self.key_pq.contains(key):\n return -1\nself.key_pq.touch(key, ts)\nreturn self.val_map.get(key)",
"ts = next(self.counter)\nif self.cap == 0:\n return\nif self.key_pq.size() ==... | <|body_start_0|>
self.cap = capacity
self.key_pq = PQ()
self.val_map = {}
self.counter = itertools.count()
<|end_body_0|>
<|body_start_1|>
ts = next(self.counter)
if not self.key_pq.contains(key):
return -1
self.key_pq.touch(key, ts)
return se... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_073338 | 2,058 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_test_001248 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 2722c0deafcd094ce64140a9a837b4027d29ed6f | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.key_pq = PQ()
self.val_map = {}
self.counter = itertools.count()
def get(self, key):
""":type key: int :rtype: int"""
ts = next(self.counter)
if not s... | the_stack_v2_python_sparse | 460_LFU_cache_vh/pq.py | chao-shi/lclc | train | 0 | |
457dd9af81349a2347c96adc90fa1d1415ad4743 | [
"self.slot = slot\nself.comm = I2C\nself.host = host\nself.i2c_addr = 35\nself.tp00 = Tp00(self.slot, self.comm, self.host)\nself.tp00.start()",
"self.tp00.lock(self.slot)\ntry:\n send_data = []\n send_data.append({'act': 'w', 'add': self.i2c_addr, 'cmd': 0, 'v': []})\n send_data.append({'act': 'w', 'add... | <|body_start_0|>
self.slot = slot
self.comm = I2C
self.host = host
self.i2c_addr = 35
self.tp00 = Tp00(self.slot, self.comm, self.host)
self.tp00.start()
<|end_body_0|>
<|body_start_1|>
self.tp00.lock(self.slot)
try:
send_data = []
... | #28 Ambient light sensor | Tp28 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tp28:
"""#28 Ambient light sensor"""
def __init__(self, slot, host=None):
"""コンストラクタ"""
<|body_0|>
def get_data(self):
"""データを取得します。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.slot = slot
self.comm = I2C
self.host = hos... | stack_v2_sparse_classes_75kplus_train_073339 | 2,587 | permissive | [
{
"docstring": "コンストラクタ",
"name": "__init__",
"signature": "def __init__(self, slot, host=None)"
},
{
"docstring": "データを取得します。",
"name": "get_data",
"signature": "def get_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035825 | Implement the Python class `Tp28` described below.
Class description:
#28 Ambient light sensor
Method signatures and docstrings:
- def __init__(self, slot, host=None): コンストラクタ
- def get_data(self): データを取得します。 | Implement the Python class `Tp28` described below.
Class description:
#28 Ambient light sensor
Method signatures and docstrings:
- def __init__(self, slot, host=None): コンストラクタ
- def get_data(self): データを取得します。
<|skeleton|>
class Tp28:
"""#28 Ambient light sensor"""
def __init__(self, slot, host=None):
... | 701430da89c45397a63fd522a4f5cf80516f57d0 | <|skeleton|>
class Tp28:
"""#28 Ambient light sensor"""
def __init__(self, slot, host=None):
"""コンストラクタ"""
<|body_0|>
def get_data(self):
"""データを取得します。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tp28:
"""#28 Ambient light sensor"""
def __init__(self, slot, host=None):
"""コンストラクタ"""
self.slot = slot
self.comm = I2C
self.host = host
self.i2c_addr = 35
self.tp00 = Tp00(self.slot, self.comm, self.host)
self.tp00.start()
def get_data(self):... | the_stack_v2_python_sparse | py/tp28.py | cw-tpdev/node-red-contrib-tibbo-pi-p4 | train | 2 |
73de3fb8129f85c8ea3ccf38427052133ad983c7 | [
"self.id = element_id\nif condition is None:\n self.condition = Condition()\nelse:\n self.condition = condition\nif text is None:\n self.text = Text()\nelse:\n self.text = text\nif position is None:\n self.position = Coordinate()\nelse:\n self.position = position\nif alignment is None:\n self.a... | <|body_start_0|>
self.id = element_id
if condition is None:
self.condition = Condition()
else:
self.condition = condition
if text is None:
self.text = Text()
else:
self.text = text
if position is None:
self.posit... | PlotText | [
"AFL-3.0",
"AFL-2.1",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotText:
def __init__(self, element_id='', condition=None, text=None, position=None, alignment=None, style=None):
""":param element_id: z-tree element id :type element_id: str :param condition: plot text display condition :type condition: Condition :param text: text displayed in the plo... | stack_v2_sparse_classes_75kplus_train_073340 | 1,998 | permissive | [
{
"docstring": ":param element_id: z-tree element id :type element_id: str :param condition: plot text display condition :type condition: Condition :param text: text displayed in the plot text :type text: Text :param position: the coordinate the text will be plotted on :type position: Coordinate :param alignmen... | 2 | stack_v2_sparse_classes_30k_train_003883 | Implement the Python class `PlotText` described below.
Class description:
Implement the PlotText class.
Method signatures and docstrings:
- def __init__(self, element_id='', condition=None, text=None, position=None, alignment=None, style=None): :param element_id: z-tree element id :type element_id: str :param conditi... | Implement the Python class `PlotText` described below.
Class description:
Implement the PlotText class.
Method signatures and docstrings:
- def __init__(self, element_id='', condition=None, text=None, position=None, alignment=None, style=None): :param element_id: z-tree element id :type element_id: str :param conditi... | 53ae0b1e07c2b13cb08f7d803623010f508ba1b7 | <|skeleton|>
class PlotText:
def __init__(self, element_id='', condition=None, text=None, position=None, alignment=None, style=None):
""":param element_id: z-tree element id :type element_id: str :param condition: plot text display condition :type condition: Condition :param text: text displayed in the plo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotText:
def __init__(self, element_id='', condition=None, text=None, position=None, alignment=None, style=None):
""":param element_id: z-tree element id :type element_id: str :param condition: plot text display condition :type condition: Condition :param text: text displayed in the plot text :type t... | the_stack_v2_python_sparse | zmodulo/plot/text/plot_text.py | cesslab/ZTree-ZModulo | train | 1 | |
285b7087fb18311a04510e123e05ec35856026c7 | [
"self.logging.info('Looking in memcache for session at ID: \"%s\".' % id)\nself.logging.info('Looking in memcache for encoded session ID: \"%s\"' % self._en(id))\nsession = memcache.get(self._en(id))\nself.logging.info('Memcache result: \"%s\"' % session)\nreturn session",
"self.logging.info('Saving session in me... | <|body_start_0|>
self.logging.info('Looking in memcache for session at ID: "%s".' % id)
self.logging.info('Looking in memcache for encoded session ID: "%s"' % self._en(id))
session = memcache.get(self._en(id))
self.logging.info('Memcache result: "%s"' % session)
return session
<|... | Session loader that loads and saves sessions with memcache | MemcacheSessionLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemcacheSessionLoader:
"""Session loader that loads and saves sessions with memcache"""
def get_session(self, id):
"""Returns a session from memcache, given a session ID."""
<|body_0|>
def put_session(self, id, struct, handler):
"""Saves a session to memcache, fr... | stack_v2_sparse_classes_75kplus_train_073341 | 4,626 | no_license | [
{
"docstring": "Returns a session from memcache, given a session ID.",
"name": "get_session",
"signature": "def get_session(self, id)"
},
{
"docstring": "Saves a session to memcache, from a generated response.",
"name": "put_session",
"signature": "def put_session(self, id, struct, handl... | 2 | stack_v2_sparse_classes_30k_train_042778 | Implement the Python class `MemcacheSessionLoader` described below.
Class description:
Session loader that loads and saves sessions with memcache
Method signatures and docstrings:
- def get_session(self, id): Returns a session from memcache, given a session ID.
- def put_session(self, id, struct, handler): Saves a se... | Implement the Python class `MemcacheSessionLoader` described below.
Class description:
Session loader that loads and saves sessions with memcache
Method signatures and docstrings:
- def get_session(self, id): Returns a session from memcache, given a session ID.
- def put_session(self, id, struct, handler): Saves a se... | b0ea12ff7b56ea86179a97b08055d6ff1b57355c | <|skeleton|>
class MemcacheSessionLoader:
"""Session loader that loads and saves sessions with memcache"""
def get_session(self, id):
"""Returns a session from memcache, given a session ID."""
<|body_0|>
def put_session(self, id, struct, handler):
"""Saves a session to memcache, fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemcacheSessionLoader:
"""Session loader that loads and saves sessions with memcache"""
def get_session(self, id):
"""Returns a session from memcache, given a session ID."""
self.logging.info('Looking in memcache for session at ID: "%s".' % id)
self.logging.info('Looking in memcac... | the_stack_v2_python_sparse | app/openfire/core/sessions/loader.py | openfire/openfire_old | train | 0 |
3b695bfe77dd08f949951029c6ab2893aa6d00c7 | [
"for a in range(1, int(input_val / 2)):\n for b in range(a + 1, int(input_val / 2) + 1):\n c = sqrt(a * a + b * b)\n if c.is_integer() and a + b + c == input_val:\n return a * b * c\nreturn 0",
"for a in range(1, int(input_val * (1 - 1 / sqrt(2))) + 1):\n b = input_val * (input_val ... | <|body_start_0|>
for a in range(1, int(input_val / 2)):
for b in range(a + 1, int(input_val / 2) + 1):
c = sqrt(a * a + b * b)
if c.is_integer() and a + b + c == input_val:
return a * b * c
return 0
<|end_body_0|>
<|body_start_1|>
... | A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc. | Problem0009 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem0009:
"""A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc."""
def solver(input_val):
"""This algorit... | stack_v2_sparse_classes_75kplus_train_073342 | 3,216 | no_license | [
{
"docstring": "This algorithm is sufficiently fast for small enough s, but it doesn’t scale well. If you multiply the value of s by a factor k, the span of each of the two loops is multiplied by the same factor and since the loops are nested, the number of cases to check is multiplied by k2. So if s is doubled... | 4 | stack_v2_sparse_classes_30k_train_051996 | Implement the Python class `Problem0009` described below.
Class description:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc.
Method signatu... | Implement the Python class `Problem0009` described below.
Class description:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc.
Method signatu... | 2db81b6a4c368e18e31d138fb2cccd8304ef0d42 | <|skeleton|>
class Problem0009:
"""A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc."""
def solver(input_val):
"""This algorit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Problem0009:
"""A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc."""
def solver(input_val):
"""This algorithm is suffici... | the_stack_v2_python_sparse | solutions/p009.py | tweber36/project-euler | train | 0 |
859f84e36f77e8d81b4d6664f387a11726119aed | [
"Frame.__init__(self)\nself.pack(expand=YES, fill=BOTH)\nself.master.title('testowanie pol tekstowych')\nself.master.geometry('325x100')\nself.frame1 = Frame(self)\nself.frame1.pack(pady=5)\nself.text1 = Entry(self.frame1, name='tekstowe 1')\nself.text1.bind('<Return>', self.showContents)\nself.text1.pack(side=LEFT... | <|body_start_0|>
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('testowanie pol tekstowych')
self.master.geometry('325x100')
self.frame1 = Frame(self)
self.frame1.pack(pady=5)
self.text1 = Entry(self.frame1, name='tekstowe 1')
self... | DEMONSTYRUJE 4 POLA TEKSTOWE | EntryDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntryDemo:
"""DEMONSTYRUJE 4 POLA TEKSTOWE"""
def __init__(self):
"""tworzy pakuje i binduhje zdaezenia do pol tekstowych"""
<|body_0|>
def showContents(self, events):
"""wyswietl zawartosc pola"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Fr... | stack_v2_sparse_classes_75kplus_train_073343 | 2,084 | no_license | [
{
"docstring": "tworzy pakuje i binduhje zdaezenia do pol tekstowych",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "wyswietl zawartosc pola",
"name": "showContents",
"signature": "def showContents(self, events)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044642 | Implement the Python class `EntryDemo` described below.
Class description:
DEMONSTYRUJE 4 POLA TEKSTOWE
Method signatures and docstrings:
- def __init__(self): tworzy pakuje i binduhje zdaezenia do pol tekstowych
- def showContents(self, events): wyswietl zawartosc pola | Implement the Python class `EntryDemo` described below.
Class description:
DEMONSTYRUJE 4 POLA TEKSTOWE
Method signatures and docstrings:
- def __init__(self): tworzy pakuje i binduhje zdaezenia do pol tekstowych
- def showContents(self, events): wyswietl zawartosc pola
<|skeleton|>
class EntryDemo:
"""DEMONSTYR... | 7bef3e416352a6b5666a729f533d1eb229657008 | <|skeleton|>
class EntryDemo:
"""DEMONSTYRUJE 4 POLA TEKSTOWE"""
def __init__(self):
"""tworzy pakuje i binduhje zdaezenia do pol tekstowych"""
<|body_0|>
def showContents(self, events):
"""wyswietl zawartosc pola"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntryDemo:
"""DEMONSTYRUJE 4 POLA TEKSTOWE"""
def __init__(self):
"""tworzy pakuje i binduhje zdaezenia do pol tekstowych"""
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('testowanie pol tekstowych')
self.master.geometry('325x100')
... | the_stack_v2_python_sparse | zaj7/py64.py | grzegorz-rogalski/pythonGrogal | train | 0 |
f2b2489938fbd6a91761c1cd2b40e678162818ce | [
"super(DecoderWithAttention, self).__init__()\nself.encoder_dim = encoder_dim\nself.attention_dim = attention_dim\nself.embed_dim = embed_dim\nself.decoder_dim = decoder_dim\nself.vocab_size = vocab_size\nself.attention = AttentionModule(encoder_dim, decoder_dim, attention_dim)\nself.embedding = nn.Embedding(vocab_... | <|body_start_0|>
super(DecoderWithAttention, self).__init__()
self.encoder_dim = encoder_dim
self.attention_dim = attention_dim
self.embed_dim = embed_dim
self.decoder_dim = decoder_dim
self.vocab_size = vocab_size
self.attention = AttentionModule(encoder_dim, dec... | DecoderWithAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderWithAttention:
def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5):
""":params attention_dim: 注意力机制的维度 :params embed_dim: 词向量的维度 :params decoder_dim: 解码器的维度 :params vocab_size: 单词总数 :params encoder_dim: 编码图像的特征维度 :params dropout: dr... | stack_v2_sparse_classes_75kplus_train_073344 | 9,580 | no_license | [
{
"docstring": ":params attention_dim: 注意力机制的维度 :params embed_dim: 词向量的维度 :params decoder_dim: 解码器的维度 :params vocab_size: 单词总数 :params encoder_dim: 编码图像的特征维度 :params dropout: dropout 的比例",
"name": "__init__",
"signature": "def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim... | 4 | stack_v2_sparse_classes_30k_train_009963 | Implement the Python class `DecoderWithAttention` described below.
Class description:
Implement the DecoderWithAttention class.
Method signatures and docstrings:
- def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5): :params attention_dim: 注意力机制的维度 :params embed_dim: 词... | Implement the Python class `DecoderWithAttention` described below.
Class description:
Implement the DecoderWithAttention class.
Method signatures and docstrings:
- def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5): :params attention_dim: 注意力机制的维度 :params embed_dim: 词... | ca6f993cfa569250b3116921f4b481d01de36197 | <|skeleton|>
class DecoderWithAttention:
def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5):
""":params attention_dim: 注意力机制的维度 :params embed_dim: 词向量的维度 :params decoder_dim: 解码器的维度 :params vocab_size: 单词总数 :params encoder_dim: 编码图像的特征维度 :params dropout: dr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderWithAttention:
def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5):
""":params attention_dim: 注意力机制的维度 :params embed_dim: 词向量的维度 :params decoder_dim: 解码器的维度 :params vocab_size: 单词总数 :params encoder_dim: 编码图像的特征维度 :params dropout: dropout 的比例"""
... | the_stack_v2_python_sparse | 2018202177/src/codes/models.py | weimingtom/ai20projects | train | 0 | |
f9e59208ab9d9cfc2c543766856cceab19f6147f | [
"self.resolver = resolver\nself.lock_cache = lock_cache\nself.dependency = dependency",
"if self.dependency not in self.lock_cache:\n raise DependencyError(msg='Not found in lock cache: {}'.format(self.lock_cache), dependency=self.dependency)\nself.lock_cache.check_sha1(dependency=self.dependency)\nreturn self... | <|body_start_0|>
self.resolver = resolver
self.lock_cache = lock_cache
self.dependency = dependency
<|end_body_0|>
<|body_start_1|>
if self.dependency not in self.lock_cache:
raise DependencyError(msg='Not found in lock cache: {}'.format(self.lock_cache), dependency=self.dep... | Iterates through a list of resolvers until a path is resolved. | CheckLockCacheResolver | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckLockCacheResolver:
"""Iterates through a list of resolvers until a path is resolved."""
def __init__(self, resolver, lock_cache, dependency):
"""Construct an instance. :param resolvers: A list of resolvers object for the available sources :param lock_cache: A dict containing the... | stack_v2_sparse_classes_75kplus_train_073345 | 1,068 | permissive | [
{
"docstring": "Construct an instance. :param resolvers: A list of resolvers object for the available sources :param lock_cache: A dict containing the lock cache information :param dependency: A Dependency instance.",
"name": "__init__",
"signature": "def __init__(self, resolver, lock_cache, dependency)... | 2 | stack_v2_sparse_classes_30k_train_030427 | Implement the Python class `CheckLockCacheResolver` described below.
Class description:
Iterates through a list of resolvers until a path is resolved.
Method signatures and docstrings:
- def __init__(self, resolver, lock_cache, dependency): Construct an instance. :param resolvers: A list of resolvers object for the a... | Implement the Python class `CheckLockCacheResolver` described below.
Class description:
Iterates through a list of resolvers until a path is resolved.
Method signatures and docstrings:
- def __init__(self, resolver, lock_cache, dependency): Construct an instance. :param resolvers: A list of resolvers object for the a... | ba94d46ce58ac7e936fc45acaca1168ae0d7780b | <|skeleton|>
class CheckLockCacheResolver:
"""Iterates through a list of resolvers until a path is resolved."""
def __init__(self, resolver, lock_cache, dependency):
"""Construct an instance. :param resolvers: A list of resolvers object for the available sources :param lock_cache: A dict containing the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckLockCacheResolver:
"""Iterates through a list of resolvers until a path is resolved."""
def __init__(self, resolver, lock_cache, dependency):
"""Construct an instance. :param resolvers: A list of resolvers object for the available sources :param lock_cache: A dict containing the lock cache i... | the_stack_v2_python_sparse | src/wurf/check_lock_cache_resolver.py | steinwurf/waf | train | 15 |
e8936994808e6f1a18a7dabbcf92d1570ab6efee | [
"super(ParameterizedStrategy, self).__init__(network)\nself.matrix = FeatureMatrix(network)\nself.bound = bound\nself.label = None\nself.covered_count = None\nself.objective_covered = None\nself.strategy = np.random.uniform(-self.bound, self.bound, size=FeatureMatrix.TOTAL_FEATURES)",
"scores = self.matrix.dot(se... | <|body_start_0|>
super(ParameterizedStrategy, self).__init__(network)
self.matrix = FeatureMatrix(network)
self.bound = bound
self.label = None
self.covered_count = None
self.objective_covered = None
self.strategy = np.random.uniform(-self.bound, self.bound, size=... | A strategy that uses a parameterized selection strategy. Parameterized neuron selection strategy is a strategy that parameterized neurons and scores with a selection vector. Please see the following paper for more details: Effective White-Box Testing for Deep Neural Networks with Adaptive Neuron-Selection Strategy http... | ParameterizedStrategy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterizedStrategy:
"""A strategy that uses a parameterized selection strategy. Parameterized neuron selection strategy is a strategy that parameterized neurons and scores with a selection vector. Please see the following paper for more details: Effective White-Box Testing for Deep Neural Netw... | stack_v2_sparse_classes_75kplus_train_073346 | 17,144 | permissive | [
{
"docstring": "Create a parameterized strategy, and initialize its variables. Args: network: A wrapped Keras model with `adapt.Network`. bound: A floating point number indicates the absolute value of minimum and maximum bounds. Example: >>> from adapt import Network >>> from adapt.strategy import Parameterized... | 4 | stack_v2_sparse_classes_30k_val_002526 | Implement the Python class `ParameterizedStrategy` described below.
Class description:
A strategy that uses a parameterized selection strategy. Parameterized neuron selection strategy is a strategy that parameterized neurons and scores with a selection vector. Please see the following paper for more details: Effective... | Implement the Python class `ParameterizedStrategy` described below.
Class description:
A strategy that uses a parameterized selection strategy. Parameterized neuron selection strategy is a strategy that parameterized neurons and scores with a selection vector. Please see the following paper for more details: Effective... | 0b801d2d2e828ac480d1097cb3bdd82b1e25c15b | <|skeleton|>
class ParameterizedStrategy:
"""A strategy that uses a parameterized selection strategy. Parameterized neuron selection strategy is a strategy that parameterized neurons and scores with a selection vector. Please see the following paper for more details: Effective White-Box Testing for Deep Neural Netw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParameterizedStrategy:
"""A strategy that uses a parameterized selection strategy. Parameterized neuron selection strategy is a strategy that parameterized neurons and scores with a selection vector. Please see the following paper for more details: Effective White-Box Testing for Deep Neural Networks with Ada... | the_stack_v2_python_sparse | code/deep/ReMoS/CV_adv/DNNtest/strategy/adapt.py | jindongwang/transferlearning | train | 12,773 |
9019089878591b41be51d0e0c2a06c907eb542c0 | [
"self.params = copy.deepcopy(params)\nself.scope = params['scope']\nsuper(BertModel, self).__init__(name=self.scope)\nself.pad = lambda x: x\nif params['max_encoder_length'] <= 512:\n logging.info('Switching to full attention for short sequences')\n self.params['attention_type'] = 'original_full'\nif self.par... | <|body_start_0|>
self.params = copy.deepcopy(params)
self.scope = params['scope']
super(BertModel, self).__init__(name=self.scope)
self.pad = lambda x: x
if params['max_encoder_length'] <= 512:
logging.info('Switching to full attention for short sequences')
... | BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into SentencePiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]]) params = utils.BigBirdConfig(vocab_size=32000, hidden_size=512, ... | BertModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertModel:
"""BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into SentencePiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]]) params = utils.BigBirdConfi... | stack_v2_sparse_classes_75kplus_train_073347 | 18,962 | permissive | [
{
"docstring": "Constructor for BertModel. Args: params: `BigBirdConfig` dictionary.",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Constructor for BertModel. Args: input_ids: int32 Tensor of shape [batch_size, seq_length]. token_type_ids: (optional) int32 Ten... | 2 | stack_v2_sparse_classes_30k_train_012803 | Implement the Python class `BertModel` described below.
Class description:
BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into SentencePiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) token_type_ids = tf.constant([[0, 0, 1], ... | Implement the Python class `BertModel` described below.
Class description:
BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into SentencePiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) token_type_ids = tf.constant([[0, 0, 1], ... | dc64e0aa3661e2f135e02794b979c2f6af4f3c9a | <|skeleton|>
class BertModel:
"""BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into SentencePiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]]) params = utils.BigBirdConfi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BertModel:
"""BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into SentencePiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]]) params = utils.BigBirdConfig(vocab_size=... | the_stack_v2_python_sparse | pretrain/kobigbird/modeling.py | monologg/KoBigBird | train | 208 |
b048991257749230dd69fe52b14d782f86861ae0 | [
"kafka_connection_strings = os.environ.get('kafka_connection_strings')\nif kafka_connection_strings is not None:\n kafka_connection_strings = kafka_connection_strings.split(',')\n print('Kafka connection strings, extracted from env variable: %s' % kafka_connection_strings)\nelse:\n kafka_connection_strings... | <|body_start_0|>
kafka_connection_strings = os.environ.get('kafka_connection_strings')
if kafka_connection_strings is not None:
kafka_connection_strings = kafka_connection_strings.split(',')
print('Kafka connection strings, extracted from env variable: %s' % kafka_connection_stri... | Storm Spout Logic Responsible for offloading streaming objects containing text data (both real-time and prerecorded). | TextRecorder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextRecorder:
"""Storm Spout Logic Responsible for offloading streaming objects containing text data (both real-time and prerecorded)."""
def initialize(self, stormconf, context):
"""Storm Spout 'constructor method' :param storm_conf: :param context: :return:"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_073348 | 4,138 | no_license | [
{
"docstring": "Storm Spout 'constructor method' :param storm_conf: :param context: :return:",
"name": "initialize",
"signature": "def initialize(self, stormconf, context)"
},
{
"docstring": "Submitter method for Spout, emits captured and segmented text down the pipeline :return:",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_007038 | Implement the Python class `TextRecorder` described below.
Class description:
Storm Spout Logic Responsible for offloading streaming objects containing text data (both real-time and prerecorded).
Method signatures and docstrings:
- def initialize(self, stormconf, context): Storm Spout 'constructor method' :param stor... | Implement the Python class `TextRecorder` described below.
Class description:
Storm Spout Logic Responsible for offloading streaming objects containing text data (both real-time and prerecorded).
Method signatures and docstrings:
- def initialize(self, stormconf, context): Storm Spout 'constructor method' :param stor... | 2177d43c75939a0c4906aa3761772365d4bf79e2 | <|skeleton|>
class TextRecorder:
"""Storm Spout Logic Responsible for offloading streaming objects containing text data (both real-time and prerecorded)."""
def initialize(self, stormconf, context):
"""Storm Spout 'constructor method' :param storm_conf: :param context: :return:"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextRecorder:
"""Storm Spout Logic Responsible for offloading streaming objects containing text data (both real-time and prerecorded)."""
def initialize(self, stormconf, context):
"""Storm Spout 'constructor method' :param storm_conf: :param context: :return:"""
kafka_connection_strings =... | the_stack_v2_python_sparse | deliverable/SourceCode/streaming/src/spouts/text_recorder.py | eldrad294/ICS5114_Practical_Assignment | train | 0 |
2ddecd9114f9d28791355050c36172b4f42fbdf5 | [
"self.info_urls = celebrity.get('Urls')\nself.name = celebrity.get('Name')\nself.id = celebrity.get('Id')\nself.face = RekognitionFace(celebrity.get('Face'))\nself.confidence = celebrity.get('MatchConfidence')\nself.bounding_box = celebrity.get('BoundingBox')\nself.timestamp = timestamp",
"rendering = self.face.t... | <|body_start_0|>
self.info_urls = celebrity.get('Urls')
self.name = celebrity.get('Name')
self.id = celebrity.get('Id')
self.face = RekognitionFace(celebrity.get('Face'))
self.confidence = celebrity.get('MatchConfidence')
self.bounding_box = celebrity.get('BoundingBox')
... | Encapsulates an Amazon Rekognition celebrity. | RekognitionCelebrity | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RekognitionCelebrity:
"""Encapsulates an Amazon Rekognition celebrity."""
def __init__(self, celebrity, timestamp=None):
"""Initializes the celebrity object. :param celebrity: Celebrity data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the ... | stack_v2_sparse_classes_75kplus_train_073349 | 11,689 | permissive | [
{
"docstring": "Initializes the celebrity object. :param celebrity: Celebrity data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the celebrity was detected, if the celebrity was detected in a video.",
"name": "__init__",
"signature": "def __init__(self, celebri... | 2 | stack_v2_sparse_classes_30k_train_045332 | Implement the Python class `RekognitionCelebrity` described below.
Class description:
Encapsulates an Amazon Rekognition celebrity.
Method signatures and docstrings:
- def __init__(self, celebrity, timestamp=None): Initializes the celebrity object. :param celebrity: Celebrity data, in the format returned by Amazon Re... | Implement the Python class `RekognitionCelebrity` described below.
Class description:
Encapsulates an Amazon Rekognition celebrity.
Method signatures and docstrings:
- def __init__(self, celebrity, timestamp=None): Initializes the celebrity object. :param celebrity: Celebrity data, in the format returned by Amazon Re... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class RekognitionCelebrity:
"""Encapsulates an Amazon Rekognition celebrity."""
def __init__(self, celebrity, timestamp=None):
"""Initializes the celebrity object. :param celebrity: Celebrity data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RekognitionCelebrity:
"""Encapsulates an Amazon Rekognition celebrity."""
def __init__(self, celebrity, timestamp=None):
"""Initializes the celebrity object. :param celebrity: Celebrity data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the celebrity was... | the_stack_v2_python_sparse | python/example_code/rekognition/rekognition_objects.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
7997a700d761ba7a127cbf785d8c9e50a9fa305d | [
"dp = [0] * n\np2, p3, p5 = (0, 0, 0)\ndp[0] = 1\nfor i in range(1, n):\n dp[i] = min(dp[p2] * 2, dp[p3] * 3, dp[p5] * 5)\n if dp[p2] * 2 == dp[i]:\n p2 += 1\n if dp[p3] * 3 == dp[i]:\n p3 += 1\n if dp[p5] * 5 == dp[i]:\n p5 += 1\nreturn dp[-1]",
"twos, threes, fives = (0, 2, 2)\n... | <|body_start_0|>
dp = [0] * n
p2, p3, p5 = (0, 0, 0)
dp[0] = 1
for i in range(1, n):
dp[i] = min(dp[p2] * 2, dp[p3] * 3, dp[p5] * 5)
if dp[p2] * 2 == dp[i]:
p2 += 1
if dp[p3] * 3 == dp[i]:
p3 += 1
if dp[p5] *... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nthUglyNumberNotDP(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * n
p2, p3, p5 = (0, 0, 0)
dp[0] = ... | stack_v2_sparse_classes_75kplus_train_073350 | 1,296 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "nthUglyNumber",
"signature": "def nthUglyNumber(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nthUglyNumberNotDP",
"signature": "def nthUglyNumberNotDP(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthUglyNumberNotDP(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthUglyNumberNotDP(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def nthUglyNumber(self, n):
... | b93e46f6526be7a92ebe16f45998527e2b1dc494 | <|skeleton|>
class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nthUglyNumberNotDP(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
dp = [0] * n
p2, p3, p5 = (0, 0, 0)
dp[0] = 1
for i in range(1, n):
dp[i] = min(dp[p2] * 2, dp[p3] * 3, dp[p5] * 5)
if dp[p2] * 2 == dp[i]:
p2 += 1
i... | the_stack_v2_python_sparse | Ugly_number_II.py | stephenosullivan/LT-Code | train | 1 | |
f0a583739c9777f0b9d30126a71a4df0d12ddcd4 | [
"if not quota_max_calls:\n use_rate_limiter = False\nself._projects_locations = None\nself._projects_zones = None\nself._projects_zones_clusters = None\nsuper(ContainerRepositoryClient, self).__init__(API_NAME, versions=['v1', 'v1beta1'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_rate_limit... | <|body_start_0|>
if not quota_max_calls:
use_rate_limiter = False
self._projects_locations = None
self._projects_zones = None
self._projects_zones_clusters = None
super(ContainerRepositoryClient, self).__init__(API_NAME, versions=['v1', 'v1beta1'], quota_max_calls=quo... | Cloud Kubernetes Engine API Respository. | ContainerRepositoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainerRepositoryClient:
"""Cloud Kubernetes Engine API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time ... | stack_v2_sparse_classes_75kplus_train_073351 | 10,586 | permissive | [
{
"docstring": "Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests over. use_rate_limiter (bool): Set to false to disable the use of a rate limiter for this service.",
"name": "__init__",
"signature": "def __... | 4 | stack_v2_sparse_classes_30k_train_010279 | Implement the Python class `ContainerRepositoryClient` described below.
Class description:
Cloud Kubernetes Engine API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <q... | Implement the Python class `ContainerRepositoryClient` described below.
Class description:
Cloud Kubernetes Engine API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <q... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class ContainerRepositoryClient:
"""Cloud Kubernetes Engine API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContainerRepositoryClient:
"""Cloud Kubernetes Engine API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to tra... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_api/container.py | kevensen/forseti-security | train | 1 |
b680dfffaff84fd4e873884b2b637a8d3a6f4cf0 | [
"configs = []\nweight = 0\nfor config in exam_config:\n if 'datetime' in config.keys():\n if config['datetime'] < timezone.now():\n raise ParseError('A data/hora da prova não pode ser menor que a data/hora atual.')\n if 'weight' in config.keys():\n weight += config['weight']\n else... | <|body_start_0|>
configs = []
weight = 0
for config in exam_config:
if 'datetime' in config.keys():
if config['datetime'] < timezone.now():
raise ParseError('A data/hora da prova não pode ser menor que a data/hora atual.')
if 'weight' i... | Serializado de dados dos grupos da disciplina. | SectionSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SectionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def create_exam_config(self, exam_config):
"""Cria as configurações da avaliação."""
<|body_0|>
def create(self, validated_data):
"""Cria e retorna uma nova seção."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_073352 | 3,246 | no_license | [
{
"docstring": "Cria as configurações da avaliação.",
"name": "create_exam_config",
"signature": "def create_exam_config(self, exam_config)"
},
{
"docstring": "Cria e retorna uma nova seção.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "At... | 3 | stack_v2_sparse_classes_30k_train_018343 | Implement the Python class `SectionSerializer` described below.
Class description:
Serializado de dados dos grupos da disciplina.
Method signatures and docstrings:
- def create_exam_config(self, exam_config): Cria as configurações da avaliação.
- def create(self, validated_data): Cria e retorna uma nova seção.
- def ... | Implement the Python class `SectionSerializer` described below.
Class description:
Serializado de dados dos grupos da disciplina.
Method signatures and docstrings:
- def create_exam_config(self, exam_config): Cria as configurações da avaliação.
- def create(self, validated_data): Cria e retorna uma nova seção.
- def ... | 3a8009b17518384c269dfee3c8fe44cbe2567cc0 | <|skeleton|>
class SectionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def create_exam_config(self, exam_config):
"""Cria as configurações da avaliação."""
<|body_0|>
def create(self, validated_data):
"""Cria e retorna uma nova seção."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SectionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def create_exam_config(self, exam_config):
"""Cria as configurações da avaliação."""
configs = []
weight = 0
for config in exam_config:
if 'datetime' in config.keys():
if co... | the_stack_v2_python_sparse | project/alma/sections/serializers.py | VWApplications/VWAlmaAPI | train | 1 |
be7d4862aa1ded6bcb77903ffcd2477196fd6161 | [
"if not os.path.isabs(tarfile_path):\n logger.warning('Only absolute paths are accepted, but got apparent relative path \"%s\".\\nAttempting to convert it to an absolute path.', tarfile_path)\n tarfile_path = os.path.abspath(tarfile_path)\nif not tarfile.is_tarfile(tarfile_path):\n raise IOError('{0} is no... | <|body_start_0|>
if not os.path.isabs(tarfile_path):
logger.warning('Only absolute paths are accepted, but got apparent relative path "%s".\nAttempting to convert it to an absolute path.', tarfile_path)
tarfile_path = os.path.abspath(tarfile_path)
if not tarfile.is_tarfile(tarfil... | Wrapper for a file inside a TAR archive or OVA. | FileInTAR | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileInTAR:
"""Wrapper for a file inside a TAR archive or OVA."""
def __init__(self, tarfile_path, filename, **kwargs):
"""Create a reference to a file contained in a TAR archive. Args: tarfile_path (str): Path to TAR archive to read filename (str): File name in the TAR archive. **kwa... | stack_v2_sparse_classes_75kplus_train_073353 | 13,057 | permissive | [
{
"docstring": "Create a reference to a file contained in a TAR archive. Args: tarfile_path (str): Path to TAR archive to read filename (str): File name in the TAR archive. **kwargs: Passed through to :meth:`FileReference.__init__`. Raises: IOError: if ``tarfile_path`` doesn't reference a TAR file, or the TAR f... | 6 | stack_v2_sparse_classes_30k_train_050311 | Implement the Python class `FileInTAR` described below.
Class description:
Wrapper for a file inside a TAR archive or OVA.
Method signatures and docstrings:
- def __init__(self, tarfile_path, filename, **kwargs): Create a reference to a file contained in a TAR archive. Args: tarfile_path (str): Path to TAR archive to... | Implement the Python class `FileInTAR` described below.
Class description:
Wrapper for a file inside a TAR archive or OVA.
Method signatures and docstrings:
- def __init__(self, tarfile_path, filename, **kwargs): Create a reference to a file contained in a TAR archive. Args: tarfile_path (str): Path to TAR archive to... | 0811b96311881a8293f28f2e300f6bed1b77ee31 | <|skeleton|>
class FileInTAR:
"""Wrapper for a file inside a TAR archive or OVA."""
def __init__(self, tarfile_path, filename, **kwargs):
"""Create a reference to a file contained in a TAR archive. Args: tarfile_path (str): Path to TAR archive to read filename (str): File name in the TAR archive. **kwa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileInTAR:
"""Wrapper for a file inside a TAR archive or OVA."""
def __init__(self, tarfile_path, filename, **kwargs):
"""Create a reference to a file contained in a TAR archive. Args: tarfile_path (str): Path to TAR archive to read filename (str): File name in the TAR archive. **kwargs: Passed t... | the_stack_v2_python_sparse | COT/file_reference.py | glennmatthews/cot | train | 88 |
222ea5650f62c19504934c075a6dbf4c0580bf72 | [
"if namespace is None:\n namespace = {}\nself.namespace = namespace\nif not valuedict:\n valuedict = {}\nself.values = valuedict\nself.default = default",
"if default is __notfound__:\n default = self.default\nif name in self.values:\n value = self.values[name]\nelse:\n try:\n value = self.n... | <|body_start_0|>
if namespace is None:
namespace = {}
self.namespace = namespace
if not valuedict:
valuedict = {}
self.values = valuedict
self.default = default
<|end_body_0|>
<|body_start_1|>
if default is __notfound__:
default = self... | Smart dictionary object | SmartDict | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmartDict:
"""Smart dictionary object"""
def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__):
"""init"""
<|body_0|>
def __getitem__(self, name, default=__notfound__):
"""get item from values *or* namespace"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_073354 | 2,260 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__)"
},
{
"docstring": "get item from values *or* namespace",
"name": "__getitem__",
"signature": "def __getitem__(self, name, default=__notfound__)"
}... | 3 | stack_v2_sparse_classes_30k_train_043480 | Implement the Python class `SmartDict` described below.
Class description:
Smart dictionary object
Method signatures and docstrings:
- def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__): init
- def __getitem__(self, name, default=__notfound__): get item from values *or* namespace
- def ... | Implement the Python class `SmartDict` described below.
Class description:
Smart dictionary object
Method signatures and docstrings:
- def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__): init
- def __getitem__(self, name, default=__notfound__): get item from values *or* namespace
- def ... | 0f2e6a2d1c71f104b1522fd68ec01b9f9f3b92f9 | <|skeleton|>
class SmartDict:
"""Smart dictionary object"""
def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__):
"""init"""
<|body_0|>
def __getitem__(self, name, default=__notfound__):
"""get item from values *or* namespace"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmartDict:
"""Smart dictionary object"""
def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__):
"""init"""
if namespace is None:
namespace = {}
self.namespace = namespace
if not valuedict:
valuedict = {}
self.valu... | the_stack_v2_python_sparse | apps/TCPB_-_Expressions/src/smartdict.py | ThreatConnect-Inc/threatconnect-playbooks | train | 76 |
62ef5b693f5b3d7b7241bed16918afb55a92b034 | [
"super().__init__(env)\nself._prefix = prefix\nself._episode_lengths: List[int] = []\nself._episode_rewards: List[float] = []\nself._timestamps: List[float] = []\nself._random_seed: Optional[int] = None\nself._steps = None\nself._total_steps = 0\nself._rewards = None\nself._done = False\nself._set_attributes()",
... | <|body_start_0|>
super().__init__(env)
self._prefix = prefix
self._episode_lengths: List[int] = []
self._episode_rewards: List[float] = []
self._timestamps: List[float] = []
self._random_seed: Optional[int] = None
self._steps = None
self._total_steps = 0
... | Stats recorder. | StatsRecorder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsRecorder:
"""Stats recorder."""
def __init__(self, env: gym.Env, prefix: str=''):
"""Initialize stats recorder. :param env: the environment to monitor. :param prefix: the prefix to add to statistics attributes."""
<|body_0|>
def _set_attributes(self):
"""Set... | stack_v2_sparse_classes_75kplus_train_073355 | 4,840 | no_license | [
{
"docstring": "Initialize stats recorder. :param env: the environment to monitor. :param prefix: the prefix to add to statistics attributes.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, prefix: str='')"
},
{
"docstring": "Set main attributes with the prefix.",
"name"... | 6 | null | Implement the Python class `StatsRecorder` described below.
Class description:
Stats recorder.
Method signatures and docstrings:
- def __init__(self, env: gym.Env, prefix: str=''): Initialize stats recorder. :param env: the environment to monitor. :param prefix: the prefix to add to statistics attributes.
- def _set_... | Implement the Python class `StatsRecorder` described below.
Class description:
Stats recorder.
Method signatures and docstrings:
- def __init__(self, env: gym.Env, prefix: str=''): Initialize stats recorder. :param env: the environment to monitor. :param prefix: the prefix to add to statistics attributes.
- def _set_... | b516ffa46e9df6a67fbda7546f9128c23920c460 | <|skeleton|>
class StatsRecorder:
"""Stats recorder."""
def __init__(self, env: gym.Env, prefix: str=''):
"""Initialize stats recorder. :param env: the environment to monitor. :param prefix: the prefix to add to statistics attributes."""
<|body_0|>
def _set_attributes(self):
"""Set... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatsRecorder:
"""Stats recorder."""
def __init__(self, env: gym.Env, prefix: str=''):
"""Initialize stats recorder. :param env: the environment to monitor. :param prefix: the prefix to add to statistics attributes."""
super().__init__(env)
self._prefix = prefix
self._epis... | the_stack_v2_python_sparse | src/wrappers/utils.py | marcofavorito/PAC-RDPs-code | train | 2 |
23d0729ffa8ad03b581b74c8f37f9069c98c8d5e | [
"if sound.is_equal(a):\n return ee\nelif sound.is_equal(a.lengthen()):\n return ee.lengthen()\nelif sound.is_equal(o):\n return oee\nelif sound.is_equal(o.lengthen()):\n return oee.lengthen()\nelif sound.is_equal(u):\n return y\nelif sound.is_equal(u.lengthen()):\n return y.lengthen()\nif sound.is... | <|body_start_0|>
if sound.is_equal(a):
return ee
elif sound.is_equal(a.lengthen()):
return ee.lengthen()
elif sound.is_equal(o):
return oee
elif sound.is_equal(o.lengthen()):
return oee.lengthen()
elif sound.is_equal(u):
... | Class that applies position-dependent phonological transformation | OldNorsePhonology | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OldNorsePhonology:
"""Class that applies position-dependent phonological transformation"""
def phonetic_i_umlaut(sound: Vowel) -> Vowel:
""">>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a) >>> umlaut_a.ipar 'ɛ' >>> umlaut_au = OldNorsePhonology.phonetic_i_umlaut(DIPHTHONGS_IPA_c... | stack_v2_sparse_classes_75kplus_train_073356 | 10,883 | permissive | [
{
"docstring": ">>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a) >>> umlaut_a.ipar 'ɛ' >>> umlaut_au = OldNorsePhonology.phonetic_i_umlaut(DIPHTHONGS_IPA_class[\"au\"]) >>> umlaut_au.ipar 'ɐy' :param sound: vowel :return: transformed vowel",
"name": "phonetic_i_umlaut",
"signature": "def phonetic_i... | 4 | stack_v2_sparse_classes_30k_train_051007 | Implement the Python class `OldNorsePhonology` described below.
Class description:
Class that applies position-dependent phonological transformation
Method signatures and docstrings:
- def phonetic_i_umlaut(sound: Vowel) -> Vowel: >>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a) >>> umlaut_a.ipar 'ɛ' >>> umlaut_... | Implement the Python class `OldNorsePhonology` described below.
Class description:
Class that applies position-dependent phonological transformation
Method signatures and docstrings:
- def phonetic_i_umlaut(sound: Vowel) -> Vowel: >>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a) >>> umlaut_a.ipar 'ɛ' >>> umlaut_... | 8a122113d2509aef85bebba8e2c303471c107ff4 | <|skeleton|>
class OldNorsePhonology:
"""Class that applies position-dependent phonological transformation"""
def phonetic_i_umlaut(sound: Vowel) -> Vowel:
""">>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a) >>> umlaut_a.ipar 'ɛ' >>> umlaut_au = OldNorsePhonology.phonetic_i_umlaut(DIPHTHONGS_IPA_c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OldNorsePhonology:
"""Class that applies position-dependent phonological transformation"""
def phonetic_i_umlaut(sound: Vowel) -> Vowel:
""">>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a) >>> umlaut_a.ipar 'ɛ' >>> umlaut_au = OldNorsePhonology.phonetic_i_umlaut(DIPHTHONGS_IPA_class["au"]) >... | the_stack_v2_python_sparse | src/cltk/phonology/non/transcription.py | cltk/cltk | train | 847 |
6282cf24458897954dc7428dc0083cf2541e03a1 | [
"super(DollarVolumeSymbolHandler, self).__init__(portfolio_handlers)\nself.n = n\nself.symbols = symbols",
"bars = gets.prices(date, symbols=self.symbols)\ndv = bars.ix['adj_price_close', -1, :] * bars.ix['adj_volume', -1, :]\nrank = dv.sort_values(ascending=False).dropna()\nreturn self.append_positions(list(rank... | <|body_start_0|>
super(DollarVolumeSymbolHandler, self).__init__(portfolio_handlers)
self.n = n
self.symbols = symbols
<|end_body_0|>
<|body_start_1|>
bars = gets.prices(date, symbols=self.symbols)
dv = bars.ix['adj_price_close', -1, :] * bars.ix['adj_volume', -1, :]
ran... | Dollar Volume Symbol Handler Class The dollar volume symbol handler selects assets by ranking stocks according to the total dollar volume transacted during the previous trading session. The symbol handler ignores the S&P 100 and S&P 500 indices which have huge volume. | DollarVolumeSymbolHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DollarVolumeSymbolHandler:
"""Dollar Volume Symbol Handler Class The dollar volume symbol handler selects assets by ranking stocks according to the total dollar volume transacted during the previous trading session. The symbol handler ignores the S&P 100 and S&P 500 indices which have huge volume... | stack_v2_sparse_classes_75kplus_train_073357 | 1,639 | permissive | [
{
"docstring": "Initialize parameters of the dollar volume symbol handler object. Parameters ---------- n: Integer. The number of assets to take from the ranking according to dollar volume; i.e. the top stocks according to dollar volume during the previous trading session. symbols (optional): List of strings. A... | 2 | stack_v2_sparse_classes_30k_train_031519 | Implement the Python class `DollarVolumeSymbolHandler` described below.
Class description:
Dollar Volume Symbol Handler Class The dollar volume symbol handler selects assets by ranking stocks according to the total dollar volume transacted during the previous trading session. The symbol handler ignores the S&P 100 and... | Implement the Python class `DollarVolumeSymbolHandler` described below.
Class description:
Dollar Volume Symbol Handler Class The dollar volume symbol handler selects assets by ranking stocks according to the total dollar volume transacted during the previous trading session. The symbol handler ignores the S&P 100 and... | e2e9d638c68947d24f1260d35a3527dd84c2523f | <|skeleton|>
class DollarVolumeSymbolHandler:
"""Dollar Volume Symbol Handler Class The dollar volume symbol handler selects assets by ranking stocks according to the total dollar volume transacted during the previous trading session. The symbol handler ignores the S&P 100 and S&P 500 indices which have huge volume... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DollarVolumeSymbolHandler:
"""Dollar Volume Symbol Handler Class The dollar volume symbol handler selects assets by ranking stocks according to the total dollar volume transacted during the previous trading session. The symbol handler ignores the S&P 100 and S&P 500 indices which have huge volume."""
def... | the_stack_v2_python_sparse | odin/handlers/symbol_handler/dollar_volume_symbol_handler.py | stjordanis/Odin | train | 0 |
1304f8f616f91930fafd0307a67fd2fb1c24ad44 | [
"next_index = next_object_key(self)\nelement_ids = self.get_member_ids_from_nodes_ids(node_A, node_B)\nif element_ids != None:\n print('There is more than one member with the same end nodes. Ensure they have different offsets.')\nmember = Member(node_A, node_B, section_id, fixity_A, fixity_B, type, cable_length)... | <|body_start_0|>
next_index = next_object_key(self)
element_ids = self.get_member_ids_from_nodes_ids(node_A, node_B)
if element_ids != None:
print('There is more than one member with the same end nodes. Ensure they have different offsets.')
member = Member(node_A, node_B, sec... | Creates an instance of the SkyCiv Members class. | Members | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Members:
"""Creates an instance of the SkyCiv Members class."""
def add(self, node_A: int, node_B: int, section_id: int, fixity_A: str='FFFFFF', fixity_B: str='FFFFFF', type: Literal['normal', 'normal_continuous', 'cable', 'rigid']='normal', cable_length: float=None) -> int:
"""Creat... | stack_v2_sparse_classes_75kplus_train_073358 | 2,666 | permissive | [
{
"docstring": "Create a member with the next available ID. Args: node_A (int): The ID of the node at the beginning of the member. node_B (int): The ID of the node at the end of the member. section_id (int): The ID of the section to apply to the member. fixity_A (str, optional): See docs for restraint code. htt... | 2 | stack_v2_sparse_classes_30k_train_021292 | Implement the Python class `Members` described below.
Class description:
Creates an instance of the SkyCiv Members class.
Method signatures and docstrings:
- def add(self, node_A: int, node_B: int, section_id: int, fixity_A: str='FFFFFF', fixity_B: str='FFFFFF', type: Literal['normal', 'normal_continuous', 'cable', '... | Implement the Python class `Members` described below.
Class description:
Creates an instance of the SkyCiv Members class.
Method signatures and docstrings:
- def add(self, node_A: int, node_B: int, section_id: int, fixity_A: str='FFFFFF', fixity_B: str='FFFFFF', type: Literal['normal', 'normal_continuous', 'cable', '... | 1cf3dad7f8d451760df02886df41684add72a4eb | <|skeleton|>
class Members:
"""Creates an instance of the SkyCiv Members class."""
def add(self, node_A: int, node_B: int, section_id: int, fixity_A: str='FFFFFF', fixity_B: str='FFFFFF', type: Literal['normal', 'normal_continuous', 'cable', 'rigid']='normal', cable_length: float=None) -> int:
"""Creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Members:
"""Creates an instance of the SkyCiv Members class."""
def add(self, node_A: int, node_B: int, section_id: int, fixity_A: str='FFFFFF', fixity_B: str='FFFFFF', type: Literal['normal', 'normal_continuous', 'cable', 'rigid']='normal', cable_length: float=None) -> int:
"""Create a member wi... | the_stack_v2_python_sparse | src/skyciv/classes/model/components/members/members.py | osasanchezme/skyciv-pip | train | 0 |
e6172e67d1d14a607b27b81c2769837ea070138a | [
"_table_1 = DataFrame({'a': [1.0, 2.0, 3.0], 'b': [np.nan, np.nan, 3.0], 'c': [1.0, 4.0, 5.0], 'd': [np.nan, np.nan, np.nan]})\n_cleanings = [{'operator': 'default_value', 'columns': ['a'], 'value': 0.0}]\n_vc = VariableCleaner(_table_1)\n_vc.clean(_cleanings)\nassert_frame_equal(_table_1, _vc.frame)",
"_table_1 ... | <|body_start_0|>
_table_1 = DataFrame({'a': [1.0, 2.0, 3.0], 'b': [np.nan, np.nan, 3.0], 'c': [1.0, 4.0, 5.0], 'd': [np.nan, np.nan, np.nan]})
_cleanings = [{'operator': 'default_value', 'columns': ['a'], 'value': 0.0}]
_vc = VariableCleaner(_table_1)
_vc.clean(_cleanings)
assert... | Tests for the ``preprocess._clean_variables`` module. | CleanDefaultValueSingleColumnTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleanDefaultValueSingleColumnTests:
"""Tests for the ``preprocess._clean_variables`` module."""
def test_clean_default_1():
"""Test cleaning a single column with no NaN values."""
<|body_0|>
def test_clean_default_2():
"""Test cleaning a single column with some N... | stack_v2_sparse_classes_75kplus_train_073359 | 5,264 | permissive | [
{
"docstring": "Test cleaning a single column with no NaN values.",
"name": "test_clean_default_1",
"signature": "def test_clean_default_1()"
},
{
"docstring": "Test cleaning a single column with some NaN values.",
"name": "test_clean_default_2",
"signature": "def test_clean_default_2()"... | 3 | stack_v2_sparse_classes_30k_train_039226 | Implement the Python class `CleanDefaultValueSingleColumnTests` described below.
Class description:
Tests for the ``preprocess._clean_variables`` module.
Method signatures and docstrings:
- def test_clean_default_1(): Test cleaning a single column with no NaN values.
- def test_clean_default_2(): Test cleaning a sing... | Implement the Python class `CleanDefaultValueSingleColumnTests` described below.
Class description:
Tests for the ``preprocess._clean_variables`` module.
Method signatures and docstrings:
- def test_clean_default_1(): Test cleaning a single column with no NaN values.
- def test_clean_default_2(): Test cleaning a sing... | 2e89bc55a61ce2a4ce77646bb427f5b3040f672c | <|skeleton|>
class CleanDefaultValueSingleColumnTests:
"""Tests for the ``preprocess._clean_variables`` module."""
def test_clean_default_1():
"""Test cleaning a single column with no NaN values."""
<|body_0|>
def test_clean_default_2():
"""Test cleaning a single column with some N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CleanDefaultValueSingleColumnTests:
"""Tests for the ``preprocess._clean_variables`` module."""
def test_clean_default_1():
"""Test cleaning a single column with no NaN values."""
_table_1 = DataFrame({'a': [1.0, 2.0, 3.0], 'b': [np.nan, np.nan, 3.0], 'c': [1.0, 4.0, 5.0], 'd': [np.nan, n... | the_stack_v2_python_sparse | numom2b_preprocessing/unittests/cleaning_tests/test_clean_default.py | hayesall/nuMoM2b_preprocessing | train | 2 |
6e14bf0472e328dbac299c7c80ed27b62685cbd9 | [
"if out_frames not in self.VALID_OUT_FRAMES:\n raise ValueError('Invalid number of frames in desired output: %d' % out_frames)\nsuper(Deconv, self).__init__()\nself.deconv_name = deconv_name\nself.out_frames = out_frames\nself.conv3d_1a = nn.Conv3d(in_channels=in_channels, out_channels=256, kernel_size=(3, 3, 3)... | <|body_start_0|>
if out_frames not in self.VALID_OUT_FRAMES:
raise ValueError('Invalid number of frames in desired output: %d' % out_frames)
super(Deconv, self).__init__()
self.deconv_name = deconv_name
self.out_frames = out_frames
self.conv3d_1a = nn.Conv3d(in_channe... | Class representing the Deconvolutional network that is used to estimate the video keypoints. | Deconv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deconv:
"""Class representing the Deconvolutional network that is used to estimate the video keypoints."""
def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'):
"""Initializes the Deconvolutional network. :param in_channels: (int) The number of channels ... | stack_v2_sparse_classes_75kplus_train_073360 | 2,862 | no_license | [
{
"docstring": "Initializes the Deconvolutional network. :param in_channels: (int) The number of channels in the input tensor. :param out_frames: (int) The number of frames desired in the generated output video. Legal values: 8, 16 :param deconv_name: (str, optional) The name of the network (default 'Deconvolut... | 2 | stack_v2_sparse_classes_30k_train_010084 | Implement the Python class `Deconv` described below.
Class description:
Class representing the Deconvolutional network that is used to estimate the video keypoints.
Method signatures and docstrings:
- def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'): Initializes the Deconvolutional n... | Implement the Python class `Deconv` described below.
Class description:
Class representing the Deconvolutional network that is used to estimate the video keypoints.
Method signatures and docstrings:
- def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'): Initializes the Deconvolutional n... | 6de28b5a8992f6122f2e9813de8b92d9e97ccbf3 | <|skeleton|>
class Deconv:
"""Class representing the Deconvolutional network that is used to estimate the video keypoints."""
def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'):
"""Initializes the Deconvolutional network. :param in_channels: (int) The number of channels ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Deconv:
"""Class representing the Deconvolutional network that is used to estimate the video keypoints."""
def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'):
"""Initializes the Deconvolutional network. :param in_channels: (int) The number of channels in the input ... | the_stack_v2_python_sparse | archive/phase1/netWith2828i3dOutput/deconv3.py | schatzkara/REU2019 | train | 0 |
9aa0cb6c58524236b9584c48375f685c4253dc65 | [
"self._init_args = locals()\nself.rl_alg_factory = rl_alg_factory\nself.env = env_factory()\nself.frame = 0\nself.rl_alg = rl_alg_factory(self.env.observation_space, self.env.action_space, log_time_interval=log_time_interval)\nself.env.set_num_envs(self.rl_alg.num_actors)\nself.states = self.env.reset()\nself.all_r... | <|body_start_0|>
self._init_args = locals()
self.rl_alg_factory = rl_alg_factory
self.env = env_factory()
self.frame = 0
self.rl_alg = rl_alg_factory(self.env.observation_space, self.env.action_space, log_time_interval=log_time_interval)
self.env.set_num_envs(self.rl_alg.... | GymWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GymWrapper:
def __init__(self, rl_alg_factory: Callable, env_factory: Callable, log_time_interval=5, log_path=None, tag=''):
"""Simplifies training of RL algorithms with gym environments. Args: rl_alg_factory: RL algorithm factory / type. env: Environment factory. Accepted values are env... | stack_v2_sparse_classes_75kplus_train_073361 | 2,707 | permissive | [
{
"docstring": "Simplifies training of RL algorithms with gym environments. Args: rl_alg_factory: RL algorithm factory / type. env: Environment factory. Accepted values are environment name, function which returns `gym.Env`, `gym.Env` object log_time_interval: Tensorboard logging interval in seconds. log_path: ... | 3 | stack_v2_sparse_classes_30k_train_052205 | Implement the Python class `GymWrapper` described below.
Class description:
Implement the GymWrapper class.
Method signatures and docstrings:
- def __init__(self, rl_alg_factory: Callable, env_factory: Callable, log_time_interval=5, log_path=None, tag=''): Simplifies training of RL algorithms with gym environments. A... | Implement the Python class `GymWrapper` described below.
Class description:
Implement the GymWrapper class.
Method signatures and docstrings:
- def __init__(self, rl_alg_factory: Callable, env_factory: Callable, log_time_interval=5, log_path=None, tag=''): Simplifies training of RL algorithms with gym environments. A... | 04cd026116bfbd7353274f8dbb4951cddfc66e6b | <|skeleton|>
class GymWrapper:
def __init__(self, rl_alg_factory: Callable, env_factory: Callable, log_time_interval=5, log_path=None, tag=''):
"""Simplifies training of RL algorithms with gym environments. Args: rl_alg_factory: RL algorithm factory / type. env: Environment factory. Accepted values are env... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GymWrapper:
def __init__(self, rl_alg_factory: Callable, env_factory: Callable, log_time_interval=5, log_path=None, tag=''):
"""Simplifies training of RL algorithms with gym environments. Args: rl_alg_factory: RL algorithm factory / type. env: Environment factory. Accepted values are environment name,... | the_stack_v2_python_sparse | ppo_pytorch/common/gym_wrapper.py | famishedrover/pytorch-rl-kit | train | 0 | |
48f1522337e0c96dcfa1ce7627c658e4ff7c7d66 | [
"user = User.from_db(username)\nif not user:\n api.abort(404, 'No such user')\nreturn (user, 200)",
"args = right_add_parser.parse_args()\nuser = User.from_db(username)\nif not user:\n api.abort(404, 'No such user')\ntry:\n for right_name in args.rights:\n user.add_right_from_string(right_name)\ne... | <|body_start_0|>
user = User.from_db(username)
if not user:
api.abort(404, 'No such user')
return (user, 200)
<|end_body_0|>
<|body_start_1|>
args = right_add_parser.parse_args()
user = User.from_db(username)
if not user:
api.abort(404, 'No such u... | UserRight | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRight:
def get(self, username):
"""Get a user's rights"""
<|body_0|>
def post(self, username):
"""Add one or multiple rights to a user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = User.from_db(username)
if not user:
... | stack_v2_sparse_classes_75kplus_train_073362 | 12,864 | no_license | [
{
"docstring": "Get a user's rights",
"name": "get",
"signature": "def get(self, username)"
},
{
"docstring": "Add one or multiple rights to a user",
"name": "post",
"signature": "def post(self, username)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018899 | Implement the Python class `UserRight` described below.
Class description:
Implement the UserRight class.
Method signatures and docstrings:
- def get(self, username): Get a user's rights
- def post(self, username): Add one or multiple rights to a user | Implement the Python class `UserRight` described below.
Class description:
Implement the UserRight class.
Method signatures and docstrings:
- def get(self, username): Get a user's rights
- def post(self, username): Add one or multiple rights to a user
<|skeleton|>
class UserRight:
def get(self, username):
... | ab8c722673d5c43e5bd40c4747c374a73ea56ccc | <|skeleton|>
class UserRight:
def get(self, username):
"""Get a user's rights"""
<|body_0|>
def post(self, username):
"""Add one or multiple rights to a user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRight:
def get(self, username):
"""Get a user's rights"""
user = User.from_db(username)
if not user:
api.abort(404, 'No such user')
return (user, 200)
def post(self, username):
"""Add one or multiple rights to a user"""
args = right_add_pars... | the_stack_v2_python_sparse | kovaak_stats_back/kovaak_stats/api/users.py | ftsn/kovaak-stats-viewer | train | 0 | |
640483cd24c17f240b3a4df15091941e23b3743a | [
"next_space = string.find(' ')\nnext_nl = string.find('\\n')\nif next_space == -1:\n return next_nl\nif next_nl == -1:\n return next_space\nreturn min(next_space, next_nl)",
"words = []\ncurrent_word = RenderedText()\nfor basic_rendered_text in iterable:\n if not basic_rendered_text.plain:\n curre... | <|body_start_0|>
next_space = string.find(' ')
next_nl = string.find('\n')
if next_space == -1:
return next_nl
if next_nl == -1:
return next_space
return min(next_space, next_nl)
<|end_body_0|>
<|body_start_1|>
words = []
current_word = Re... | Format the given text, split it in words, do line wrapping... | Formatter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Formatter:
"""Format the given text, split it in words, do line wrapping..."""
def get_next_space_index(string):
"""Find the index of the next ' ' or ' ' character."""
<|body_0|>
def get_words(cls, iterable):
"""Collect blurbs of text and return words. Given an i... | stack_v2_sparse_classes_75kplus_train_073363 | 28,131 | permissive | [
{
"docstring": "Find the index of the next ' ' or ' ' character.",
"name": "get_next_space_index",
"signature": "def get_next_space_index(string)"
},
{
"docstring": "Collect blurbs of text and return words. Given an iterator over basic RenderedText (i.e. RenderedText generated by RenderedText.te... | 3 | null | Implement the Python class `Formatter` described below.
Class description:
Format the given text, split it in words, do line wrapping...
Method signatures and docstrings:
- def get_next_space_index(string): Find the index of the next ' ' or ' ' character.
- def get_words(cls, iterable): Collect blurbs of text and ret... | Implement the Python class `Formatter` described below.
Class description:
Format the given text, split it in words, do line wrapping...
Method signatures and docstrings:
- def get_next_space_index(string): Find the index of the next ' ' or ' ' character.
- def get_words(cls, iterable): Collect blurbs of text and ret... | d3d124af392da85422d303242e43673a817b360f | <|skeleton|>
class Formatter:
"""Format the given text, split it in words, do line wrapping..."""
def get_next_space_index(string):
"""Find the index of the next ' ' or ' ' character."""
<|body_0|>
def get_words(cls, iterable):
"""Collect blurbs of text and return words. Given an i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Formatter:
"""Format the given text, split it in words, do line wrapping..."""
def get_next_space_index(string):
"""Find the index of the next ' ' or ' ' character."""
next_space = string.find(' ')
next_nl = string.find('\n')
if next_space == -1:
return next_nl... | the_stack_v2_python_sparse | checker.py | L-Sherry/Localize-Me-Tools | train | 1 |
fd9c87a41a3c0b049ef3bd5c2e960f248cbd6960 | [
"self.tree = KDTree(x, leafsize=leafsize)\nself.x = x\nself.nnear = nnear",
"node_xy = np.asarray(node_xy)\nqdim = node_xy.ndim\nif qdim == 1:\n node_xy = np.array([node_xy])\nself.distances, self.ix = self.tree.query(node_xy, k=self.nnear, eps=eps)\nw = 1 / self.distances ** p\nif weights is not None:\n w ... | <|body_start_0|>
self.tree = KDTree(x, leafsize=leafsize)
self.x = x
self.nnear = nnear
<|end_body_0|>
<|body_start_1|>
node_xy = np.asarray(node_xy)
qdim = node_xy.ndim
if qdim == 1:
node_xy = np.array([node_xy])
self.distances, self.ix = self.tree.q... | Inverse-distance-weighted interpolation using KDTree Examples -------- tree = interp_2d.Invdisttree(obs_xy) # initialize KDTree with observational points tree.weights(node_xy) # calculate weights for each node. values_v = tree.interp(obs.temperature.values) # perform spatial interpolation with the calculated weights fr... | Invdisttree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Invdisttree:
"""Inverse-distance-weighted interpolation using KDTree Examples -------- tree = interp_2d.Invdisttree(obs_xy) # initialize KDTree with observational points tree.weights(node_xy) # calculate weights for each node. values_v = tree.interp(obs.temperature.values) # perform spatial inter... | stack_v2_sparse_classes_75kplus_train_073364 | 4,669 | permissive | [
{
"docstring": "Constructor using coordinates and data Parameters ---------- x : np.ndarray, shape (n,2) Coordinates of data points n is the number of data points nnear : positive int, optional The number of nearest neighbors to be included, the default is 10. leafsize: positive int, optional The number of poin... | 3 | stack_v2_sparse_classes_30k_train_002052 | Implement the Python class `Invdisttree` described below.
Class description:
Inverse-distance-weighted interpolation using KDTree Examples -------- tree = interp_2d.Invdisttree(obs_xy) # initialize KDTree with observational points tree.weights(node_xy) # calculate weights for each node. values_v = tree.interp(obs.temp... | Implement the Python class `Invdisttree` described below.
Class description:
Inverse-distance-weighted interpolation using KDTree Examples -------- tree = interp_2d.Invdisttree(obs_xy) # initialize KDTree with observational points tree.weights(node_xy) # calculate weights for each node. values_v = tree.interp(obs.temp... | 45b132fe0b287a87e26add8300b38b04a7ab2dbe | <|skeleton|>
class Invdisttree:
"""Inverse-distance-weighted interpolation using KDTree Examples -------- tree = interp_2d.Invdisttree(obs_xy) # initialize KDTree with observational points tree.weights(node_xy) # calculate weights for each node. values_v = tree.interp(obs.temperature.values) # perform spatial inter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Invdisttree:
"""Inverse-distance-weighted interpolation using KDTree Examples -------- tree = interp_2d.Invdisttree(obs_xy) # initialize KDTree with observational points tree.weights(node_xy) # calculate weights for each node. values_v = tree.interp(obs.temperature.values) # perform spatial interpolation with... | the_stack_v2_python_sparse | schimpy/interp_2d.py | CADWRDeltaModeling/schimpy | train | 7 |
c02a10014c61d560668dc1b197b34400f50ef1ac | [
"self.resolution = resolution\nself.fps = fps\nself.frame_size_bytes = resolution[0] * resolution[1] * 3",
"compressed_frame_size = compression.value / self.fps\ncurr_ts = 0.0\nframes = []\nfor i in range(0, self.fps * duration):\n frames.append(Frame(curr_ts, compressed_frame_size))\n curr_ts += 1.0 / self... | <|body_start_0|>
self.resolution = resolution
self.fps = fps
self.frame_size_bytes = resolution[0] * resolution[1] * 3
<|end_body_0|>
<|body_start_1|>
compressed_frame_size = compression.value / self.fps
curr_ts = 0.0
frames = []
for i in range(0, self.fps * dura... | FixedSizeStream | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedSizeStream:
def __init__(self, resolution, fps):
"""Params: - resolution: resolution of video, (l, w) - fps: frame rate of video"""
<|body_0|>
def generate_stream(self, duration, compression):
"""Generates a stream of frames of the given duration Params: - durat... | stack_v2_sparse_classes_75kplus_train_073365 | 1,703 | no_license | [
{
"docstring": "Params: - resolution: resolution of video, (l, w) - fps: frame rate of video",
"name": "__init__",
"signature": "def __init__(self, resolution, fps)"
},
{
"docstring": "Generates a stream of frames of the given duration Params: - duration: duration of video in seconds - compressi... | 3 | stack_v2_sparse_classes_30k_train_041220 | Implement the Python class `FixedSizeStream` described below.
Class description:
Implement the FixedSizeStream class.
Method signatures and docstrings:
- def __init__(self, resolution, fps): Params: - resolution: resolution of video, (l, w) - fps: frame rate of video
- def generate_stream(self, duration, compression)... | Implement the Python class `FixedSizeStream` described below.
Class description:
Implement the FixedSizeStream class.
Method signatures and docstrings:
- def __init__(self, resolution, fps): Params: - resolution: resolution of video, (l, w) - fps: frame rate of video
- def generate_stream(self, duration, compression)... | da69867078aa570736dde82c25c85ebf7d7eaacb | <|skeleton|>
class FixedSizeStream:
def __init__(self, resolution, fps):
"""Params: - resolution: resolution of video, (l, w) - fps: frame rate of video"""
<|body_0|>
def generate_stream(self, duration, compression):
"""Generates a stream of frames of the given duration Params: - durat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FixedSizeStream:
def __init__(self, resolution, fps):
"""Params: - resolution: resolution of video, (l, w) - fps: frame rate of video"""
self.resolution = resolution
self.fps = fps
self.frame_size_bytes = resolution[0] * resolution[1] * 3
def generate_stream(self, duration... | the_stack_v2_python_sparse | models/streams.py | alexyu0/829_project | train | 0 | |
bf066cbc17a32102c3bb2eea848caf82c68e5a8b | [
"ans = defaultdict(list)\nfor string in strs:\n count = [0] * 26\n for char in string:\n count[ord(char) - ord('a')] += 1\n ans[tuple(count)].append(string)\nreturn ans.values()",
"ans = defaultdict(list)\nfor string in strs:\n ans[tuple(sorted(string))].append(string)\nreturn ans.values()"
] | <|body_start_0|>
ans = defaultdict(list)
for string in strs:
count = [0] * 26
for char in string:
count[ord(char) - ord('a')] += 1
ans[tuple(count)].append(string)
return ans.values()
<|end_body_0|>
<|body_start_1|>
ans = defaultdict(l... | Anagrams | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Anagrams:
def group(self, strs: List[str]) -> List[str]:
"""Approach: Categorize by count Time Complexity: O(NK) Space Complexity: O(NK) :param strs: :return:"""
<|body_0|>
def group_(self, strs: List[str]) -> List[str]:
"""Approach: Categorize by sorted string Time ... | stack_v2_sparse_classes_75kplus_train_073366 | 1,103 | no_license | [
{
"docstring": "Approach: Categorize by count Time Complexity: O(NK) Space Complexity: O(NK) :param strs: :return:",
"name": "group",
"signature": "def group(self, strs: List[str]) -> List[str]"
},
{
"docstring": "Approach: Categorize by sorted string Time Complexity: O(N log K) Space Complexity... | 2 | stack_v2_sparse_classes_30k_train_023508 | Implement the Python class `Anagrams` described below.
Class description:
Implement the Anagrams class.
Method signatures and docstrings:
- def group(self, strs: List[str]) -> List[str]: Approach: Categorize by count Time Complexity: O(NK) Space Complexity: O(NK) :param strs: :return:
- def group_(self, strs: List[st... | Implement the Python class `Anagrams` described below.
Class description:
Implement the Anagrams class.
Method signatures and docstrings:
- def group(self, strs: List[str]) -> List[str]: Approach: Categorize by count Time Complexity: O(NK) Space Complexity: O(NK) :param strs: :return:
- def group_(self, strs: List[st... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Anagrams:
def group(self, strs: List[str]) -> List[str]:
"""Approach: Categorize by count Time Complexity: O(NK) Space Complexity: O(NK) :param strs: :return:"""
<|body_0|>
def group_(self, strs: List[str]) -> List[str]:
"""Approach: Categorize by sorted string Time ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Anagrams:
def group(self, strs: List[str]) -> List[str]:
"""Approach: Categorize by count Time Complexity: O(NK) Space Complexity: O(NK) :param strs: :return:"""
ans = defaultdict(list)
for string in strs:
count = [0] * 26
for char in string:
cou... | the_stack_v2_python_sparse | revisited_2021/math_and_string/group_anagrams.py | Shiv2157k/leet_code | train | 1 | |
9bf8d11218dd53ee021cbbda4b58a6a125e23cdc | [
"if not module.is_HeckeModule(X) or not module.is_HeckeModule(Y):\n raise TypeError('X and Y must be Hecke modules')\nif X.base_ring() != Y.base_ring():\n raise TypeError('X and Y must have the same base ring')\nif category is None:\n category = X.category()\nsage.categories.homset.HomsetWithBase.__init__(... | <|body_start_0|>
if not module.is_HeckeModule(X) or not module.is_HeckeModule(Y):
raise TypeError('X and Y must be Hecke modules')
if X.base_ring() != Y.base_ring():
raise TypeError('X and Y must have the same base ring')
if category is None:
category = X.cate... | A space of homomorphisms between two objects in the category of Hecke modules over a given base ring. | HeckeModuleHomspace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeckeModuleHomspace:
"""A space of homomorphisms between two objects in the category of Hecke modules over a given base ring."""
def __init__(self, X, Y, category=None):
"""Create the space of homomorphisms between X and Y, which must have the same base ring. EXAMPLE:: sage: M = Modu... | stack_v2_sparse_classes_75kplus_train_073367 | 4,617 | no_license | [
{
"docstring": "Create the space of homomorphisms between X and Y, which must have the same base ring. EXAMPLE:: sage: M = ModularForms(Gamma0(7), 4) sage: M.Hom(M) Set of Morphisms from ... to ... in Category of Hecke modules over Rational Field sage: sage.modular.hecke.homspace.HeckeModuleHomspace(M, M.base_e... | 2 | stack_v2_sparse_classes_30k_train_004312 | Implement the Python class `HeckeModuleHomspace` described below.
Class description:
A space of homomorphisms between two objects in the category of Hecke modules over a given base ring.
Method signatures and docstrings:
- def __init__(self, X, Y, category=None): Create the space of homomorphisms between X and Y, whi... | Implement the Python class `HeckeModuleHomspace` described below.
Class description:
A space of homomorphisms between two objects in the category of Hecke modules over a given base ring.
Method signatures and docstrings:
- def __init__(self, X, Y, category=None): Create the space of homomorphisms between X and Y, whi... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class HeckeModuleHomspace:
"""A space of homomorphisms between two objects in the category of Hecke modules over a given base ring."""
def __init__(self, X, Y, category=None):
"""Create the space of homomorphisms between X and Y, which must have the same base ring. EXAMPLE:: sage: M = Modu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HeckeModuleHomspace:
"""A space of homomorphisms between two objects in the category of Hecke modules over a given base ring."""
def __init__(self, X, Y, category=None):
"""Create the space of homomorphisms between X and Y, which must have the same base ring. EXAMPLE:: sage: M = ModularForms(Gamm... | the_stack_v2_python_sparse | sage/src/sage/modular/hecke/homspace.py | bopopescu/geosci | train | 0 |
c56488561c662330cc6bcc3663d039f2d34cb467 | [
"threading.Thread.__init__(self)\nself.parent = parent\nself.idler = MPC_Idler(parent)",
"try:\n self.idler.check_party_mode_init()\nexcept (ConnectionError, CommandError) as e:\n self.parent.print_message('MPD INIT ERROR')\n self.parent.print_message(e)\nexcept psycopg2.OperationalError as e:\n self.... | <|body_start_0|>
threading.Thread.__init__(self)
self.parent = parent
self.idler = MPC_Idler(parent)
<|end_body_0|>
<|body_start_1|>
try:
self.idler.check_party_mode_init()
except (ConnectionError, CommandError) as e:
self.parent.print_message('MPD INIT E... | Threaded mpd communicator service. Idle until something happens and check if random add songs (party mode) | MPDService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPDService:
"""Threaded mpd communicator service. Idle until something happens and check if random add songs (party mode)"""
def __init__(self, parent):
"""Keep reference to PiBlasterWorker to know when to leave."""
<|body_0|>
def run(self):
"""Daemon loop for MP... | stack_v2_sparse_classes_75kplus_train_073368 | 9,139 | no_license | [
{
"docstring": "Keep reference to PiBlasterWorker to know when to leave.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Daemon loop for MPD service. Idle until any MPD event occurs and check if to do anything. NOTE: You should be sure to catch all exceptions o... | 3 | null | Implement the Python class `MPDService` described below.
Class description:
Threaded mpd communicator service. Idle until something happens and check if random add songs (party mode)
Method signatures and docstrings:
- def __init__(self, parent): Keep reference to PiBlasterWorker to know when to leave.
- def run(self... | Implement the Python class `MPDService` described below.
Class description:
Threaded mpd communicator service. Idle until something happens and check if random add songs (party mode)
Method signatures and docstrings:
- def __init__(self, parent): Keep reference to PiBlasterWorker to know when to leave.
- def run(self... | 36d08b9ad6f000cd676caafbf9029c6b2b8cb049 | <|skeleton|>
class MPDService:
"""Threaded mpd communicator service. Idle until something happens and check if random add songs (party mode)"""
def __init__(self, parent):
"""Keep reference to PiBlasterWorker to know when to leave."""
<|body_0|>
def run(self):
"""Daemon loop for MP... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MPDService:
"""Threaded mpd communicator service. Idle until something happens and check if random add songs (party mode)"""
def __init__(self, parent):
"""Keep reference to PiBlasterWorker to know when to leave."""
threading.Thread.__init__(self)
self.parent = parent
self... | the_stack_v2_python_sparse | workers/partymode.py | ujac81/PiBlaster3 | train | 0 |
a48acbc7352754a229a735cdc0859ee820ee5af6 | [
"code = request.GET.get('code')\nweapp = WeApp()\ndata = weapp.get_session_key(code)\nopenid = data.get('openid', None)\nif not openid:\n return Response(data)\nitem = WeixinUnionID.objects.filter(app_key=settings.WEAPP_APPID, openid=openid).first()\nunionid = item.unionid if item else ''\nif unionid:\n custo... | <|body_start_0|>
code = request.GET.get('code')
weapp = WeApp()
data = weapp.get_session_key(code)
openid = data.get('openid', None)
if not openid:
return Response(data)
item = WeixinUnionID.objects.filter(app_key=settings.WEAPP_APPID, openid=openid).first()
... | WeAppViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeAppViewSet:
def login(self, request, *args, **kwargs):
"""GET /rest/v2/weapp/login params: - code return: { 'session': 'xxxxx' } code 换取 session_key"""
<|body_0|>
def post_user_info(self, request, *args, **kwargs):
"""POST /rest/v2/weapp/user_info params: - encrypt... | stack_v2_sparse_classes_75kplus_train_073369 | 4,739 | no_license | [
{
"docstring": "GET /rest/v2/weapp/login params: - code return: { 'session': 'xxxxx' } code 换取 session_key",
"name": "login",
"signature": "def login(self, request, *args, **kwargs)"
},
{
"docstring": "POST /rest/v2/weapp/user_info params: - encryptedData - rawData - iv - token return: { 'code':... | 2 | stack_v2_sparse_classes_30k_train_036749 | Implement the Python class `WeAppViewSet` described below.
Class description:
Implement the WeAppViewSet class.
Method signatures and docstrings:
- def login(self, request, *args, **kwargs): GET /rest/v2/weapp/login params: - code return: { 'session': 'xxxxx' } code 换取 session_key
- def post_user_info(self, request, ... | Implement the Python class `WeAppViewSet` described below.
Class description:
Implement the WeAppViewSet class.
Method signatures and docstrings:
- def login(self, request, *args, **kwargs): GET /rest/v2/weapp/login params: - code return: { 'session': 'xxxxx' } code 换取 session_key
- def post_user_info(self, request, ... | be58dc8f1f0630d3a04e551911f66d9091bedc45 | <|skeleton|>
class WeAppViewSet:
def login(self, request, *args, **kwargs):
"""GET /rest/v2/weapp/login params: - code return: { 'session': 'xxxxx' } code 换取 session_key"""
<|body_0|>
def post_user_info(self, request, *args, **kwargs):
"""POST /rest/v2/weapp/user_info params: - encrypt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeAppViewSet:
def login(self, request, *args, **kwargs):
"""GET /rest/v2/weapp/login params: - code return: { 'session': 'xxxxx' } code 换取 session_key"""
code = request.GET.get('code')
weapp = WeApp()
data = weapp.get_session_key(code)
openid = data.get('openid', None)
... | the_stack_v2_python_sparse | flashsale/restpro/v2/views/weapp.py | nidepuzi/ndpuzsys | train | 1 | |
bd5f9ae26eced8943d606a9056a9f09b2ca355f0 | [
"super().__init__()\nself.cvr_pooling = nn.AdaptiveAvgPool1d(1)\nself.ctr_pooling = nn.AdaptiveAvgPool1d(1)\nself.cvr_deep = DNNLayer(num_fields, 1, layer_sizes, dropout_p, activation)\nself.ctr_deep = DNNLayer(num_fields, 1, layer_sizes, dropout_p, activation)",
"pooled_cvr = self.cvr_pooling(emb_inputs.rename(N... | <|body_start_0|>
super().__init__()
self.cvr_pooling = nn.AdaptiveAvgPool1d(1)
self.ctr_pooling = nn.AdaptiveAvgPool1d(1)
self.cvr_deep = DNNLayer(num_fields, 1, layer_sizes, dropout_p, activation)
self.ctr_deep = DNNLayer(num_fields, 1, layer_sizes, dropout_p, activation)
<|end_... | Model class of Entire Space Multi Task Model (ESMM) Entire Space Multi Task Model is a model applying transfer learning on recommendation system in a straightforward way, which is a pair of pooling and dense networks to calculate prediction of click-through-rate (CTR) and conversion rate (CVR) sharing a set of embeddin... | EntireSpaceMultiTaskModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntireSpaceMultiTaskModel:
"""Model class of Entire Space Multi Task Model (ESMM) Entire Space Multi Task Model is a model applying transfer learning on recommendation system in a straightforward way, which is a pair of pooling and dense networks to calculate prediction of click-through-rate (CTR... | stack_v2_sparse_classes_75kplus_train_073370 | 3,337 | permissive | [
{
"docstring": "Initialize EntireSpaceMultiTaskModel Args: num_fields (int): number of inputs' fields layer_sizes (List[int]): layer sizes of dense network dropout_p (List[float], optional): probability of Dropout in dense network. Defaults to None. activation (torch.nn.Module, optional): activation function of... | 2 | stack_v2_sparse_classes_30k_train_009744 | Implement the Python class `EntireSpaceMultiTaskModel` described below.
Class description:
Model class of Entire Space Multi Task Model (ESMM) Entire Space Multi Task Model is a model applying transfer learning on recommendation system in a straightforward way, which is a pair of pooling and dense networks to calculat... | Implement the Python class `EntireSpaceMultiTaskModel` described below.
Class description:
Model class of Entire Space Multi Task Model (ESMM) Entire Space Multi Task Model is a model applying transfer learning on recommendation system in a straightforward way, which is a pair of pooling and dense networks to calculat... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class EntireSpaceMultiTaskModel:
"""Model class of Entire Space Multi Task Model (ESMM) Entire Space Multi Task Model is a model applying transfer learning on recommendation system in a straightforward way, which is a pair of pooling and dense networks to calculate prediction of click-through-rate (CTR... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntireSpaceMultiTaskModel:
"""Model class of Entire Space Multi Task Model (ESMM) Entire Space Multi Task Model is a model applying transfer learning on recommendation system in a straightforward way, which is a pair of pooling and dense networks to calculate prediction of click-through-rate (CTR) and convers... | the_stack_v2_python_sparse | torecsys/models/ctr/entire_space_multi_task.py | p768lwy3/torecsys | train | 98 |
99c13fed045c7752c3fcade7186736b464552908 | [
"self.owner = owner\nself.cardFinder = IndexInZone(index, HAND)\nCommand.__init__(self, [CurrentPlayer(), NoRequest(), self.cardFinder])",
"coroutine = self.owner.playCardFromHand(self.cardFinder.card)\nresponse = (yield coroutine.next())\nwhile True:\n response = (yield coroutine.send(response))"
] | <|body_start_0|>
self.owner = owner
self.cardFinder = IndexInZone(index, HAND)
Command.__init__(self, [CurrentPlayer(), NoRequest(), self.cardFinder])
<|end_body_0|>
<|body_start_1|>
coroutine = self.owner.playCardFromHand(self.cardFinder.card)
response = (yield coroutine.next()... | Represents a Command to play a card | PlayCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayCard:
"""Represents a Command to play a card"""
def __init__(self, index, owner):
"""Initialize the Play Card Command"""
<|body_0|>
def perform(self):
"""Perform the command"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.owner = owner
... | stack_v2_sparse_classes_75kplus_train_073371 | 859 | no_license | [
{
"docstring": "Initialize the Play Card Command",
"name": "__init__",
"signature": "def __init__(self, index, owner)"
},
{
"docstring": "Perform the command",
"name": "perform",
"signature": "def perform(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006102 | Implement the Python class `PlayCard` described below.
Class description:
Represents a Command to play a card
Method signatures and docstrings:
- def __init__(self, index, owner): Initialize the Play Card Command
- def perform(self): Perform the command | Implement the Python class `PlayCard` described below.
Class description:
Represents a Command to play a card
Method signatures and docstrings:
- def __init__(self, index, owner): Initialize the Play Card Command
- def perform(self): Perform the command
<|skeleton|>
class PlayCard:
"""Represents a Command to pla... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class PlayCard:
"""Represents a Command to play a card"""
def __init__(self, index, owner):
"""Initialize the Play Card Command"""
<|body_0|>
def perform(self):
"""Perform the command"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlayCard:
"""Represents a Command to play a card"""
def __init__(self, index, owner):
"""Initialize the Play Card Command"""
self.owner = owner
self.cardFinder = IndexInZone(index, HAND)
Command.__init__(self, [CurrentPlayer(), NoRequest(), self.cardFinder])
def perfo... | the_stack_v2_python_sparse | src/Game/Commands/play_card.py | dfwarden/DeckBuilding | train | 0 |
98bf84298584055d82ad4afbaceec4eaf8b4050d | [
"super(StackedAttention, self).__init__()\nself.visualize_attention = None\nself.san = nn.ModuleList([Attention(question_image_encoding_size, key_query_size)] * num_att_layers)",
"for att_layer in self.san:\n u, attention_prob = att_layer(encoded_image, encoded_question)\n if AppState().visualize:\n ... | <|body_start_0|>
super(StackedAttention, self).__init__()
self.visualize_attention = None
self.san = nn.ModuleList([Attention(question_image_encoding_size, key_query_size)] * num_att_layers)
<|end_body_0|>
<|body_start_1|>
for att_layer in self.san:
u, attention_prob = att_l... | Implements a stacked attention layers, this attention was designed in this paper: https://arxiv.org/abs/1511.02274. | StackedAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackedAttention:
"""Implements a stacked attention layers, this attention was designed in this paper: https://arxiv.org/abs/1511.02274."""
def __init__(self, question_image_encoding_size, key_query_size, num_att_layers=2):
"""Constructor of the StackedAttention class. :param questio... | stack_v2_sparse_classes_75kplus_train_073372 | 4,654 | permissive | [
{
"docstring": "Constructor of the StackedAttention class. :param question_image_encoding_size: question encoding size. :param key_query_size: key and query size, are the same in this implementation :param num_att_layers: num of stacked attention layers",
"name": "__init__",
"signature": "def __init__(s... | 2 | stack_v2_sparse_classes_30k_train_035532 | Implement the Python class `StackedAttention` described below.
Class description:
Implements a stacked attention layers, this attention was designed in this paper: https://arxiv.org/abs/1511.02274.
Method signatures and docstrings:
- def __init__(self, question_image_encoding_size, key_query_size, num_att_layers=2): ... | Implement the Python class `StackedAttention` described below.
Class description:
Implements a stacked attention layers, this attention was designed in this paper: https://arxiv.org/abs/1511.02274.
Method signatures and docstrings:
- def __init__(self, question_image_encoding_size, key_query_size, num_att_layers=2): ... | c655c88cc6aec4d0724c19ea95209f1c2dd6770d | <|skeleton|>
class StackedAttention:
"""Implements a stacked attention layers, this attention was designed in this paper: https://arxiv.org/abs/1511.02274."""
def __init__(self, question_image_encoding_size, key_query_size, num_att_layers=2):
"""Constructor of the StackedAttention class. :param questio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StackedAttention:
"""Implements a stacked attention layers, this attention was designed in this paper: https://arxiv.org/abs/1511.02274."""
def __init__(self, question_image_encoding_size, key_query_size, num_att_layers=2):
"""Constructor of the StackedAttention class. :param question_image_encod... | the_stack_v2_python_sparse | models/stacked_attention_vqa/stacked_attention.py | aasseman/mi-prometheus | train | 0 |
a158d69fe934d2c8b37d4e42167b50b1e6141ebc | [
"self.words_dict = {}\nfor index, word in enumerate(words):\n if word not in self.words_dict:\n self.words_dict[word] = [index]\n else:\n self.words_dict[word].append(index)",
"word1_index = self.words_dict[word1]\nword2_index = self.words_dict[word2]\nmin_d = float('inf')\ni1, i2 = (0, 0)\nwh... | <|body_start_0|>
self.words_dict = {}
for index, word in enumerate(words):
if word not in self.words_dict:
self.words_dict[word] = [index]
else:
self.words_dict[word].append(index)
<|end_body_0|>
<|body_start_1|>
word1_index = self.words_d... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.words_dict = {}
for inde... | stack_v2_sparse_classes_75kplus_train_073373 | 2,951 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | cefa2f08667de4d2973274de3ff29a31a7d25eda | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.words_dict = {}
for index, word in enumerate(words):
if word not in self.words_dict:
self.words_dict[word] = [index]
else:
self.words_dict[word].append(ind... | the_stack_v2_python_sparse | 244/Solution.py | zhangruochi/leetcode | train | 14 | |
63e6cd5ca7a04228a1430aa16b9982f98bd82e5e | [
"self.__screen = screen\nself.__selectedDisks = selectedDisks\nself.__partitioner = partitioner\ndisks = ','.join([temp.name for temp in self.__selectedDisks])\npvs = self.__partitioner.getDelPvs()\nvgs = self.__partitioner.getDelVgs()\nself.__msg = TextboxReflowed(60, ARE_YOU_SURE_YOU_WANTO_TO.localize() % (disks,... | <|body_start_0|>
self.__screen = screen
self.__selectedDisks = selectedDisks
self.__partitioner = partitioner
disks = ','.join([temp.name for temp in self.__selectedDisks])
pvs = self.__partitioner.getDelPvs()
vgs = self.__partitioner.getDelVgs()
self.__msg = Text... | Confirm the last option | Confirmation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Confirmation:
"""Confirm the last option"""
def __init__(self, screen, selectedDisks, partitioner):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def run(self):
"""Draws the screen @rtype: boolean @returns: sucess stat... | stack_v2_sparse_classes_75kplus_train_073374 | 1,508 | no_license | [
{
"docstring": "Constructor @type screen: SnackScreen @param screen: SnackScreen instance",
"name": "__init__",
"signature": "def __init__(self, screen, selectedDisks, partitioner)"
},
{
"docstring": "Draws the screen @rtype: boolean @returns: sucess status",
"name": "run",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_027710 | Implement the Python class `Confirmation` described below.
Class description:
Confirm the last option
Method signatures and docstrings:
- def __init__(self, screen, selectedDisks, partitioner): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def run(self): Draws the screen @rtype: boolean ... | Implement the Python class `Confirmation` described below.
Class description:
Confirm the last option
Method signatures and docstrings:
- def __init__(self, screen, selectedDisks, partitioner): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def run(self): Draws the screen @rtype: boolean ... | 1c738fd5e6ee3f8fd4f47acf2207038f20868212 | <|skeleton|>
class Confirmation:
"""Confirm the last option"""
def __init__(self, screen, selectedDisks, partitioner):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def run(self):
"""Draws the screen @rtype: boolean @returns: sucess stat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Confirmation:
"""Confirm the last option"""
def __init__(self, screen, selectedDisks, partitioner):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
self.__screen = screen
self.__selectedDisks = selectedDisks
self.__partitioner = partitioner
... | the_stack_v2_python_sparse | zfrobisher-installer/src/viewer/newt/confirmation.py | fedosu85nce/work | train | 2 |
2724fd1e7bc09a955f1e5d13e87b1a834e4566ac | [
"super().__init__()\nself.tade1 = TADELayer(in_channels=in_channels, aux_channels=aux_channels, kernel_size=kernel_size, bias=bias, upsample_factor=1, upsample_mode=upsample_mode)\nself.gated_conv1 = nn.Conv1D(in_channels, in_channels * 2, kernel_size, 1, bias_attr=bias, padding=(kernel_size - 1) // 2)\nself.tade2 ... | <|body_start_0|>
super().__init__()
self.tade1 = TADELayer(in_channels=in_channels, aux_channels=aux_channels, kernel_size=kernel_size, bias=bias, upsample_factor=1, upsample_mode=upsample_mode)
self.gated_conv1 = nn.Conv1D(in_channels, in_channels * 2, kernel_size, 1, bias_attr=bias, padding=(k... | TADEResBlock module. | TADEResBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TADEResBlock:
"""TADEResBlock module."""
def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'):
"""Initialize TADEResBlock module."""
... | stack_v2_sparse_classes_75kplus_train_073375 | 5,634 | permissive | [
{
"docstring": "Initialize TADEResBlock module.",
"name": "__init__",
"signature": "def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax')"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_030115 | Implement the Python class `TADEResBlock` described below.
Class description:
TADEResBlock module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_functio... | Implement the Python class `TADEResBlock` described below.
Class description:
TADEResBlock module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_functio... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class TADEResBlock:
"""TADEResBlock module."""
def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'):
"""Initialize TADEResBlock module."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TADEResBlock:
"""TADEResBlock module."""
def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'):
"""Initialize TADEResBlock module."""
super().... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/tade_res_block.py | anniyanvr/DeepSpeech-1 | train | 0 |
a177d9466cfa39b2734c4e785325b2241d2942a3 | [
"self.cube = set_up_variable_cube(np.full((3, 3), fill_value=280, dtype=np.float32), spatial_grid='equalarea')\nself.ok_mask = set_up_variable_cube(np.ones_like(self.cube.data).astype(np.int8), spatial_grid='equalarea')\nself.bad_mask = set_up_variable_cube(np.ones_like(self.cube.data).astype(np.int32), spatial_gri... | <|body_start_0|>
self.cube = set_up_variable_cube(np.full((3, 3), fill_value=280, dtype=np.float32), spatial_grid='equalarea')
self.ok_mask = set_up_variable_cube(np.ones_like(self.cube.data).astype(np.int8), spatial_grid='equalarea')
self.bad_mask = set_up_variable_cube(np.ones_like(self.cube.d... | Test whether a cube conforms to mandatory dtype and units standards. | Test_enforce_dtypes | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_enforce_dtypes:
"""Test whether a cube conforms to mandatory dtype and units standards."""
def setUp(self):
"""Set up a conformant test cube and two mask cubes to apply to the cube, one good (int8, no numpy float promotion), one bad (int32, numpy promotes output to float64)."""
... | stack_v2_sparse_classes_75kplus_train_073376 | 12,462 | permissive | [
{
"docstring": "Set up a conformant test cube and two mask cubes to apply to the cube, one good (int8, no numpy float promotion), one bad (int32, numpy promotes output to float64).",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test conformant data (no error is thrown and i... | 3 | stack_v2_sparse_classes_30k_train_005577 | Implement the Python class `Test_enforce_dtypes` described below.
Class description:
Test whether a cube conforms to mandatory dtype and units standards.
Method signatures and docstrings:
- def setUp(self): Set up a conformant test cube and two mask cubes to apply to the cube, one good (int8, no numpy float promotion... | Implement the Python class `Test_enforce_dtypes` described below.
Class description:
Test whether a cube conforms to mandatory dtype and units standards.
Method signatures and docstrings:
- def setUp(self): Set up a conformant test cube and two mask cubes to apply to the cube, one good (int8, no numpy float promotion... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_enforce_dtypes:
"""Test whether a cube conforms to mandatory dtype and units standards."""
def setUp(self):
"""Set up a conformant test cube and two mask cubes to apply to the cube, one good (int8, no numpy float promotion), one bad (int32, numpy promotes output to float64)."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_enforce_dtypes:
"""Test whether a cube conforms to mandatory dtype and units standards."""
def setUp(self):
"""Set up a conformant test cube and two mask cubes to apply to the cube, one good (int8, no numpy float promotion), one bad (int32, numpy promotes output to float64)."""
self.... | the_stack_v2_python_sparse | improver_tests/metadata/test_check_datatypes.py | metoppv/improver | train | 101 |
877f5b80287df8a421d8210906712d9475b5f57e | [
"corp_id = 'ww9c9dfb3253386139'\ncorp_secret = 'ow77plErSKg8EbcJ5n6kPcioaqpgZbGeCoT063nn1Ow'\ntoken_url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}'\nr = requests.get(url=token_url)\nself.token = r.json()['access_token']",
"create_url = f'https://qyapi.weixin.qq.com/... | <|body_start_0|>
corp_id = 'ww9c9dfb3253386139'
corp_secret = 'ow77plErSKg8EbcJ5n6kPcioaqpgZbGeCoT063nn1Ow'
token_url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}'
r = requests.get(url=token_url)
self.token = r.json()['access_token']
... | TestDepartment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDepartment:
def setup_class(self):
"""每次执行前,需要先获取token信息"""
<|body_0|>
def test_create_department(self):
"""创建部门 通讯录api默认只有只读权限,需手动设置为可编辑状态 (管理工具->通讯录同步)"""
<|body_1|>
def test_update_department(self):
"""修改部门名称"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus_train_073377 | 3,530 | no_license | [
{
"docstring": "每次执行前,需要先获取token信息",
"name": "setup_class",
"signature": "def setup_class(self)"
},
{
"docstring": "创建部门 通讯录api默认只有只读权限,需手动设置为可编辑状态 (管理工具->通讯录同步)",
"name": "test_create_department",
"signature": "def test_create_department(self)"
},
{
"docstring": "修改部门名称",
"n... | 4 | null | Implement the Python class `TestDepartment` described below.
Class description:
Implement the TestDepartment class.
Method signatures and docstrings:
- def setup_class(self): 每次执行前,需要先获取token信息
- def test_create_department(self): 创建部门 通讯录api默认只有只读权限,需手动设置为可编辑状态 (管理工具->通讯录同步)
- def test_update_department(self): 修改部门名称... | Implement the Python class `TestDepartment` described below.
Class description:
Implement the TestDepartment class.
Method signatures and docstrings:
- def setup_class(self): 每次执行前,需要先获取token信息
- def test_create_department(self): 创建部门 通讯录api默认只有只读权限,需手动设置为可编辑状态 (管理工具->通讯录同步)
- def test_update_department(self): 修改部门名称... | 76ad28f163daf4384218106115e2c1ba250f82b5 | <|skeleton|>
class TestDepartment:
def setup_class(self):
"""每次执行前,需要先获取token信息"""
<|body_0|>
def test_create_department(self):
"""创建部门 通讯录api默认只有只读权限,需手动设置为可编辑状态 (管理工具->通讯录同步)"""
<|body_1|>
def test_update_department(self):
"""修改部门名称"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDepartment:
def setup_class(self):
"""每次执行前,需要先获取token信息"""
corp_id = 'ww9c9dfb3253386139'
corp_secret = 'ow77plErSKg8EbcJ5n6kPcioaqpgZbGeCoT063nn1Ow'
token_url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}'
r = requests.... | the_stack_v2_python_sparse | Hogwarts/test_requests/test_department.py | ouwenjuan1117/owjproject | train | 0 | |
4ffe6b92d6d24f1fecb74a43cdf54a1ba52d04e5 | [
"for item in list_target:\n if func_condition(item):\n yield item",
"for item in list_target:\n if func_condition(item):\n return item",
"number = 0\nfor item in list_target:\n if func_condition(item):\n number += 1\nreturn number",
"for item in list_target:\n if func_conditio... | <|body_start_0|>
for item in list_target:
if func_condition(item):
yield item
<|end_body_0|>
<|body_start_1|>
for item in list_target:
if func_condition(item):
return item
<|end_body_1|>
<|body_start_2|>
number = 0
for item in lis... | 列表助手类 | ListHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
<|body_0|>
def find_single_condition(list_target, func_condition):
"... | stack_v2_sparse_classes_75kplus_train_073378 | 2,479 | no_license | [
{
"docstring": "通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.",
"name": "find_all",
"signature": "def find_all(list_target, func_condition)"
},
{
"docstring": "通用的查找某个条件的单个元素的方法 :param list_target: 需要查找的列表 :param func_co... | 4 | stack_v2_sparse_classes_30k_train_012499 | Implement the Python class `ListHelper` described below.
Class description:
列表助手类
Method signatures and docstrings:
- def find_all(list_target, func_condition): 通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.
- def find_single_condition(list_ta... | Implement the Python class `ListHelper` described below.
Class description:
列表助手类
Method signatures and docstrings:
- def find_all(list_target, func_condition): 通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.
- def find_single_condition(list_ta... | 55e6681da1a9faf9c0ec618ed60f5da9ecc6beb6 | <|skeleton|>
class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
<|body_0|>
def find_single_condition(list_target, func_condition):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
for item in list_target:
if func_condition(item):
yield item
... | the_stack_v2_python_sparse | MyNotes_01/Step01/4-CORE/day04_17/common/list_helper.py | ZimingGuo/MyNotes01 | train | 0 |
cd3573f0dfa867d336d395af0fa81e99a4782534 | [
"res = []\n\ndef helper(root):\n if not root:\n return\n res.append(str(root.val))\n res.append(str(len(root.children)))\n for ch in root.children:\n helper(ch)\nhelper(root)\nreturn ','.join(res)",
"if not data:\n return\ndata = iter(data.split(','))\n\ndef helper():\n tmp = int(n... | <|body_start_0|>
res = []
def helper(root):
if not root:
return
res.append(str(root.val))
res.append(str(len(root.children)))
for ch in root.children:
helper(ch)
helper(root)
return ','.join(res)
<|end_body_... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_073379 | 2,421 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_043420 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 631df2ce6892a6fbb3e435f57e90d85f8200d125 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
def helper(root):
if not root:
return
res.append(str(root.val))
res.append(str(len(root.children)))
... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree.py | c940606/leetcode | train | 3 | |
161dccc492b6da747c3a26392360b25c06096edf | [
"def new_buffer():\n return SegmentationBuffer(capacity, max_seq_len, max_ep_len)\nself.buffers = defaultdict(new_buffer)",
"batch = batch.copy()\nbatch = batch.as_multi_agent()\nfor policy_id, sample_batch in batch.policy_batches.items():\n self.buffers[policy_id].add(sample_batch)",
"samples = {}\nfor p... | <|body_start_0|>
def new_buffer():
return SegmentationBuffer(capacity, max_seq_len, max_ep_len)
self.buffers = defaultdict(new_buffer)
<|end_body_0|>
<|body_start_1|>
batch = batch.copy()
batch = batch.as_multi_agent()
for policy_id, sample_batch in batch.policy_batc... | A minimal replay buffer used by Decision Transformer (DT) to process episodes into max_seq_len length segments and do shuffling. Stores MultiAgentSample. | MultiAgentSegmentationBuffer | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiAgentSegmentationBuffer:
"""A minimal replay buffer used by Decision Transformer (DT) to process episodes into max_seq_len length segments and do shuffling. Stores MultiAgentSample."""
def __init__(self, capacity: int=20, max_seq_len: int=20, max_ep_len: int=1000):
"""Args: capa... | stack_v2_sparse_classes_75kplus_train_073380 | 7,703 | permissive | [
{
"docstring": "Args: capacity: Maximum number of episodes the buffer can store. max_seq_len: Length of segments that are sampled. max_ep_len: Maximum length of episodes added.",
"name": "__init__",
"signature": "def __init__(self, capacity: int=20, max_seq_len: int=20, max_ep_len: int=1000)"
},
{
... | 3 | stack_v2_sparse_classes_30k_val_002109 | Implement the Python class `MultiAgentSegmentationBuffer` described below.
Class description:
A minimal replay buffer used by Decision Transformer (DT) to process episodes into max_seq_len length segments and do shuffling. Stores MultiAgentSample.
Method signatures and docstrings:
- def __init__(self, capacity: int=2... | Implement the Python class `MultiAgentSegmentationBuffer` described below.
Class description:
A minimal replay buffer used by Decision Transformer (DT) to process episodes into max_seq_len length segments and do shuffling. Stores MultiAgentSample.
Method signatures and docstrings:
- def __init__(self, capacity: int=2... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class MultiAgentSegmentationBuffer:
"""A minimal replay buffer used by Decision Transformer (DT) to process episodes into max_seq_len length segments and do shuffling. Stores MultiAgentSample."""
def __init__(self, capacity: int=20, max_seq_len: int=20, max_ep_len: int=1000):
"""Args: capa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiAgentSegmentationBuffer:
"""A minimal replay buffer used by Decision Transformer (DT) to process episodes into max_seq_len length segments and do shuffling. Stores MultiAgentSample."""
def __init__(self, capacity: int=20, max_seq_len: int=20, max_ep_len: int=1000):
"""Args: capacity: Maximum... | the_stack_v2_python_sparse | rllib/algorithms/dt/segmentation_buffer.py | ray-project/ray | train | 29,482 |
31922e16be1fa0d719765fe55480f978f8872630 | [
"vals = []\n\ndef preOrder(node):\n if node:\n vals.append(node.val)\n preOrder(node.left)\n preOrder(node.right)\npreOrder(root)\nreturn ' '.join([str(val) for val in vals])",
"vals = collections.deque((int(val) for val in data.split()))\n\ndef build(minVal, maxVal):\n if vals and minV... | <|body_start_0|>
vals = []
def preOrder(node):
if node:
vals.append(node.val)
preOrder(node.left)
preOrder(node.right)
preOrder(root)
return ' '.join([str(val) for val in vals])
<|end_body_0|>
<|body_start_1|>
vals = c... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_073381 | 1,441 | 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 | null | 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:... | 93c4712779d3631adca1f40004f2ed9ee4fad766 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
vals = []
def preOrder(node):
if node:
vals.append(node.val)
preOrder(node.left)
preOrder(node.right)
preOrde... | the_stack_v2_python_sparse | 3_tree/medium/449. Serialize and Deserialize BST.py | Jerrydepon/LeetCode | train | 0 | |
b9d0b1b21b60eebbe5cacc647a77f6b100476efa | [
"url = self._gen_request_url('/open-apis/drive/explorer/v2/file/{}'.format(folder_token))\nbody = {'title': title, 'type': converter_enum(file_type, ranges=[DriveFileType.doc, DriveFileType.sheet])}\nres = self._post(url, body=body, auth_token=user_access_token)\nreturn make_datatype(DriveCreateFile, res['data'])",... | <|body_start_0|>
url = self._gen_request_url('/open-apis/drive/explorer/v2/file/{}'.format(folder_token))
body = {'title': title, 'type': converter_enum(file_type, ranges=[DriveFileType.doc, DriveFileType.sheet])}
res = self._post(url, body=body, auth_token=user_access_token)
return make... | APIDriveFileMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIDriveFileMixin:
def create_drive_file(self, user_access_token, folder_token, title, file_type):
"""创建云空间文件 :type self: OpenLark :param user_access_token: user_access_token :type user_access_token: str :param folder_token: 文件夹的 token :type folder_token: str :param title: 文档标题 :type tit... | stack_v2_sparse_classes_75kplus_train_073382 | 4,406 | permissive | [
{
"docstring": "创建云空间文件 :type self: OpenLark :param user_access_token: user_access_token :type user_access_token: str :param folder_token: 文件夹的 token :type folder_token: str :param title: 文档标题 :type title: str :param file_type: 文档类型,可选值为 doc 和 sheet :type file_type: DriveFileType :return: 文件夹元信息 :rtype: DriveCr... | 3 | stack_v2_sparse_classes_30k_train_010837 | Implement the Python class `APIDriveFileMixin` described below.
Class description:
Implement the APIDriveFileMixin class.
Method signatures and docstrings:
- def create_drive_file(self, user_access_token, folder_token, title, file_type): 创建云空间文件 :type self: OpenLark :param user_access_token: user_access_token :type u... | Implement the Python class `APIDriveFileMixin` described below.
Class description:
Implement the APIDriveFileMixin class.
Method signatures and docstrings:
- def create_drive_file(self, user_access_token, folder_token, title, file_type): 创建云空间文件 :type self: OpenLark :param user_access_token: user_access_token :type u... | 36a610926553f0fc5325c87d3955fde5f5d417be | <|skeleton|>
class APIDriveFileMixin:
def create_drive_file(self, user_access_token, folder_token, title, file_type):
"""创建云空间文件 :type self: OpenLark :param user_access_token: user_access_token :type user_access_token: str :param folder_token: 文件夹的 token :type folder_token: str :param title: 文档标题 :type tit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIDriveFileMixin:
def create_drive_file(self, user_access_token, folder_token, title, file_type):
"""创建云空间文件 :type self: OpenLark :param user_access_token: user_access_token :type user_access_token: str :param folder_token: 文件夹的 token :type folder_token: str :param title: 文档标题 :type title: str :param... | the_stack_v2_python_sparse | feishu/api_drive_file.py | crisone/feishu-python-sdk | train | 0 | |
1789a05bc8ec67b32174dec1ae7eb7e8d4ee355c | [
"title1 = CategoryFactory(name='title1', slug='title1-slug', is_static_url=True)\ntitle2 = CategoryFactory(name='title2', slug='title2-slug')\ntitle3 = CategoryFactory(name='title3')\ntitle1slug = CategoryFactory(name='title1-slug')\nassert title1.slug == 'title1-slug'\nassert title2.slug == 'title2'\nassert title3... | <|body_start_0|>
title1 = CategoryFactory(name='title1', slug='title1-slug', is_static_url=True)
title2 = CategoryFactory(name='title2', slug='title2-slug')
title3 = CategoryFactory(name='title3')
title1slug = CategoryFactory(name='title1-slug')
assert title1.slug == 'title1-slug... | TestSlugFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSlugFunctions:
def test_category_slug(self):
"""Test Category slug creation"""
<|body_0|>
def test_static_slug(self):
"""Test Static slug creation"""
<|body_1|>
def test_content_slug(self):
"""Test Content slug creation"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_073383 | 7,123 | no_license | [
{
"docstring": "Test Category slug creation",
"name": "test_category_slug",
"signature": "def test_category_slug(self)"
},
{
"docstring": "Test Static slug creation",
"name": "test_static_slug",
"signature": "def test_static_slug(self)"
},
{
"docstring": "Test Content slug creati... | 3 | stack_v2_sparse_classes_30k_train_022463 | Implement the Python class `TestSlugFunctions` described below.
Class description:
Implement the TestSlugFunctions class.
Method signatures and docstrings:
- def test_category_slug(self): Test Category slug creation
- def test_static_slug(self): Test Static slug creation
- def test_content_slug(self): Test Content sl... | Implement the Python class `TestSlugFunctions` described below.
Class description:
Implement the TestSlugFunctions class.
Method signatures and docstrings:
- def test_category_slug(self): Test Category slug creation
- def test_static_slug(self): Test Static slug creation
- def test_content_slug(self): Test Content sl... | 9fe00a6ff548a8330f0b2af29aac7dc0b7a4aba6 | <|skeleton|>
class TestSlugFunctions:
def test_category_slug(self):
"""Test Category slug creation"""
<|body_0|>
def test_static_slug(self):
"""Test Static slug creation"""
<|body_1|>
def test_content_slug(self):
"""Test Content slug creation"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSlugFunctions:
def test_category_slug(self):
"""Test Category slug creation"""
title1 = CategoryFactory(name='title1', slug='title1-slug', is_static_url=True)
title2 = CategoryFactory(name='title2', slug='title2-slug')
title3 = CategoryFactory(name='title3')
title1s... | the_stack_v2_python_sparse | panel/tests.py | tugcanolgun/Blog | train | 0 | |
9b17a340886e5d9b2c7586617e54a61bbf434be3 | [
"request_new = clone_request(request, 'GET')\ndata = QueryDict('', mutable=True)\nparams = dict(request.GET.items())\nif 'u_id' in params:\n data['user_id'] = params['u_id']\nif 'p_id' in params:\n data['booking_ref'] = params.get('p_id')\nif 'pagination' in params:\n data['page_size'] = params['pagination... | <|body_start_0|>
request_new = clone_request(request, 'GET')
data = QueryDict('', mutable=True)
params = dict(request.GET.items())
if 'u_id' in params:
data['user_id'] = params['u_id']
if 'p_id' in params:
data['booking_ref'] = params.get('p_id')
i... | My Bookings Backward compatibility viewset. * Requires token for verification of the user. | MyBookingsBackwardViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyBookingsBackwardViewSet:
"""My Bookings Backward compatibility viewset. * Requires token for verification of the user."""
def clone_search_booking_request(self, request):
"""Clone request searchbookingv4."""
<|body_0|>
def list(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_073384 | 19,225 | no_license | [
{
"docstring": "Clone request searchbookingv4.",
"name": "clone_search_booking_request",
"signature": "def clone_search_booking_request(self, request)"
},
{
"docstring": "Search booking v4. Args: request: version: *args: **kwargs: Returns:",
"name": "list",
"signature": "def list(self, r... | 2 | stack_v2_sparse_classes_30k_train_001238 | Implement the Python class `MyBookingsBackwardViewSet` described below.
Class description:
My Bookings Backward compatibility viewset. * Requires token for verification of the user.
Method signatures and docstrings:
- def clone_search_booking_request(self, request): Clone request searchbookingv4.
- def list(self, req... | Implement the Python class `MyBookingsBackwardViewSet` described below.
Class description:
My Bookings Backward compatibility viewset. * Requires token for verification of the user.
Method signatures and docstrings:
- def clone_search_booking_request(self, request): Clone request searchbookingv4.
- def list(self, req... | 26ca47c726f2c38211247a41d294e38a67cecb7f | <|skeleton|>
class MyBookingsBackwardViewSet:
"""My Bookings Backward compatibility viewset. * Requires token for verification of the user."""
def clone_search_booking_request(self, request):
"""Clone request searchbookingv4."""
<|body_0|>
def list(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyBookingsBackwardViewSet:
"""My Bookings Backward compatibility viewset. * Requires token for verification of the user."""
def clone_search_booking_request(self, request):
"""Clone request searchbookingv4."""
request_new = clone_request(request, 'GET')
data = QueryDict('', mutabl... | the_stack_v2_python_sparse | depot/apps/apis/my_bookings/views.py | rsenwar/depot | train | 0 |
0f1017ccab0212e5f7b1a4264eaed6822e9a7983 | [
"super(DownloadFile, self).__init__()\nself.source = source\nself.bucket_name = bucket_name\nself.file_path = file_path\nif file_path is None:\n self.file_path = os.environ.get('HOME')\nself.file_name = os.path.basename(self.source)",
"if not os.path.exists(self.file_path):\n os.makedirs(self.file_path)\nfu... | <|body_start_0|>
super(DownloadFile, self).__init__()
self.source = source
self.bucket_name = bucket_name
self.file_path = file_path
if file_path is None:
self.file_path = os.environ.get('HOME')
self.file_name = os.path.basename(self.source)
<|end_body_0|>
<|... | The current class provides download files from AWS S3 :param source path to file :param bucket_name name of your bucket in AWS :param aws_access_key_id access id to your AWS account :param aws_secret_access_key secret access key to your AWS account :param file_path full path to directory where you want to save a file | DownloadFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadFile:
"""The current class provides download files from AWS S3 :param source path to file :param bucket_name name of your bucket in AWS :param aws_access_key_id access id to your AWS account :param aws_secret_access_key secret access key to your AWS account :param file_path full path to d... | stack_v2_sparse_classes_75kplus_train_073385 | 1,585 | no_license | [
{
"docstring": "Initialization variables",
"name": "__init__",
"signature": "def __init__(self, source: str, bucket_name: str, file_path=None)"
},
{
"docstring": "Download file and creates folder if folder in directory does not exist",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `DownloadFile` described below.
Class description:
The current class provides download files from AWS S3 :param source path to file :param bucket_name name of your bucket in AWS :param aws_access_key_id access id to your AWS account :param aws_secret_access_key secret access key to your AWS ... | Implement the Python class `DownloadFile` described below.
Class description:
The current class provides download files from AWS S3 :param source path to file :param bucket_name name of your bucket in AWS :param aws_access_key_id access id to your AWS account :param aws_secret_access_key secret access key to your AWS ... | 5eab8d4612834e771547a79566cd9f68c77666e4 | <|skeleton|>
class DownloadFile:
"""The current class provides download files from AWS S3 :param source path to file :param bucket_name name of your bucket in AWS :param aws_access_key_id access id to your AWS account :param aws_secret_access_key secret access key to your AWS account :param file_path full path to d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DownloadFile:
"""The current class provides download files from AWS S3 :param source path to file :param bucket_name name of your bucket in AWS :param aws_access_key_id access id to your AWS account :param aws_secret_access_key secret access key to your AWS account :param file_path full path to directory wher... | the_stack_v2_python_sparse | aws_helper/aws_s3_helper/v1_args/download_file_from_aws.py | Rostyk1404/test_aws | train | 0 |
174bc3527eb0ff61768bba5a3c6ad02612d8d969 | [
"self.multi_bdtmodel_1d = multi_bdtmodel_1d\nself.cut_values = np.array(cut_values)\nassert len(cut_values) == len(self.multi_bdtmodel_1d.bdts)",
"mbdtm = self.multi_bdtmodel_1d\nif scores is None:\n scores = mbdtm.score(thing)\nmany_events = False\nif isinstance(thing, DataSet):\n many_events = True\n c... | <|body_start_0|>
self.multi_bdtmodel_1d = multi_bdtmodel_1d
self.cut_values = np.array(cut_values)
assert len(cut_values) == len(self.multi_bdtmodel_1d.bdts)
<|end_body_0|>
<|body_start_1|>
mbdtm = self.multi_bdtmodel_1d
if scores is None:
scores = mbdtm.score(thing)... | A cut which takes one value per MultiModel1D bin. | MultiModel1DCut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiModel1DCut:
"""A cut which takes one value per MultiModel1D bin."""
def __init__(self, multi_bdtmodel_1d, cut_values):
"""Construct a :class:`MultiModel1DCut`. :type multi_bdtmodel_1d: :class:`MultiModel1D` :param multi_bdtmodel_1d: The MultiModel1D. :type cut_values: array-like... | stack_v2_sparse_classes_75kplus_train_073386 | 40,314 | no_license | [
{
"docstring": "Construct a :class:`MultiModel1DCut`. :type multi_bdtmodel_1d: :class:`MultiModel1D` :param multi_bdtmodel_1d: The MultiModel1D. :type cut_values: array-like :param cut_values: The cut values, where len (cut_values) == len (multi_bdt_model_1d.bdts)",
"name": "__init__",
"signature": "def... | 2 | null | Implement the Python class `MultiModel1DCut` described below.
Class description:
A cut which takes one value per MultiModel1D bin.
Method signatures and docstrings:
- def __init__(self, multi_bdtmodel_1d, cut_values): Construct a :class:`MultiModel1DCut`. :type multi_bdtmodel_1d: :class:`MultiModel1D` :param multi_bd... | Implement the Python class `MultiModel1DCut` described below.
Class description:
A cut which takes one value per MultiModel1D bin.
Method signatures and docstrings:
- def __init__(self, multi_bdtmodel_1d, cut_values): Construct a :class:`MultiModel1DCut`. :type multi_bdtmodel_1d: :class:`MultiModel1D` :param multi_bd... | 91f939afecf4a9297999b022cea807dea407abe9 | <|skeleton|>
class MultiModel1DCut:
"""A cut which takes one value per MultiModel1D bin."""
def __init__(self, multi_bdtmodel_1d, cut_values):
"""Construct a :class:`MultiModel1DCut`. :type multi_bdtmodel_1d: :class:`MultiModel1D` :param multi_bdtmodel_1d: The MultiModel1D. :type cut_values: array-like... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiModel1DCut:
"""A cut which takes one value per MultiModel1D bin."""
def __init__(self, multi_bdtmodel_1d, cut_values):
"""Construct a :class:`MultiModel1DCut`. :type multi_bdtmodel_1d: :class:`MultiModel1D` :param multi_bdtmodel_1d: The MultiModel1D. :type cut_values: array-like :param cut_v... | the_stack_v2_python_sparse | pybdt/python/ml.py | AlexHarn/bfrv1_icetray | train | 0 |
2e586c91da5632e8e2730e9850babc34cd6b3e37 | [
"if min_int is None:\n min_int = 0\nif max_int is None:\n max_int = 9\nif min_int < 0:\n raise ValueError('random_int min_int must >= 0')\nif max_int > 9:\n raise ValueError('random_int max_int must <= 9')\nif min_int >= max_int:\n raise ValueError('random_int max_int must > min_int')\nres = []\nfor ... | <|body_start_0|>
if min_int is None:
min_int = 0
if max_int is None:
max_int = 9
if min_int < 0:
raise ValueError('random_int min_int must >= 0')
if max_int > 9:
raise ValueError('random_int max_int must <= 9')
if min_int >= max_int... | RandomUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomUtils:
def random_int(cls, length, min_int=None, max_int=None):
"""随机 int 值"""
<|body_0|>
def random_str(cls, length, letters=None):
"""随机 str 值"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if min_int is None:
min_int = 0
... | stack_v2_sparse_classes_75kplus_train_073387 | 1,690 | permissive | [
{
"docstring": "随机 int 值",
"name": "random_int",
"signature": "def random_int(cls, length, min_int=None, max_int=None)"
},
{
"docstring": "随机 str 值",
"name": "random_str",
"signature": "def random_str(cls, length, letters=None)"
}
] | 2 | null | Implement the Python class `RandomUtils` described below.
Class description:
Implement the RandomUtils class.
Method signatures and docstrings:
- def random_int(cls, length, min_int=None, max_int=None): 随机 int 值
- def random_str(cls, length, letters=None): 随机 str 值 | Implement the Python class `RandomUtils` described below.
Class description:
Implement the RandomUtils class.
Method signatures and docstrings:
- def random_int(cls, length, min_int=None, max_int=None): 随机 int 值
- def random_str(cls, length, letters=None): 随机 str 值
<|skeleton|>
class RandomUtils:
def random_int... | 96c6cb44e466fe9582dfcec5a3afe86871a19e67 | <|skeleton|>
class RandomUtils:
def random_int(cls, length, min_int=None, max_int=None):
"""随机 int 值"""
<|body_0|>
def random_str(cls, length, letters=None):
"""随机 str 值"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomUtils:
def random_int(cls, length, min_int=None, max_int=None):
"""随机 int 值"""
if min_int is None:
min_int = 0
if max_int is None:
max_int = 9
if min_int < 0:
raise ValueError('random_int min_int must >= 0')
if max_int > 9:
... | the_stack_v2_python_sparse | wpy/randoms.py | wxnacy/wpy | train | 0 | |
d107f9aeed16dac218fef4df123b2d4f55a59050 | [
"auth = get_authorization_header(request).split()\nif not auth or auth[0].lower() != self.keyword.lower().encode():\n return None\nif len(auth) == 1:\n raise exceptions.AuthenticationFailed(_('Invalid token or secret header. No credentials provided.'))\nelif len(auth) > 2:\n raise exceptions.Authentication... | <|body_start_0|>
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != self.keyword.lower().encode():
return None
if len(auth) == 1:
raise exceptions.AuthenticationFailed(_('Invalid token or secret header. No credentials provided.'))
e... | This class is the token model of `Tokens` | TokensModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokensModel:
"""This class is the token model of `Tokens`"""
def authenticate(self, request):
"""Rewrite the authenticate function to allow read by hash key and not by raw key."""
<|body_0|>
def authenticate_credentials(self, key, secret):
"""Override the `authen... | stack_v2_sparse_classes_75kplus_train_073388 | 7,667 | no_license | [
{
"docstring": "Rewrite the authenticate function to allow read by hash key and not by raw key.",
"name": "authenticate",
"signature": "def authenticate(self, request)"
},
{
"docstring": "Override the `authenticate_credentials` to the model search by the `secret` and `mode` as well.",
"name"... | 2 | null | Implement the Python class `TokensModel` described below.
Class description:
This class is the token model of `Tokens`
Method signatures and docstrings:
- def authenticate(self, request): Rewrite the authenticate function to allow read by hash key and not by raw key.
- def authenticate_credentials(self, key, secret):... | Implement the Python class `TokensModel` described below.
Class description:
This class is the token model of `Tokens`
Method signatures and docstrings:
- def authenticate(self, request): Rewrite the authenticate function to allow read by hash key and not by raw key.
- def authenticate_credentials(self, key, secret):... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class TokensModel:
"""This class is the token model of `Tokens`"""
def authenticate(self, request):
"""Rewrite the authenticate function to allow read by hash key and not by raw key."""
<|body_0|>
def authenticate_credentials(self, key, secret):
"""Override the `authen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TokensModel:
"""This class is the token model of `Tokens`"""
def authenticate(self, request):
"""Rewrite the authenticate function to allow read by hash key and not by raw key."""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != self.keyword.lower... | the_stack_v2_python_sparse | models/users.py | ignite7/backproject | train | 0 |
c1cd41f0c9f2b559e3a5b65ee403196ed4936e17 | [
"\"\"\"\n Treat each node as root, calculate their depths, return the minimum roots.\n This method will get TLE\n \"\"\"\ngraph = [[] for _ in range(n)]\nfor a, b in edges:\n graph[a].append(b)\n graph[b].append(a)\n\ndef get_height(root, visited):\n visited.add(root)\n heig... | <|body_start_0|>
"""
Treat each node as root, calculate their depths, return the minimum roots.
This method will get TLE
"""
graph = [[] for _ in range(n)]
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""Brute Force, Time: O(V^2), Space: O(V)"""
<|body_0|>
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""BFS, Time: O(V), Space: O(V)"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_073389 | 3,079 | no_license | [
{
"docstring": "Brute Force, Time: O(V^2), Space: O(V)",
"name": "findMinHeightTrees",
"signature": "def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]"
},
{
"docstring": "BFS, Time: O(V), Space: O(V)",
"name": "findMinHeightTrees",
"signature": "def findMinHeightT... | 2 | stack_v2_sparse_classes_30k_train_049710 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: Brute Force, Time: O(V^2), Space: O(V)
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: Brute Force, Time: O(V^2), Space: O(V)
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""Brute Force, Time: O(V^2), Space: O(V)"""
<|body_0|>
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""BFS, Time: O(V), Space: O(V)"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""Brute Force, Time: O(V^2), Space: O(V)"""
"""
Treat each node as root, calculate their depths, return the minimum roots.
This method will get TLE
"""
... | the_stack_v2_python_sparse | python/310-Minimum Height Trees.py | cwza/leetcode | train | 0 | |
7383f79ccccb08b1981ba4ea56c20fcedfc10f35 | [
"self.id = int(data['id'])\nself.name = data['name']\noption_datas = data.get('options')\nif option_datas is None or not option_datas:\n options = None\nelse:\n options = [ApplicationCommandInteractionOption(option_data) for option_data in option_datas]\nself.options = options",
"result = ['<', self.__class... | <|body_start_0|>
self.id = int(data['id'])
self.name = data['name']
option_datas = data.get('options')
if option_datas is None or not option_datas:
options = None
else:
options = [ApplicationCommandInteractionOption(option_data) for option_data in option_d... | Represents an ``ApplicationCommand`` invoked by a user. Attributes ---------- id : int` The represented application command's identifier number. name : `str` The name of the command. It's length can be in range [1:32]. options : `None` or `list` of ApplicationCommandInteractionOption The parameters and values from the ... | ApplicationCommandInteraction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationCommandInteraction:
"""Represents an ``ApplicationCommand`` invoked by a user. Attributes ---------- id : int` The represented application command's identifier number. name : `str` The name of the command. It's length can be in range [1:32]. options : `None` or `list` of ApplicationCom... | stack_v2_sparse_classes_75kplus_train_073390 | 45,838 | permissive | [
{
"docstring": "Creates a new ``ApplicationCommandInteraction`` from the data received from Discord. Parameters ---------- data : `dict of (`str`, `Any`) items The received application command interaction data.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Retu... | 2 | stack_v2_sparse_classes_30k_train_053120 | Implement the Python class `ApplicationCommandInteraction` described below.
Class description:
Represents an ``ApplicationCommand`` invoked by a user. Attributes ---------- id : int` The represented application command's identifier number. name : `str` The name of the command. It's length can be in range [1:32]. optio... | Implement the Python class `ApplicationCommandInteraction` described below.
Class description:
Represents an ``ApplicationCommand`` invoked by a user. Attributes ---------- id : int` The represented application command's identifier number. name : `str` The name of the command. It's length can be in range [1:32]. optio... | 74058ba2c878087e312120520bf4c56c312fbeca | <|skeleton|>
class ApplicationCommandInteraction:
"""Represents an ``ApplicationCommand`` invoked by a user. Attributes ---------- id : int` The represented application command's identifier number. name : `str` The name of the command. It's length can be in range [1:32]. options : `None` or `list` of ApplicationCom... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApplicationCommandInteraction:
"""Represents an ``ApplicationCommand`` invoked by a user. Attributes ---------- id : int` The represented application command's identifier number. name : `str` The name of the command. It's length can be in range [1:32]. options : `None` or `list` of ApplicationCommandInteracti... | the_stack_v2_python_sparse | hata/discord/interaction.py | 00-00-00-11/hata | train | 0 |
b04126b5be53634a8a34ec381c081c2c19b171f0 | [
"actions = super().get_actions(request)\nactions['delete_selected'] = (delete_selected, 'delete_selected', delete_selected.short_description)\nreturn actions",
"for obj in queryset:\n obj_display = force_text(obj)\n modeladmin.log_deletion(request, obj, obj_display)\nqueryset.delete()"
] | <|body_start_0|>
actions = super().get_actions(request)
actions['delete_selected'] = (delete_selected, 'delete_selected', delete_selected.short_description)
return actions
<|end_body_0|>
<|body_start_1|>
for obj in queryset:
obj_display = force_text(obj)
modeladm... | DeleteSelectedMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteSelectedMixin:
def get_actions(self, request):
"""Customize delete action"""
<|body_0|>
def perform_delete_selected(modeladmin, request, queryset):
"""Perform delete many records"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
actions = super(... | stack_v2_sparse_classes_75kplus_train_073391 | 720 | permissive | [
{
"docstring": "Customize delete action",
"name": "get_actions",
"signature": "def get_actions(self, request)"
},
{
"docstring": "Perform delete many records",
"name": "perform_delete_selected",
"signature": "def perform_delete_selected(modeladmin, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012255 | Implement the Python class `DeleteSelectedMixin` described below.
Class description:
Implement the DeleteSelectedMixin class.
Method signatures and docstrings:
- def get_actions(self, request): Customize delete action
- def perform_delete_selected(modeladmin, request, queryset): Perform delete many records | Implement the Python class `DeleteSelectedMixin` described below.
Class description:
Implement the DeleteSelectedMixin class.
Method signatures and docstrings:
- def get_actions(self, request): Customize delete action
- def perform_delete_selected(modeladmin, request, queryset): Perform delete many records
<|skeleto... | 9375593778f335ed237957ec589aea9d9aca5792 | <|skeleton|>
class DeleteSelectedMixin:
def get_actions(self, request):
"""Customize delete action"""
<|body_0|>
def perform_delete_selected(modeladmin, request, queryset):
"""Perform delete many records"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteSelectedMixin:
def get_actions(self, request):
"""Customize delete action"""
actions = super().get_actions(request)
actions['delete_selected'] = (delete_selected, 'delete_selected', delete_selected.short_description)
return actions
def perform_delete_selected(modelad... | the_stack_v2_python_sparse | src/app/common/admin/mixins.py | z-station/cappa | train | 13 | |
1adc4dfdd99b1437a41ed430e3ac093df267ab44 | [
"if mask is not None:\n mask = np.asarray(mask)\n nvox = mask.astype(np.int32).sum()\nelse:\n nvox = np.product(fmri_image[0].shape[1:])\nself.n = fmri_image.coordmap.shape[0]\nself.avg = np.zeros((self.n,))\nfor i, d in data_generator(fmri_image):\n if mask is not None:\n d = d * mask\n self.... | <|body_start_0|>
if mask is not None:
mask = np.asarray(mask)
nvox = mask.astype(np.int32).sum()
else:
nvox = np.product(fmri_image[0].shape[1:])
self.n = fmri_image.coordmap.shape[0]
self.avg = np.zeros((self.n,))
for i, d in data_generator(fm... | This class constructs a callable object that is sometimes used to normalize fMRI data before applying a GLM. The normalization consists of dividing each point in the time series by the corresponding frame average of the fMRI image. | WholeBrainNormalize | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WholeBrainNormalize:
"""This class constructs a callable object that is sometimes used to normalize fMRI data before applying a GLM. The normalization consists of dividing each point in the time series by the corresponding frame average of the fMRI image."""
def __init__(self, fmri_image, ma... | stack_v2_sparse_classes_75kplus_train_073392 | 1,849 | permissive | [
{
"docstring": ":Parameters: `fmri_image` : A sequence of fMRI Images (can be a 4D Image) `mask` : A mask over which to average each fMRI volume.",
"name": "__init__",
"signature": "def __init__(self, fmri_image, mask=None)"
},
{
"docstring": ":Parameters: `fmri_data` : fMRI data assumed to have... | 2 | stack_v2_sparse_classes_30k_train_004152 | Implement the Python class `WholeBrainNormalize` described below.
Class description:
This class constructs a callable object that is sometimes used to normalize fMRI data before applying a GLM. The normalization consists of dividing each point in the time series by the corresponding frame average of the fMRI image.
M... | Implement the Python class `WholeBrainNormalize` described below.
Class description:
This class constructs a callable object that is sometimes used to normalize fMRI data before applying a GLM. The normalization consists of dividing each point in the time series by the corresponding frame average of the fMRI image.
M... | 559f17150bd9fa8ead4fd088b330d7cf7db7aa79 | <|skeleton|>
class WholeBrainNormalize:
"""This class constructs a callable object that is sometimes used to normalize fMRI data before applying a GLM. The normalization consists of dividing each point in the time series by the corresponding frame average of the fMRI image."""
def __init__(self, fmri_image, ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WholeBrainNormalize:
"""This class constructs a callable object that is sometimes used to normalize fMRI data before applying a GLM. The normalization consists of dividing each point in the time series by the corresponding frame average of the fMRI image."""
def __init__(self, fmri_image, mask=None):
... | the_stack_v2_python_sparse | nipy/modalities/fmri/fmristat/utils.py | fperez/nipy | train | 1 |
dbefbd8dcbae44398a0acb668a1e9bcdf6ae0ae1 | [
"function_name = 'getWikiPages'\nparms = [project_id, space_id]\nif fields:\n function_name += 'WithFields'\n parms += [cls._convert_obj_fields_to_polarion(fields)]\nwikis = []\nfor suds_wiki in getattr(cls.session.tracker_client.service, function_name)(*parms):\n wikis.append(cls(suds_object=suds_wiki))\n... | <|body_start_0|>
function_name = 'getWikiPages'
parms = [project_id, space_id]
if fields:
function_name += 'WithFields'
parms += [cls._convert_obj_fields_to_polarion(fields)]
wikis = []
for suds_wiki in getattr(cls.session.tracker_client.service, function_... | Object to handle the Polarion WSDL tns3:WikiPage class Attributes: attachments (ArrayOfWikiPageAttachment) author (User) created (dateTime) home_page_content (Text) wiki_page_id (string) linked_page_uris (ArrayOfSubterraURI) location (Location) page_location (Location) page_name (string) project (Project) space_id (str... | WikiPage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiPage:
"""Object to handle the Polarion WSDL tns3:WikiPage class Attributes: attachments (ArrayOfWikiPageAttachment) author (User) created (dateTime) home_page_content (Text) wiki_page_id (string) linked_page_uris (ArrayOfSubterraURI) location (Location) page_location (Location) page_name (str... | stack_v2_sparse_classes_75kplus_train_073393 | 6,901 | permissive | [
{
"docstring": "Returns Wiki Pages from given project and space. Args: project_id: project id (not null) space_id: space id (not null) Returns: list of WikiPage objects",
"name": "get_wiki_pages",
"signature": "def get_wiki_pages(cls, project_id, space_id, fields)"
},
{
"docstring": "Searches fo... | 3 | stack_v2_sparse_classes_30k_train_010566 | Implement the Python class `WikiPage` described below.
Class description:
Object to handle the Polarion WSDL tns3:WikiPage class Attributes: attachments (ArrayOfWikiPageAttachment) author (User) created (dateTime) home_page_content (Text) wiki_page_id (string) linked_page_uris (ArrayOfSubterraURI) location (Location) ... | Implement the Python class `WikiPage` described below.
Class description:
Object to handle the Polarion WSDL tns3:WikiPage class Attributes: attachments (ArrayOfWikiPageAttachment) author (User) created (dateTime) home_page_content (Text) wiki_page_id (string) linked_page_uris (ArrayOfSubterraURI) location (Location) ... | 04c9bc2a47b3d99a3113b5104e57e50401189b64 | <|skeleton|>
class WikiPage:
"""Object to handle the Polarion WSDL tns3:WikiPage class Attributes: attachments (ArrayOfWikiPageAttachment) author (User) created (dateTime) home_page_content (Text) wiki_page_id (string) linked_page_uris (ArrayOfSubterraURI) location (Location) page_location (Location) page_name (str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WikiPage:
"""Object to handle the Polarion WSDL tns3:WikiPage class Attributes: attachments (ArrayOfWikiPageAttachment) author (User) created (dateTime) home_page_content (Text) wiki_page_id (string) linked_page_uris (ArrayOfSubterraURI) location (Location) page_location (Location) page_name (string) project ... | the_stack_v2_python_sparse | src/pylero/wiki_page.py | jamepark4/pylero | train | 0 |
2ed00d6321641ba26d98df9508466cd849d80b7f | [
"sysmeta = req.get_container_info(self.app).get('sysmeta', {})\nelem = Element('VersioningConfiguration')\nif sysmeta.get('versions-enabled'):\n SubElement(elem, 'Status').text = 'Enabled' if config_true_value(sysmeta['versions-enabled']) else 'Suspended'\nbody = tostring(elem)\nreturn HTTPOk(body=body, content_... | <|body_start_0|>
sysmeta = req.get_container_info(self.app).get('sysmeta', {})
elem = Element('VersioningConfiguration')
if sysmeta.get('versions-enabled'):
SubElement(elem, 'Status').text = 'Enabled' if config_true_value(sysmeta['versions-enabled']) else 'Suspended'
body = t... | Handles the following APIs: * GET Bucket versioning * PUT Bucket versioning Those APIs are logged as VERSIONING operations in the S3 server log. | VersioningController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersioningController:
"""Handles the following APIs: * GET Bucket versioning * PUT Bucket versioning Those APIs are logged as VERSIONING operations in the S3 server log."""
def GET(self, req):
"""Handles GET Bucket versioning."""
<|body_0|>
def PUT(self, req):
""... | stack_v2_sparse_classes_75kplus_train_073394 | 2,703 | permissive | [
{
"docstring": "Handles GET Bucket versioning.",
"name": "GET",
"signature": "def GET(self, req)"
},
{
"docstring": "Handles PUT Bucket versioning.",
"name": "PUT",
"signature": "def PUT(self, req)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039318 | Implement the Python class `VersioningController` described below.
Class description:
Handles the following APIs: * GET Bucket versioning * PUT Bucket versioning Those APIs are logged as VERSIONING operations in the S3 server log.
Method signatures and docstrings:
- def GET(self, req): Handles GET Bucket versioning.
... | Implement the Python class `VersioningController` described below.
Class description:
Handles the following APIs: * GET Bucket versioning * PUT Bucket versioning Those APIs are logged as VERSIONING operations in the S3 server log.
Method signatures and docstrings:
- def GET(self, req): Handles GET Bucket versioning.
... | f06e5369579599648cc78e4b556887bc6d978c2b | <|skeleton|>
class VersioningController:
"""Handles the following APIs: * GET Bucket versioning * PUT Bucket versioning Those APIs are logged as VERSIONING operations in the S3 server log."""
def GET(self, req):
"""Handles GET Bucket versioning."""
<|body_0|>
def PUT(self, req):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VersioningController:
"""Handles the following APIs: * GET Bucket versioning * PUT Bucket versioning Those APIs are logged as VERSIONING operations in the S3 server log."""
def GET(self, req):
"""Handles GET Bucket versioning."""
sysmeta = req.get_container_info(self.app).get('sysmeta', {... | the_stack_v2_python_sparse | swift/common/middleware/s3api/controllers/versioning.py | openstack/swift | train | 2,370 |
3ccf7c090207f6136384ca024d8af0315c7324fa | [
"self.dt = dt\nself.v_cov = v_cov\nself.dphi_cov = dphi_cov",
"x = st[:, 0] + st[:, 2] * self.dt * np.cos(st[:, 3])\ny = st[:, 1] + st[:, 2] * self.dt * np.sin(st[:, 3])\nv = st[:, 2] + np.random.normal(scale=np.sqrt(self.v_cov), size=st[:, 2].shape)\nphi = st[:, 3] + self.dt * st[:, 4]\ndphi = st[:, 4] + np.rand... | <|body_start_0|>
self.dt = dt
self.v_cov = v_cov
self.dphi_cov = dphi_cov
<|end_body_0|>
<|body_start_1|>
x = st[:, 0] + st[:, 2] * self.dt * np.cos(st[:, 3])
y = st[:, 1] + st[:, 2] * self.dt * np.sin(st[:, 3])
v = st[:, 2] + np.random.normal(scale=np.sqrt(self.v_cov), ... | Represents how the robot's state evolves over time. | motion_model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class motion_model:
"""Represents how the robot's state evolves over time."""
def __init__(self, dt, v_cov, dphi_cov):
"""dt - sampling time v_cov - covariance for velocity dphi_cov - covariance for turningratio"""
<|body_0|>
def propagate(self, st):
"""Propagates the ... | stack_v2_sparse_classes_75kplus_train_073395 | 5,492 | no_license | [
{
"docstring": "dt - sampling time v_cov - covariance for velocity dphi_cov - covariance for turningratio",
"name": "__init__",
"signature": "def __init__(self, dt, v_cov, dphi_cov)"
},
{
"docstring": "Propagates the robot's state for a single step",
"name": "propagate",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_029603 | Implement the Python class `motion_model` described below.
Class description:
Represents how the robot's state evolves over time.
Method signatures and docstrings:
- def __init__(self, dt, v_cov, dphi_cov): dt - sampling time v_cov - covariance for velocity dphi_cov - covariance for turningratio
- def propagate(self,... | Implement the Python class `motion_model` described below.
Class description:
Represents how the robot's state evolves over time.
Method signatures and docstrings:
- def __init__(self, dt, v_cov, dphi_cov): dt - sampling time v_cov - covariance for velocity dphi_cov - covariance for turningratio
- def propagate(self,... | 5824741fd7ada7b1ebbde011b40a08f4deede842 | <|skeleton|>
class motion_model:
"""Represents how the robot's state evolves over time."""
def __init__(self, dt, v_cov, dphi_cov):
"""dt - sampling time v_cov - covariance for velocity dphi_cov - covariance for turningratio"""
<|body_0|>
def propagate(self, st):
"""Propagates the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class motion_model:
"""Represents how the robot's state evolves over time."""
def __init__(self, dt, v_cov, dphi_cov):
"""dt - sampling time v_cov - covariance for velocity dphi_cov - covariance for turningratio"""
self.dt = dt
self.v_cov = v_cov
self.dphi_cov = dphi_cov
de... | the_stack_v2_python_sparse | particle_filter/src/bootstrap_PF.py | JoanaMWarnecke/sftt | train | 0 |
40d4e6de6c4911cb616e3d22be68dec5f5377580 | [
"json_dict = json.loads(request.body.decode())\nsku_id = json_dict.get('sku_id')\ntry:\n SKU.objects.get(id=sku_id)\nexcept SKU.DoesNotExist:\n return http.HttpResponseForbidden('木有这个sku')\nredis_conn = get_redis_connection('history')\npl = redis_conn.pipeline()\nuser_id = request.user.id\npl.lrem('history_%s... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('sku_id')
try:
SKU.objects.get(id=sku_id)
except SKU.DoesNotExist:
return http.HttpResponseForbidden('木有这个sku')
redis_conn = get_redis_connection('history')
pl = ... | (前提必须要用户处于登录状态)用户浏览记录 | UserBrowseHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBrowseHistory:
"""(前提必须要用户处于登录状态)用户浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body_0|>
def get(self, request):
"""查询用户浏览记录"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_dict = json.loads(request.body.decode())
sku_id = ... | stack_v2_sparse_classes_75kplus_train_073396 | 22,596 | permissive | [
{
"docstring": "保存用户浏览记录",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "查询用户浏览记录",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031877 | Implement the Python class `UserBrowseHistory` described below.
Class description:
(前提必须要用户处于登录状态)用户浏览记录
Method signatures and docstrings:
- def post(self, request): 保存用户浏览记录
- def get(self, request): 查询用户浏览记录 | Implement the Python class `UserBrowseHistory` described below.
Class description:
(前提必须要用户处于登录状态)用户浏览记录
Method signatures and docstrings:
- def post(self, request): 保存用户浏览记录
- def get(self, request): 查询用户浏览记录
<|skeleton|>
class UserBrowseHistory:
"""(前提必须要用户处于登录状态)用户浏览记录"""
def post(self, request):
... | 4c00e982dd5caedaf379727e8beb630dfe2cc3de | <|skeleton|>
class UserBrowseHistory:
"""(前提必须要用户处于登录状态)用户浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body_0|>
def get(self, request):
"""查询用户浏览记录"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserBrowseHistory:
"""(前提必须要用户处于登录状态)用户浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('sku_id')
try:
SKU.objects.get(id=sku_id)
except SKU.DoesNotExist:
return http.HttpRe... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | Catherina1/meiduo_web | train | 0 |
7f2871ad81c9da99a9dd494f9d4d693184b1d338 | [
"greater_dict = {}\nstack = []\nresult = []\nfor num in nums2:\n while len(stack) > 0 and stack[-1] < num:\n greater_dict[stack.pop(-1)] = num\n stack.append(num)\nwhile len(stack) > 0:\n greater_dict[stack.pop(-1)] = -1\nfor num in nums1:\n result.append(greater_dict[num])\nreturn result",
"re... | <|body_start_0|>
greater_dict = {}
stack = []
result = []
for num in nums2:
while len(stack) > 0 and stack[-1] < num:
greater_dict[stack.pop(-1)] = num
stack.append(num)
while len(stack) > 0:
greater_dict[stack.pop(-1)] = -1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组"""
<|body_0|>
def next_greater_element_2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: ... | stack_v2_sparse_classes_75kplus_train_073397 | 3,320 | permissive | [
{
"docstring": "获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组",
"name": "next_greater_element",
"signature": "def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]"
},
{
"docstring": "获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 新数组",
"name": "next_greater_ele... | 2 | stack_v2_sparse_classes_30k_test_002355 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]: 获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组
- def next_greater_element_2(self, nums1: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]: 获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组
- def next_greater_element_2(self, nums1: List... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组"""
<|body_0|>
def next_greater_element_2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组"""
greater_dict = {}
stack = []
result = []
for num in nums2:
while len(stack) > 0 and stack[-1] < num:
... | the_stack_v2_python_sparse | src/leetcodepython/array/next_greater_element_496.py | zhangyu345293721/leetcode | train | 101 | |
6c2f8302b3ecea41ee2db945bacfdfb31bdf3573 | [
"if len(self.variant.alleles) > 2:\n raise ValueError('Additive encoding can only be used with one allele')\nallele_sum = self.allele_idxs.sum(axis=1).astype('float')\nallele_sum[(self.allele_idxs == MISSING_IDX).any(axis=1)] = np.nan\nresult = pd.array(data=allele_sum, dtype='UInt8')\nreturn result",
"if len(... | <|body_start_0|>
if len(self.variant.alleles) > 2:
raise ValueError('Additive encoding can only be used with one allele')
allele_sum = self.allele_idxs.sum(axis=1).astype('float')
allele_sum[(self.allele_idxs == MISSING_IDX).any(axis=1)] = np.nan
result = pd.array(data=allele... | Genotype Mixin containing functions for performing encoding | EncodingMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncodingMixin:
"""Genotype Mixin containing functions for performing encoding"""
def encode_additive(self) -> pd.arrays.IntegerArray:
"""Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more t... | stack_v2_sparse_classes_75kplus_train_073398 | 3,710 | permissive | [
{
"docstring": "Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more than 1 alternate allele",
"name": "encode_additive",
"signature": "def encode_additive(self) -> pd.arrays.IntegerArray"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_053218 | Implement the Python class `EncodingMixin` described below.
Class description:
Genotype Mixin containing functions for performing encoding
Method signatures and docstrings:
- def encode_additive(self) -> pd.arrays.IntegerArray: Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any... | Implement the Python class `EncodingMixin` described below.
Class description:
Genotype Mixin containing functions for performing encoding
Method signatures and docstrings:
- def encode_additive(self) -> pd.arrays.IntegerArray: Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any... | a4419a5c491567ddfca7fdb2234a1c0d7e396719 | <|skeleton|>
class EncodingMixin:
"""Genotype Mixin containing functions for performing encoding"""
def encode_additive(self) -> pd.arrays.IntegerArray:
"""Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncodingMixin:
"""Genotype Mixin containing functions for performing encoding"""
def encode_additive(self) -> pd.arrays.IntegerArray:
"""Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more than 1 alterna... | the_stack_v2_python_sparse | pandas_genomics/arrays/encoding_mixin.py | adbmd/pandas-genomics | train | 0 |
4851423a047891dd882583d003047f535464c38b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DocumentSet()",
"from .column_definition import ColumnDefinition\nfrom .content_type_info import ContentTypeInfo\nfrom .document_set_content import DocumentSetContent\nfrom .column_definition import ColumnDefinition\nfrom .content_type... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DocumentSet()
<|end_body_0|>
<|body_start_1|>
from .column_definition import ColumnDefinition
from .content_type_info import ContentTypeInfo
from .document_set_content import Doc... | DocumentSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet:
"""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: Do... | stack_v2_sparse_classes_75kplus_train_073399 | 5,010 | 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: DocumentSet",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | stack_v2_sparse_classes_30k_train_048896 | Implement the Python class `DocumentSet` described below.
Class description:
Implement the DocumentSet class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet: Creates a new instance of the appropriate class based on discriminator value Args:... | Implement the Python class `DocumentSet` described below.
Class description:
Implement the DocumentSet class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet: Creates a new instance of the appropriate class based on discriminator value Args:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DocumentSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet:
"""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: Do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet:
"""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: DocumentSet"""
... | the_stack_v2_python_sparse | msgraph/generated/models/document_set.py | microsoftgraph/msgraph-sdk-python | train | 135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.