blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7524504f1ed4e15c8f99fa651f24a889edfe5917 | [
"if not email:\n raise ValueError('Users must have an email address')\nif not username:\n raise ValueError('Users must have an username')\nuser = self.model(email=self.normalize_email(email), username=username)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(e... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have an username')
user = self.model(email=self.normalize_email(email), username=username)
user.set_password(password)
user.sa... | AccountsManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountsManager:
def create_user(self, email, username, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password=None):
"""Creates and saves a superuser with the g... | stack_v2_sparse_classes_36k_train_020000 | 2,435 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, username, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_006579 | Implement the Python class `AccountsManager` described below.
Class description:
Implement the AccountsManager class.
Method signatures and docstrings:
- def create_user(self, email, username, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email... | Implement the Python class `AccountsManager` described below.
Class description:
Implement the AccountsManager class.
Method signatures and docstrings:
- def create_user(self, email, username, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email... | 23f380994821b762d1e8169360b6998416d40f7f | <|skeleton|>
class AccountsManager:
def create_user(self, email, username, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password=None):
"""Creates and saves a superuser with the g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountsManager:
def create_user(self, email, username, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users m... | the_stack_v2_python_sparse | event_management/accounts/models.py | IIITL-DeV/College-Event-Management-System | train | 1 | |
56067c6f0a794af1aed6cc0a3bef410bf64255fa | [
"path = urlJoin(urls.ROGUE_LOCATION['GET_AP_LOC'], macaddr)\nparams = {'offset': offset, 'limit': limit, 'units': units}\nresp = conn.command(apiMethod='GET', apiPath=path, apiParams=params)\nreturn resp",
"path = urlJoin(urls.ROGUE_LOCATION['GET_FLOOR_APS'], floor_id)\nparams = {'offset': offset, 'limit': limit,... | <|body_start_0|>
path = urlJoin(urls.ROGUE_LOCATION['GET_AP_LOC'], macaddr)
params = {'offset': offset, 'limit': limit, 'units': units}
resp = conn.command(apiMethod='GET', apiPath=path, apiParams=params)
return resp
<|end_body_0|>
<|body_start_1|>
path = urlJoin(urls.ROGUE_LOCA... | A python class to obtain location of rogue access points | RougueLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RougueLocation:
"""A python class to obtain location of rogue access points"""
def get_rogueap_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of rogue a access point based on its Mac Address :param conn: Instance of class:`pycentral.ArubaCentra... | stack_v2_sparse_classes_36k_train_020001 | 13,713 | permissive | [
{
"docstring": "Get location of rogue a access point based on its Mac Address :param conn: Instance of class:`pycentral.ArubaCentralBase` to make an API call. :type conn: class:`pycentral.ArubaCentralBase` :param macaddr: Provide Mac Address of an Access Point :type macaddr: str :param offset: Pagination start ... | 2 | stack_v2_sparse_classes_30k_train_016317 | Implement the Python class `RougueLocation` described below.
Class description:
A python class to obtain location of rogue access points
Method signatures and docstrings:
- def get_rogueap_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'): Get location of rogue a access point based on its Mac Addr... | Implement the Python class `RougueLocation` described below.
Class description:
A python class to obtain location of rogue access points
Method signatures and docstrings:
- def get_rogueap_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'): Get location of rogue a access point based on its Mac Addr... | d938396a18193473afbe54e6cc6697d2bd4954a7 | <|skeleton|>
class RougueLocation:
"""A python class to obtain location of rogue access points"""
def get_rogueap_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of rogue a access point based on its Mac Address :param conn: Instance of class:`pycentral.ArubaCentra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RougueLocation:
"""A python class to obtain location of rogue access points"""
def get_rogueap_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of rogue a access point based on its Mac Address :param conn: Instance of class:`pycentral.ArubaCentralBase` to mak... | the_stack_v2_python_sparse | pycentral/visualrf.py | jayp193/pycentral | train | 0 |
42c9da8c94e84bcf0834fb01bc6a2ed2b4374d24 | [
"arguments = {'target': None, 'spn': None, 'domain': None, 'domain_sid': None, 'aesKey': None, 'nthash': None, 'keytab': None, 'extra_sid': None, 'user': None, 'password': None, 'hashes': None, 'dc_ip': None, 'ts': False, 'debug': False, 'user_id': None, 'duration': '10', 'groups': '513, 512, 520, 518, 519', 'reque... | <|body_start_0|>
arguments = {'target': None, 'spn': None, 'domain': None, 'domain_sid': None, 'aesKey': None, 'nthash': None, 'keytab': None, 'extra_sid': None, 'user': None, 'password': None, 'hashes': None, 'dc_ip': None, 'ts': False, 'debug': False, 'user_id': None, 'duration': '10', 'groups': '513, 512, 52... | Generate a Kerberos ticket using Impacket's ticker.py script that we modified to allow us to create a valid AP_REQ wrapped in SPNEGO. | KRB_TGT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KRB_TGT:
"""Generate a Kerberos ticket using Impacket's ticker.py script that we modified to allow us to create a valid AP_REQ wrapped in SPNEGO."""
def _ticketer_ns(self) -> TicketerNS:
"""This is a helper function to replace the argparse in the example script and generate a custom ... | stack_v2_sparse_classes_36k_train_020002 | 4,029 | permissive | [
{
"docstring": "This is a helper function to replace the argparse in the example script and generate a custom Namespace. References: https://github.com/SecureAuthCorp/impacket/blob/master/examples/ticketer.py#L726",
"name": "_ticketer_ns",
"signature": "def _ticketer_ns(self) -> TicketerNS"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_018178 | Implement the Python class `KRB_TGT` described below.
Class description:
Generate a Kerberos ticket using Impacket's ticker.py script that we modified to allow us to create a valid AP_REQ wrapped in SPNEGO.
Method signatures and docstrings:
- def _ticketer_ns(self) -> TicketerNS: This is a helper function to replace ... | Implement the Python class `KRB_TGT` described below.
Class description:
Generate a Kerberos ticket using Impacket's ticker.py script that we modified to allow us to create a valid AP_REQ wrapped in SPNEGO.
Method signatures and docstrings:
- def _ticketer_ns(self) -> TicketerNS: This is a helper function to replace ... | 9334d0959aef64c06a716a5ed2e4f5582ab44a26 | <|skeleton|>
class KRB_TGT:
"""Generate a Kerberos ticket using Impacket's ticker.py script that we modified to allow us to create a valid AP_REQ wrapped in SPNEGO."""
def _ticketer_ns(self) -> TicketerNS:
"""This is a helper function to replace the argparse in the example script and generate a custom ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KRB_TGT:
"""Generate a Kerberos ticket using Impacket's ticker.py script that we modified to allow us to create a valid AP_REQ wrapped in SPNEGO."""
def _ticketer_ns(self) -> TicketerNS:
"""This is a helper function to replace the argparse in the example script and generate a custom Namespace. Re... | the_stack_v2_python_sparse | ticketsplease/ticketsplease/modules/ticket/krb_tgt.py | bac/whiskeysamlandfriends | train | 0 |
dd4280ea9e25a078d70f8c6d5a4727d068eb7a9e | [
"if root == None:\n return\nprint(root.val, end='->')\nself.preorderTraversalRec(root.left)\nself.preorderTraversalRec(root.right)",
"if root == None:\n return\nself.inorderTraversalRec(root.left)\nprint(root.val, end='->')\nself.inorderTraversalRec(root.right)",
"if root == None:\n return\nself.postor... | <|body_start_0|>
if root == None:
return
print(root.val, end='->')
self.preorderTraversalRec(root.left)
self.preorderTraversalRec(root.right)
<|end_body_0|>
<|body_start_1|>
if root == None:
return
self.inorderTraversalRec(root.left)
print... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversalRec(self, root):
"""前序遍历 根节点-左节点-右节点 :return:"""
<|body_0|>
def inorderTraversalRec(self, root):
"""中序遍历 左节点-根节点-右节点 :return:"""
<|body_1|>
def postorderTraversalRec(self, root):
"""中序遍历 左节点-根节点-右节点 :return:"""
... | stack_v2_sparse_classes_36k_train_020003 | 1,609 | no_license | [
{
"docstring": "前序遍历 根节点-左节点-右节点 :return:",
"name": "preorderTraversalRec",
"signature": "def preorderTraversalRec(self, root)"
},
{
"docstring": "中序遍历 左节点-根节点-右节点 :return:",
"name": "inorderTraversalRec",
"signature": "def inorderTraversalRec(self, root)"
},
{
"docstring": "中序遍历... | 3 | stack_v2_sparse_classes_30k_train_002834 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversalRec(self, root): 前序遍历 根节点-左节点-右节点 :return:
- def inorderTraversalRec(self, root): 中序遍历 左节点-根节点-右节点 :return:
- def postorderTraversalRec(self, root): 中序遍历 左节点... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversalRec(self, root): 前序遍历 根节点-左节点-右节点 :return:
- def inorderTraversalRec(self, root): 中序遍历 左节点-根节点-右节点 :return:
- def postorderTraversalRec(self, root): 中序遍历 左节点... | 90d07a53a537212f41740adb8e65c4e30c3c4f64 | <|skeleton|>
class Solution:
def preorderTraversalRec(self, root):
"""前序遍历 根节点-左节点-右节点 :return:"""
<|body_0|>
def inorderTraversalRec(self, root):
"""中序遍历 左节点-根节点-右节点 :return:"""
<|body_1|>
def postorderTraversalRec(self, root):
"""中序遍历 左节点-根节点-右节点 :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorderTraversalRec(self, root):
"""前序遍历 根节点-左节点-右节点 :return:"""
if root == None:
return
print(root.val, end='->')
self.preorderTraversalRec(root.left)
self.preorderTraversalRec(root.right)
def inorderTraversalRec(self, root):
"""... | the_stack_v2_python_sparse | 排序与搜索和二叉树/遍历二叉树.py | xianytt/LeetCode | train | 0 | |
0d329c74abd1b6cf79b45535999e320f2f8eb5c8 | [
"response = get_and_check_page(self, 'huntserver:create_account', 200)\npost_context = {'user-first_name': 'first', 'user-last_name': 'last', 'user-username': 'user7', 'user-email': 'user7@example.com', 'person-phone': '777-777-7777', 'person-allergies': 'something', 'user-password': 'password', 'user-confirm_passw... | <|body_start_0|>
response = get_and_check_page(self, 'huntserver:create_account', 200)
post_context = {'user-first_name': 'first', 'user-last_name': 'last', 'user-username': 'user7', 'user-email': 'user7@example.com', 'person-phone': '777-777-7777', 'person-allergies': 'something', 'user-password': 'pas... | AuthTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthTests:
def test_create_account(self):
"""Test the account creation view"""
<|body_0|>
def test_login_selection(self):
"""Test the login selection view"""
<|body_1|>
def test_account_logout(self):
"""Test the account logout view"""
<|b... | stack_v2_sparse_classes_36k_train_020004 | 33,380 | permissive | [
{
"docstring": "Test the account creation view",
"name": "test_create_account",
"signature": "def test_create_account(self)"
},
{
"docstring": "Test the login selection view",
"name": "test_login_selection",
"signature": "def test_login_selection(self)"
},
{
"docstring": "Test th... | 4 | stack_v2_sparse_classes_30k_train_006623 | Implement the Python class `AuthTests` described below.
Class description:
Implement the AuthTests class.
Method signatures and docstrings:
- def test_create_account(self): Test the account creation view
- def test_login_selection(self): Test the login selection view
- def test_account_logout(self): Test the account ... | Implement the Python class `AuthTests` described below.
Class description:
Implement the AuthTests class.
Method signatures and docstrings:
- def test_create_account(self): Test the account creation view
- def test_login_selection(self): Test the login selection view
- def test_account_logout(self): Test the account ... | 44f87cc5cfe8bb23a8e04fddee187b9056407741 | <|skeleton|>
class AuthTests:
def test_create_account(self):
"""Test the account creation view"""
<|body_0|>
def test_login_selection(self):
"""Test the login selection view"""
<|body_1|>
def test_account_logout(self):
"""Test the account logout view"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthTests:
def test_create_account(self):
"""Test the account creation view"""
response = get_and_check_page(self, 'huntserver:create_account', 200)
post_context = {'user-first_name': 'first', 'user-last_name': 'last', 'user-username': 'user7', 'user-email': 'user7@example.com', 'perso... | the_stack_v2_python_sparse | huntserver/tests.py | dlareau/puzzlehunt_server | train | 20 | |
ccfe47f41237c88fa97f986eb4f02890b2463c87 | [
"self.dockerfile = dockerfile\nself.context = context\nself.image = image\nself.tag = tag\nself.registry = registry",
"cmds: List[List[str]] = []\ncmds.append(['docker', 'build', '-t', '{}:{}'.format(self.image, self.tag), '-f', self.dockerfile, self.context])\ncmds.append(['docker', 'tag', '{}:{}'.format(self.im... | <|body_start_0|>
self.dockerfile = dockerfile
self.context = context
self.image = image
self.tag = tag
self.registry = registry
<|end_body_0|>
<|body_start_1|>
cmds: List[List[str]] = []
cmds.append(['docker', 'build', '-t', '{}:{}'.format(self.image, self.tag), ... | Build and Publish a Dockerfile | DockerDeployment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DockerDeployment:
"""Build and Publish a Dockerfile"""
def __init__(self, dockerfile: str, context: str, image: str, tag: str, registry: str):
"""Initialize a DockerDeployment object :param dockerfile: path to the Dockerfile :param context: path to docker image context :param image: ... | stack_v2_sparse_classes_36k_train_020005 | 21,614 | permissive | [
{
"docstring": "Initialize a DockerDeployment object :param dockerfile: path to the Dockerfile :param context: path to docker image context :param image: built image name :param tag: built image tag :param registry: registry to publish the image to",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | stack_v2_sparse_classes_30k_train_012940 | Implement the Python class `DockerDeployment` described below.
Class description:
Build and Publish a Dockerfile
Method signatures and docstrings:
- def __init__(self, dockerfile: str, context: str, image: str, tag: str, registry: str): Initialize a DockerDeployment object :param dockerfile: path to the Dockerfile :p... | Implement the Python class `DockerDeployment` described below.
Class description:
Build and Publish a Dockerfile
Method signatures and docstrings:
- def __init__(self, dockerfile: str, context: str, image: str, tag: str, registry: str): Initialize a DockerDeployment object :param dockerfile: path to the Dockerfile :p... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class DockerDeployment:
"""Build and Publish a Dockerfile"""
def __init__(self, dockerfile: str, context: str, image: str, tag: str, registry: str):
"""Initialize a DockerDeployment object :param dockerfile: path to the Dockerfile :param context: path to docker image context :param image: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DockerDeployment:
"""Build and Publish a Dockerfile"""
def __init__(self, dockerfile: str, context: str, image: str, tag: str, registry: str):
"""Initialize a DockerDeployment object :param dockerfile: path to the Dockerfile :param context: path to docker image context :param image: built image n... | the_stack_v2_python_sparse | scripts/acn/k8s_deploy_acn_node.py | fetchai/agents-aea | train | 192 |
c328caa15112491d0a840bb65454bd4812540486 | [
"super(BasePlusNameSubEnt, self).__init__(config, vocab)\nself.name_model = NameModel(config, vocab)\nself.dim = self.name_model.dim + self.dim\nself.init_e_model()",
"fv = []\nfv.extend(self.name_model.emb(entity))\nfv.extend(super().emb(entity))\nreturn fv"
] | <|body_start_0|>
super(BasePlusNameSubEnt, self).__init__(config, vocab)
self.name_model = NameModel(config, vocab)
self.dim = self.name_model.dim + self.dim
self.init_e_model()
<|end_body_0|>
<|body_start_1|>
fv = []
fv.extend(self.name_model.emb(entity))
fv.ext... | BasePlusNameSubEnt | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasePlusNameSubEnt:
def __init__(self, config, vocab):
"""A Sub Entity model."""
<|body_0|>
def emb(self, entity):
"""Get all features of entity."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BasePlusNameSubEnt, self).__init__(config, vocab)... | stack_v2_sparse_classes_36k_train_020006 | 1,518 | permissive | [
{
"docstring": "A Sub Entity model.",
"name": "__init__",
"signature": "def __init__(self, config, vocab)"
},
{
"docstring": "Get all features of entity.",
"name": "emb",
"signature": "def emb(self, entity)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003912 | Implement the Python class `BasePlusNameSubEnt` described below.
Class description:
Implement the BasePlusNameSubEnt class.
Method signatures and docstrings:
- def __init__(self, config, vocab): A Sub Entity model.
- def emb(self, entity): Get all features of entity. | Implement the Python class `BasePlusNameSubEnt` described below.
Class description:
Implement the BasePlusNameSubEnt class.
Method signatures and docstrings:
- def __init__(self, config, vocab): A Sub Entity model.
- def emb(self, entity): Get all features of entity.
<|skeleton|>
class BasePlusNameSubEnt:
def _... | 542659170897ad05f7612639cb918886859ae9d6 | <|skeleton|>
class BasePlusNameSubEnt:
def __init__(self, config, vocab):
"""A Sub Entity model."""
<|body_0|>
def emb(self, entity):
"""Get all features of entity."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasePlusNameSubEnt:
def __init__(self, config, vocab):
"""A Sub Entity model."""
super(BasePlusNameSubEnt, self).__init__(config, vocab)
self.name_model = NameModel(config, vocab)
self.dim = self.name_model.dim + self.dim
self.init_e_model()
def emb(self, entity):
... | the_stack_v2_python_sparse | src/python/coref/models/entity/BasePlusNameSubEnt.py | nmonath/coref_tools | train | 0 | |
139dad7bedc34abbb583980b71c825fa42f91cad | [
"self.sensor = Sensor('http://127.0.0.1', '8000')\nself.pump = Pump('http://127.0.0.1', '8000')\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.PUMP_OUT, 'PUMP_OFF': self.pump.PUMP_OFF}",
"s... | <|body_start_0|>
self.sensor = Sensor('http://127.0.0.1', '8000')
self.pump = Pump('http://127.0.0.1', '8000')
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
self.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.... | Unit tests for the Controller class Write a test or tests for each of the behaviors defined for Controller.tick | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class Write a test or tests for each of the behaviors defined for Controller.tick"""
def setUp(self):
"""Run each time before any test method"""
<|body_0|>
def test_my_controller(self):
"""Test the instance"""
... | stack_v2_sparse_classes_36k_train_020007 | 5,397 | no_license | [
{
"docstring": "Run each time before any test method",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the instance",
"name": "test_my_controller",
"signature": "def test_my_controller(self)"
},
{
"docstring": "True tick state given: sensor.measure, pump.g... | 4 | stack_v2_sparse_classes_30k_train_003555 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class Write a test or tests for each of the behaviors defined for Controller.tick
Method signatures and docstrings:
- def setUp(self): Run each time before any test method
- def test_my_controller(self): Tes... | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class Write a test or tests for each of the behaviors defined for Controller.tick
Method signatures and docstrings:
- def setUp(self): Run each time before any test method
- def test_my_controller(self): Tes... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class Write a test or tests for each of the behaviors defined for Controller.tick"""
def setUp(self):
"""Run each time before any test method"""
<|body_0|>
def test_my_controller(self):
"""Test the instance"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class Write a test or tests for each of the behaviors defined for Controller.tick"""
def setUp(self):
"""Run each time before any test method"""
self.sensor = Sensor('http://127.0.0.1', '8000')
self.pump = Pump('http://127.0.0.1', ... | the_stack_v2_python_sparse | students/ScottL/lesson06/water-regulation-master/waterregulation/test.py | aurel1212/Sp2018-Online | train | 0 |
1912834a6b69a866d5f916ec54c71544a32e616a | [
"user, person = self._create_person('bob', 'bob@example.com', password='secret', first_name=u'Bob', last_name=u'Sponge')\nhtml_text_template = '<p>Profile URL: {{ profile_url }}</p>'\nsubject_template = 'Newsletter no {{ newsletter_issue_no }}'\nn = Newsletter.objects.create(html_text_template=html_text_template, s... | <|body_start_0|>
user, person = self._create_person('bob', 'bob@example.com', password='secret', first_name=u'Bob', last_name=u'Sponge')
html_text_template = '<p>Profile URL: {{ profile_url }}</p>'
subject_template = 'Newsletter no {{ newsletter_issue_no }}'
n = Newsletter.objects.create... | ViewsTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewsTestCase:
def test_view_newsletter_online(self):
"""all newsletters that have been gone out are viewable for the person."""
<|body_0|>
def test_send_unsent(self):
"""going to newsletters/send_unsent/ should send all newsletters"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_020008 | 3,886 | no_license | [
{
"docstring": "all newsletters that have been gone out are viewable for the person.",
"name": "test_view_newsletter_online",
"signature": "def test_view_newsletter_online(self)"
},
{
"docstring": "going to newsletters/send_unsent/ should send all newsletters",
"name": "test_send_unsent",
... | 2 | null | Implement the Python class `ViewsTestCase` described below.
Class description:
Implement the ViewsTestCase class.
Method signatures and docstrings:
- def test_view_newsletter_online(self): all newsletters that have been gone out are viewable for the person.
- def test_send_unsent(self): going to newsletters/send_unse... | Implement the Python class `ViewsTestCase` described below.
Class description:
Implement the ViewsTestCase class.
Method signatures and docstrings:
- def test_view_newsletter_online(self): all newsletters that have been gone out are viewable for the person.
- def test_send_unsent(self): going to newsletters/send_unse... | d7892772d9883bf2cf56542c90f173ac8031f7f0 | <|skeleton|>
class ViewsTestCase:
def test_view_newsletter_online(self):
"""all newsletters that have been gone out are viewable for the person."""
<|body_0|>
def test_send_unsent(self):
"""going to newsletters/send_unsent/ should send all newsletters"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewsTestCase:
def test_view_newsletter_online(self):
"""all newsletters that have been gone out are viewable for the person."""
user, person = self._create_person('bob', 'bob@example.com', password='secret', first_name=u'Bob', last_name=u'Sponge')
html_text_template = '<p>Profile URL:... | the_stack_v2_python_sparse | newsletter/unit_tests/test_views.py | minrivertea/kungfupeople | train | 1 | |
d10cab625a76da941cf8cda0e1fb65505639e4b4 | [
"nvars = 2\nif u0 is None:\n u0 = [2.0, 0.0]\nsuper().__init__((nvars, None, np.dtype('float64')))\nself._makeAttributeAndRegister('nvars', 'u0', localVars=locals(), readOnly=True)\nself._makeAttributeAndRegister('mu', 'newton_maxiter', 'newton_tol', 'stop_at_nan', 'crash_at_maxiter', localVars=locals())\nself.w... | <|body_start_0|>
nvars = 2
if u0 is None:
u0 = [2.0, 0.0]
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', 'u0', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('mu', 'newton_maxiter', 'newton_tol', 'stop_a... | This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math:`\\mu`. newton_maxiter : int, option... | vanderpol | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vanderpol:
"""This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math... | stack_v2_sparse_classes_36k_train_020009 | 5,657 | permissive | [
{
"docstring": "Initialization routine",
"name": "__init__",
"signature": "def __init__(self, u0=None, mu=5.0, newton_maxiter=100, newton_tol=1e-09, stop_at_nan=True, crash_at_maxiter=True)"
},
{
"docstring": "Routine to approximate the exact solution at time t by scipy or give initial condition... | 4 | stack_v2_sparse_classes_30k_train_020381 | Implement the Python class `vanderpol` described below.
Class description:
This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu ... | Implement the Python class `vanderpol` described below.
Class description:
This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu ... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class vanderpol:
"""This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class vanderpol:
"""This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math:`\\mu`. newt... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/Van_der_Pol_implicit.py | Parallel-in-Time/pySDC | train | 30 |
0161caa2ccbce2f7ff10f542760cfea86408ba33 | [
"files: set(str) = {'single video.mp4'}\nexpected_result: set(str) = {'single video.mp4'}\nvideos: set(str) = script.filter_videos(files, debug_function=True)\nself.assertSequenceEqual(videos, expected_result)\n...",
"files: set(str) = {'single video.mp4', '1st non video file.txt', '2nd non video file.txt', '3rd ... | <|body_start_0|>
files: set(str) = {'single video.mp4'}
expected_result: set(str) = {'single video.mp4'}
videos: set(str) = script.filter_videos(files, debug_function=True)
self.assertSequenceEqual(videos, expected_result)
...
<|end_body_0|>
<|body_start_1|>
files: set(s... | test filter_video function | UnitTestFilterVideos | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitTestFilterVideos:
"""test filter_video function"""
def test_1_video_from_1_file(self):
"""test: given one file return one video"""
<|body_0|>
def test_1_video_from_11_files(self):
"""test: given one file return one video"""
<|body_1|>
def test_2_... | stack_v2_sparse_classes_36k_train_020010 | 4,005 | permissive | [
{
"docstring": "test: given one file return one video",
"name": "test_1_video_from_1_file",
"signature": "def test_1_video_from_1_file(self)"
},
{
"docstring": "test: given one file return one video",
"name": "test_1_video_from_11_files",
"signature": "def test_1_video_from_11_files(self... | 5 | stack_v2_sparse_classes_30k_train_009329 | Implement the Python class `UnitTestFilterVideos` described below.
Class description:
test filter_video function
Method signatures and docstrings:
- def test_1_video_from_1_file(self): test: given one file return one video
- def test_1_video_from_11_files(self): test: given one file return one video
- def test_2_vide... | Implement the Python class `UnitTestFilterVideos` described below.
Class description:
test filter_video function
Method signatures and docstrings:
- def test_1_video_from_1_file(self): test: given one file return one video
- def test_1_video_from_11_files(self): test: given one file return one video
- def test_2_vide... | ba0c94e5212f0069b89f75a48fe2e2aafb5c921c | <|skeleton|>
class UnitTestFilterVideos:
"""test filter_video function"""
def test_1_video_from_1_file(self):
"""test: given one file return one video"""
<|body_0|>
def test_1_video_from_11_files(self):
"""test: given one file return one video"""
<|body_1|>
def test_2_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitTestFilterVideos:
"""test filter_video function"""
def test_1_video_from_1_file(self):
"""test: given one file return one video"""
files: set(str) = {'single video.mp4'}
expected_result: set(str) = {'single video.mp4'}
videos: set(str) = script.filter_videos(files, deb... | the_stack_v2_python_sparse | old/dropbox_scripts/helpers/filter_videos/unit_tests_filter_videos.py | jolitp/automation_scripts | train | 0 |
09392c28d9dd74a51ce987e28d059c9b5c222a03 | [
"super(SpatialTransformer, self).__init__()\nsize = volsize\nvectors = [torch.arange(0, s) for s in size]\ngrids = torch.meshgrid(vectors)\ngrid = torch.stack(grids)\ngrid = torch.unsqueeze(grid, 0)\ngrid = grid.type(torch.FloatTensor).cuda()\nself.register_buffer('grid', grid)\nself.mode = mode",
"new_locs = sel... | <|body_start_0|>
super(SpatialTransformer, self).__init__()
size = volsize
vectors = [torch.arange(0, s) for s in size]
grids = torch.meshgrid(vectors)
grid = torch.stack(grids)
grid = torch.unsqueeze(grid, 0)
grid = grid.type(torch.FloatTensor).cuda()
sel... | [SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample | SpatialTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, volsize, mode='bilinear'):
"""Instiatiate the bloc... | stack_v2_sparse_classes_36k_train_020011 | 9,302 | permissive | [
{
"docstring": "Instiatiate the block :param size: size of input to the spatial transformer block :param mode: method of interpolation for grid_sampler",
"name": "__init__",
"signature": "def __init__(self, volsize, mode='bilinear')"
},
{
"docstring": "Push the src and flow through the spatial t... | 2 | null | Implement the Python class `SpatialTransformer` described below.
Class description:
[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample
Method signatures and docstrings:
- def __ini... | Implement the Python class `SpatialTransformer` described below.
Class description:
[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample
Method signatures and docstrings:
- def __ini... | ae368ea39b4049afb4b54cb3447d26107c3a8ab1 | <|skeleton|>
class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, volsize, mode='bilinear'):
"""Instiatiate the bloc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, volsize, mode='bilinear'):
"""Instiatiate the block :param size... | the_stack_v2_python_sparse | UMF-CMGR/models/transform.py | Linfeng-Tang/VIF-Benchmark | train | 29 |
2afcc23bec664d72613660f59d61c5ff863dcd7c | [
"super().__init__(init_weights=init_weights, reg=reg, relu=relu, bias=bias)\nif isinstance(n_layers, int):\n if n_layers not in [16, 19]:\n raise Exception('VGG: Invalid value for n_layers')\n blocks = list(self.groups[n_layers])\nelse:\n blocks = n_layers\ninputs = Input(input_shape)\nx = self.stem... | <|body_start_0|>
super().__init__(init_weights=init_weights, reg=reg, relu=relu, bias=bias)
if isinstance(n_layers, int):
if n_layers not in [16, 19]:
raise Exception('VGG: Invalid value for n_layers')
blocks = list(self.groups[n_layers])
else:
... | VGG (composable) | VGG | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG:
"""VGG (composable)"""
def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True, reg=None, init_weights='glorot_uniform', relu=None, bias=True):
"""Construct a VGG model n_layers : number of layers (16 or 19) or metaparameter for blocks input_shap... | stack_v2_sparse_classes_36k_train_020012 | 5,614 | permissive | [
{
"docstring": "Construct a VGG model n_layers : number of layers (16 or 19) or metaparameter for blocks input_shape : input shape to the model n_classes: : number of output classes include_top : whether to include classifier reg : kernel regularizer init_weights: kernel initializer relu : max value for ReLU bi... | 5 | stack_v2_sparse_classes_30k_train_017572 | Implement the Python class `VGG` described below.
Class description:
VGG (composable)
Method signatures and docstrings:
- def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True, reg=None, init_weights='glorot_uniform', relu=None, bias=True): Construct a VGG model n_layers : number of... | Implement the Python class `VGG` described below.
Class description:
VGG (composable)
Method signatures and docstrings:
- def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True, reg=None, init_weights='glorot_uniform', relu=None, bias=True): Construct a VGG model n_layers : number of... | d157ecdf35f9c13fa8d6135406ec4d27cafd7a4f | <|skeleton|>
class VGG:
"""VGG (composable)"""
def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True, reg=None, init_weights='glorot_uniform', relu=None, bias=True):
"""Construct a VGG model n_layers : number of layers (16 or 19) or metaparameter for blocks input_shap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGG:
"""VGG (composable)"""
def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True, reg=None, init_weights='glorot_uniform', relu=None, bias=True):
"""Construct a VGG model n_layers : number of layers (16 or 19) or metaparameter for blocks input_shape : input sha... | the_stack_v2_python_sparse | zoo/vgg/vgg_c.py | kartikeyaGUPTA45/keras-idiomatic-programmer | train | 3 |
a6fc5b3180eb0cd2ff8eec119e1d1dab309771b1 | [
"if isinstance(priv_key, bytes):\n priv_key = Secp256k1PrivateKey.FromBytes(priv_key)\nelif not isinstance(priv_key, Secp256k1PrivateKey):\n raise TypeError('A secp256k1 private key is required')\npriv_key_bytes = priv_key.Raw().ToBytes()\naddress_hash = _Bip38NoEcUtils.AddressHash(priv_key_bytes, pub_key_mod... | <|body_start_0|>
if isinstance(priv_key, bytes):
priv_key = Secp256k1PrivateKey.FromBytes(priv_key)
elif not isinstance(priv_key, Secp256k1PrivateKey):
raise TypeError('A secp256k1 private key is required')
priv_key_bytes = priv_key.Raw().ToBytes()
address_hash = ... | BIP38 encrypter class. It encrypts a private key using the algorithm specified in BIP38 without EC multiplication. | Bip38NoEcEncrypter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bip38NoEcEncrypter:
"""BIP38 encrypter class. It encrypts a private key using the algorithm specified in BIP38 without EC multiplication."""
def Encrypt(priv_key: Union[bytes, IPrivateKey], passphrase: str, pub_key_mode: Bip38PubKeyModes) -> str:
"""Encrypt the specified private key.... | stack_v2_sparse_classes_36k_train_020013 | 11,103 | permissive | [
{
"docstring": "Encrypt the specified private key. Args: priv_key (bytes or IPrivateKey): Private key bytes or object passphrase (str) : Passphrase pub_key_mode (Bip38PubKeyModes): Public key mode Returns: str: Encrypted private key Raises: TypeError: If the private key is not a Secp256k1PrivateKey ValueError: ... | 2 | null | Implement the Python class `Bip38NoEcEncrypter` described below.
Class description:
BIP38 encrypter class. It encrypts a private key using the algorithm specified in BIP38 without EC multiplication.
Method signatures and docstrings:
- def Encrypt(priv_key: Union[bytes, IPrivateKey], passphrase: str, pub_key_mode: Bip... | Implement the Python class `Bip38NoEcEncrypter` described below.
Class description:
BIP38 encrypter class. It encrypts a private key using the algorithm specified in BIP38 without EC multiplication.
Method signatures and docstrings:
- def Encrypt(priv_key: Union[bytes, IPrivateKey], passphrase: str, pub_key_mode: Bip... | d15c75ddd74e4838c396a0d036ef6faf11b06a4b | <|skeleton|>
class Bip38NoEcEncrypter:
"""BIP38 encrypter class. It encrypts a private key using the algorithm specified in BIP38 without EC multiplication."""
def Encrypt(priv_key: Union[bytes, IPrivateKey], passphrase: str, pub_key_mode: Bip38PubKeyModes) -> str:
"""Encrypt the specified private key.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bip38NoEcEncrypter:
"""BIP38 encrypter class. It encrypts a private key using the algorithm specified in BIP38 without EC multiplication."""
def Encrypt(priv_key: Union[bytes, IPrivateKey], passphrase: str, pub_key_mode: Bip38PubKeyModes) -> str:
"""Encrypt the specified private key. Args: priv_k... | the_stack_v2_python_sparse | bip_utils/bip/bip38/bip38_no_ec.py | ebellocchia/bip_utils | train | 244 |
5ec7fd068f91d7b5dedadbd05abe6421a3970787 | [
"def to_date(s):\n return datetime.strptime(s, '%Y-%m-%d')\nvalidator = Validator({'birthdate': {'required': True, 'type': 'date', 'coerce': to_date}, 'document': {'required': True, 'type': 'string'}, 'name': {'required': True, 'type': 'string'}, 'email': {'required': True, 'type': 'string'}, 'password': {'requi... | <|body_start_0|>
def to_date(s):
return datetime.strptime(s, '%Y-%m-%d')
validator = Validator({'birthdate': {'required': True, 'type': 'date', 'coerce': to_date}, 'document': {'required': True, 'type': 'string'}, 'name': {'required': True, 'type': 'string'}, 'email': {'required': True, 'typ... | Defines the HTTP verbs to user model management. | UserApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserApi:
"""Defines the HTTP verbs to user model management."""
def post(self, request):
"""Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
<|body_0|>
def g... | stack_v2_sparse_classes_36k_train_020014 | 9,574 | permissive | [
{
"docstring": "Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Retrieve user list. Parameters ---------- re... | 2 | stack_v2_sparse_classes_30k_val_000044 | Implement the Python class `UserApi` described below.
Class description:
Defines the HTTP verbs to user model management.
Method signatures and docstrings:
- def post(self, request): Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body r... | Implement the Python class `UserApi` described below.
Class description:
Defines the HTTP verbs to user model management.
Method signatures and docstrings:
- def post(self, request): Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body r... | d56d365dd840ecd272ce933c26f2d408e01c44c7 | <|skeleton|>
class UserApi:
"""Defines the HTTP verbs to user model management."""
def post(self, request):
"""Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
<|body_0|>
def g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserApi:
"""Defines the HTTP verbs to user model management."""
def post(self, request):
"""Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
def to_date(s):
return... | the_stack_v2_python_sparse | api/views/user/general.py | santiagoSSAA/ParkingLot_Back | train | 0 |
c585f74d225e48c19accf2cc063c4b247d19c92a | [
"extern_pars = np.copy(pars)\nextern_pars[6:10] = np.exp(extern_pars[6:10])\nreturn extern_pars",
"intern_pars = np.copy(pars)\nintern_pars[6:10] = np.log(intern_pars[6:10])\nreturn intern_pars",
"if covmatrix is None:\n dx, dy, dz = self._pars[6:9]\n dv = self._pars[9]\n c_xy, c_xz, c_yz = self._pars[... | <|body_start_0|>
extern_pars = np.copy(pars)
extern_pars[6:10] = np.exp(extern_pars[6:10])
return extern_pars
<|end_body_0|>
<|body_start_1|>
intern_pars = np.copy(pars)
intern_pars[6:10] = np.log(intern_pars[6:10])
return intern_pars
<|end_body_1|>
<|body_start_2|>
... | EllipComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EllipComponent:
def externalise(pars):
"""Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes)."""
<|body_0|>
def internalise(pars):
"""Take parameter set in external form (as used to build attributes) and ... | stack_v2_sparse_classes_36k_train_020015 | 24,480 | permissive | [
{
"docstring": "Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes).",
"name": "externalise",
"signature": "def externalise(pars)"
},
{
"docstring": "Take parameter set in external form (as used to build attributes) and convert to int... | 3 | null | Implement the Python class `EllipComponent` described below.
Class description:
Implement the EllipComponent class.
Method signatures and docstrings:
- def externalise(pars): Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes).
- def internalise(pars): Tak... | Implement the Python class `EllipComponent` described below.
Class description:
Implement the EllipComponent class.
Method signatures and docstrings:
- def externalise(pars): Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes).
- def internalise(pars): Tak... | d38aa19edd0229bb0a8b7126f248e61b9a0a8ff3 | <|skeleton|>
class EllipComponent:
def externalise(pars):
"""Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes)."""
<|body_0|>
def internalise(pars):
"""Take parameter set in external form (as used to build attributes) and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EllipComponent:
def externalise(pars):
"""Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes)."""
extern_pars = np.copy(pars)
extern_pars[6:10] = np.exp(extern_pars[6:10])
return extern_pars
def internalise(pars... | the_stack_v2_python_sparse | chronostar/component.py | tcrundall/chronostar | train | 0 | |
dd4907cce92d7e5aa897bda1fe5228bf6177b22c | [
"self.road_data_dict = road_data_dict\nself.reach_road = reach_road\nself.reach_lane = reach_lane",
"if target_road is None:\n return (None, None)\nelif target_road == self.reach_road:\n diff = int(self.reach_lane[2:]) - int(target_lane[2:])\n return (index, diff)\nelif target_road == ego_road:\n retu... | <|body_start_0|>
self.road_data_dict = road_data_dict
self.reach_road = reach_road
self.reach_lane = reach_lane
<|end_body_0|>
<|body_start_1|>
if target_road is None:
return (None, None)
elif target_road == self.reach_road:
diff = int(self.reach_lane[2:]... | Scanner | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scanner:
def __init__(self, road_data_dict, reach_road, reach_lane):
""":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane"""
<|body_0|>
def successor(self, target_road, target_lane, ego_road=None, ego_lane=None, ... | stack_v2_sparse_classes_36k_train_020016 | 3,097 | permissive | [
{
"docstring": ":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane",
"name": "__init__",
"signature": "def __init__(self, road_data_dict, reach_road, reach_lane)"
},
{
"docstring": ":param target_road: :param target_lane: :param ego_r... | 3 | stack_v2_sparse_classes_30k_train_020168 | Implement the Python class `Scanner` described below.
Class description:
Implement the Scanner class.
Method signatures and docstrings:
- def __init__(self, road_data_dict, reach_road, reach_lane): :param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane
- def s... | Implement the Python class `Scanner` described below.
Class description:
Implement the Scanner class.
Method signatures and docstrings:
- def __init__(self, road_data_dict, reach_road, reach_lane): :param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane
- def s... | 588fc9d254b913548159bcd01c5b34bd1c5cbc73 | <|skeleton|>
class Scanner:
def __init__(self, road_data_dict, reach_road, reach_lane):
""":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane"""
<|body_0|>
def successor(self, target_road, target_lane, ego_road=None, ego_lane=None, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scanner:
def __init__(self, road_data_dict, reach_road, reach_lane):
""":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane"""
self.road_data_dict = road_data_dict
self.reach_road = reach_road
self.reach_lane = reach_... | the_stack_v2_python_sparse | Zipc_airflow/src/analyzer/utils/scanner.py | open-garden/garden | train | 16 | |
688e2ba457752838ee6cf63dea15d2040ba6ea1b | [
"super(RandomMazeWalk, self).__init__(speed, maze_layer=maze_layer)\nself._prevent_backtracking = prevent_backtracking\nself._allow_wall_backtracking = allow_wall_backtracking\nself._only_turn_at_wall = only_turn_at_wall",
"if not self._prevent_backtracking:\n return\naxis = np.argmax(np.abs(velocity))\ndirect... | <|body_start_0|>
super(RandomMazeWalk, self).__init__(speed, maze_layer=maze_layer)
self._prevent_backtracking = prevent_backtracking
self._allow_wall_backtracking = allow_wall_backtracking
self._only_turn_at_wall = only_turn_at_wall
<|end_body_0|>
<|body_start_1|>
if not self._... | Random maze walk. | RandomMazeWalk | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomMazeWalk:
"""Random maze walk."""
def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False):
"""Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turn... | stack_v2_sparse_classes_36k_train_020017 | 9,606 | permissive | [
{
"docstring": "Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turns at corners and intersections. Args: speed: Float. Speed for the sprite to move at. maze_layer: String. Layer in the environment state containing the maze sprites. prevent_backtracking... | 3 | stack_v2_sparse_classes_30k_train_010727 | Implement the Python class `RandomMazeWalk` described below.
Class description:
Random maze walk.
Method signatures and docstrings:
- def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False): Constructor. Applying this physics to sprites makes th... | Implement the Python class `RandomMazeWalk` described below.
Class description:
Random maze walk.
Method signatures and docstrings:
- def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False): Constructor. Applying this physics to sprites makes th... | 3e89e46a5918d59475851f9d4f1558956c110d38 | <|skeleton|>
class RandomMazeWalk:
"""Random maze walk."""
def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False):
"""Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomMazeWalk:
"""Random maze walk."""
def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False):
"""Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turns at corners ... | the_stack_v2_python_sparse | moog/physics/maze_walk.py | hokysung/moog.github.io | train | 0 |
580f6996e5d90cbce11380ce7de04ceefbf2d2cd | [
"DATA_PATH = os.path.join(path, f'{project_name}.yaml') if project_name else path\ntry:\n with open(DATA_PATH, encoding='utf-8') as temp:\n datas = yaml.safe_load(temp)\n data = datas.get(module_name, None)\n return data if data else datas\nexcept:\n logger.error(f'此文件{DATA_PATH}不存在')",
"browse... | <|body_start_0|>
DATA_PATH = os.path.join(path, f'{project_name}.yaml') if project_name else path
try:
with open(DATA_PATH, encoding='utf-8') as temp:
datas = yaml.safe_load(temp)
data = datas.get(module_name, None)
return data if data else datas
... | 固定参数 | Constants | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Constants:
"""固定参数"""
def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR):
"""加载配置文件"""
<|body_0|>
def driver(self, broswer, runenv=None):
"""获取浏览器驱动"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
DATA_PATH = os.path.joi... | stack_v2_sparse_classes_36k_train_020018 | 2,257 | no_license | [
{
"docstring": "加载配置文件",
"name": "load_yaml",
"signature": "def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR)"
},
{
"docstring": "获取浏览器驱动",
"name": "driver",
"signature": "def driver(self, broswer, runenv=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021200 | Implement the Python class `Constants` described below.
Class description:
固定参数
Method signatures and docstrings:
- def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR): 加载配置文件
- def driver(self, broswer, runenv=None): 获取浏览器驱动 | Implement the Python class `Constants` described below.
Class description:
固定参数
Method signatures and docstrings:
- def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR): 加载配置文件
- def driver(self, broswer, runenv=None): 获取浏览器驱动
<|skeleton|>
class Constants:
"""固定参数"""
def load_yaml(sel... | 70eaa3872b56374709cda890df0438b8dcd8ee13 | <|skeleton|>
class Constants:
"""固定参数"""
def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR):
"""加载配置文件"""
<|body_0|>
def driver(self, broswer, runenv=None):
"""获取浏览器驱动"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Constants:
"""固定参数"""
def load_yaml(self, project_name=None, module_name=None, path=PAGE_ELE_DIR):
"""加载配置文件"""
DATA_PATH = os.path.join(path, f'{project_name}.yaml') if project_name else path
try:
with open(DATA_PATH, encoding='utf-8') as temp:
datas =... | the_stack_v2_python_sparse | WebFrameWork/BasePage/Constant.py | Mozziy/UIAutoFrameWork | train | 0 |
648a893dcfdbe9916b99b3c2a7de457799884d71 | [
"meta = dict()\nfor k, v in self.__dict__.items():\n if isinstance(v, np.ndarray):\n meta[k] = v.tolist()\n else:\n meta[k] = v\nreturn meta",
"meta = dict()\nfor k, v in doc.items():\n if k == 'classes_':\n self.classes_ = np.array(v)\n continue\n meta[k] = v\nself.__dict_... | <|body_start_0|>
meta = dict()
for k, v in self.__dict__.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
else:
meta[k] = v
return meta
<|end_body_0|>
<|body_start_1|>
meta = dict()
for k, v in doc.items():
... | Label encoder with JSON serialization methods. | XGBoostLabelEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self):
"""Returns a JSON compatible dictionary"""
<|body_0|>
def from_json(self, doc):
"""Load the encoder back from a JSON compatible dict."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_020019 | 5,242 | permissive | [
{
"docstring": "Returns a JSON compatible dictionary",
"name": "to_json",
"signature": "def to_json(self)"
},
{
"docstring": "Load the encoder back from a JSON compatible dict.",
"name": "from_json",
"signature": "def from_json(self, doc)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000608 | Implement the Python class `XGBoostLabelEncoder` described below.
Class description:
Label encoder with JSON serialization methods.
Method signatures and docstrings:
- def to_json(self): Returns a JSON compatible dictionary
- def from_json(self, doc): Load the encoder back from a JSON compatible dict. | Implement the Python class `XGBoostLabelEncoder` described below.
Class description:
Label encoder with JSON serialization methods.
Method signatures and docstrings:
- def to_json(self): Returns a JSON compatible dictionary
- def from_json(self, doc): Load the encoder back from a JSON compatible dict.
<|skeleton|>
c... | a79c7e4a1e411b6a6221d193007a2328312714c3 | <|skeleton|>
class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self):
"""Returns a JSON compatible dictionary"""
<|body_0|>
def from_json(self, doc):
"""Load the encoder back from a JSON compatible dict."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self):
"""Returns a JSON compatible dictionary"""
meta = dict()
for k, v in self.__dict__.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
else:... | the_stack_v2_python_sparse | python-package/xgboost/compat.py | NVIDIA/spark-xgboost | train | 22 |
4fc044687cde6bbf1a97d66c25c5e1ae4cca31ce | [
"res = ListNode(0)\npointer = res\nlists = [v for v in lists if v]\nwhile lists:\n lists = sorted(lists, key=lambda x: x.val, reverse=True)\n pointer.next = lists.pop()\n pointer = pointer.next\n if pointer.next:\n lists.append(pointer.next)\nreturn res.next",
"from heapq import heappush, heapp... | <|body_start_0|>
res = ListNode(0)
pointer = res
lists = [v for v in lists if v]
while lists:
lists = sorted(lists, key=lambda x: x.val, reverse=True)
pointer.next = lists.pop()
pointer = pointer.next
if pointer.next:
lists.... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists2(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = ListNode(0)
... | stack_v2_sparse_classes_36k_train_020020 | 1,573 | permissive | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists2",
"signature": "def mergeKLists2(self, lists)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002179 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists2(self, lists): :type lists: List[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists2(self, lists): :type lists: List[ListNode] :rtype: ListNode
<|skeleton|>
class Solut... | aec1ddd0c51b619c1bae1e05f940d9ed587aa82f | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists2(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
res = ListNode(0)
pointer = res
lists = [v for v in lists if v]
while lists:
lists = sorted(lists, key=lambda x: x.val, reverse=True)
pointer.next = lists.... | the_stack_v2_python_sparse | Python/leetcode/MergeKSortedLists.py | darrencheng0817/AlgorithmLearning | train | 2 | |
b347078daf97a2fb92761ee070c401fcaf71f8de | [
"dh_params = DH.PARAM_NUMBERS.parameters(default_backend())\nx = dh_params.generate_private_key()\nx_bytes = x.private_numbers().x.to_bytes(128, 'big')\ngx = x.public_key()\ngx_bytes = gx.public_numbers().y.to_bytes(128, 'big')\nreturn (x, x_bytes, gx, gx_bytes)",
"gy = DH.dh_public_from_bytes(gy)\nshared_key_mat... | <|body_start_0|>
dh_params = DH.PARAM_NUMBERS.parameters(default_backend())
x = dh_params.generate_private_key()
x_bytes = x.private_numbers().x.to_bytes(128, 'big')
gx = x.public_key()
gx_bytes = gx.public_numbers().y.to_bytes(128, 'big')
return (x, x_bytes, gx, gx_bytes... | DH | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DH:
def generate_keys():
"""Generates the 128 bit diffe hellman private (x) and public (g^x) keys. :return: x value, x as bytes, gx value, and gx as bytes"""
<|body_0|>
def derrive_shared_key(x: dh.DHPrivateKey, gy: bytes, hash: bytes):
"""Derrive the shared key from... | stack_v2_sparse_classes_36k_train_020021 | 11,662 | no_license | [
{
"docstring": "Generates the 128 bit diffe hellman private (x) and public (g^x) keys. :return: x value, x as bytes, gx value, and gx as bytes",
"name": "generate_keys",
"signature": "def generate_keys()"
},
{
"docstring": "Derrive the shared key from gy with x, as done in Diffie Hellman :param ... | 4 | stack_v2_sparse_classes_30k_train_016008 | Implement the Python class `DH` described below.
Class description:
Implement the DH class.
Method signatures and docstrings:
- def generate_keys(): Generates the 128 bit diffe hellman private (x) and public (g^x) keys. :return: x value, x as bytes, gx value, and gx as bytes
- def derrive_shared_key(x: dh.DHPrivateKe... | Implement the Python class `DH` described below.
Class description:
Implement the DH class.
Method signatures and docstrings:
- def generate_keys(): Generates the 128 bit diffe hellman private (x) and public (g^x) keys. :return: x value, x as bytes, gx value, and gx as bytes
- def derrive_shared_key(x: dh.DHPrivateKe... | cf0daa63ead5a9282e36cf28133c93a9f67068c1 | <|skeleton|>
class DH:
def generate_keys():
"""Generates the 128 bit diffe hellman private (x) and public (g^x) keys. :return: x value, x as bytes, gx value, and gx as bytes"""
<|body_0|>
def derrive_shared_key(x: dh.DHPrivateKey, gy: bytes, hash: bytes):
"""Derrive the shared key from... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DH:
def generate_keys():
"""Generates the 128 bit diffe hellman private (x) and public (g^x) keys. :return: x value, x as bytes, gx value, and gx as bytes"""
dh_params = DH.PARAM_NUMBERS.parameters(default_backend())
x = dh_params.generate_private_key()
x_bytes = x.private_numb... | the_stack_v2_python_sparse | crypto/core_crypto.py | Eli-G3/PyTORoxy | train | 1 | |
7272125f3247ef7e8766be1f15e357484b5f1aae | [
"try:\n user = self.Meta.model.objects.get(username=value)\n raise serializers.ValidationError('username is already taken. Please enter a different username')\nexcept ObjectDoesNotExist:\n return value",
"try:\n user = self.Meta.model.objects.get(email=value)\n raise serializers.ValidationError('em... | <|body_start_0|>
try:
user = self.Meta.model.objects.get(username=value)
raise serializers.ValidationError('username is already taken. Please enter a different username')
except ObjectDoesNotExist:
return value
<|end_body_0|>
<|body_start_1|>
try:
... | Currently unused in preference of the below. | CustomUserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserSerializer:
"""Currently unused in preference of the below."""
def validate_username(self, value):
"""Check that the username is not already taken by searching for it in the database via model.objects.get(). If a user with that username is found then raise a validation erro... | stack_v2_sparse_classes_36k_train_020022 | 3,474 | no_license | [
{
"docstring": "Check that the username is not already taken by searching for it in the database via model.objects.get(). If a user with that username is found then raise a validation error.",
"name": "validate_username",
"signature": "def validate_username(self, value)"
},
{
"docstring": "First... | 3 | stack_v2_sparse_classes_30k_train_005207 | Implement the Python class `CustomUserSerializer` described below.
Class description:
Currently unused in preference of the below.
Method signatures and docstrings:
- def validate_username(self, value): Check that the username is not already taken by searching for it in the database via model.objects.get(). If a user... | Implement the Python class `CustomUserSerializer` described below.
Class description:
Currently unused in preference of the below.
Method signatures and docstrings:
- def validate_username(self, value): Check that the username is not already taken by searching for it in the database via model.objects.get(). If a user... | 6735a55f412a7409942a699e16a851f1b7fe2dcd | <|skeleton|>
class CustomUserSerializer:
"""Currently unused in preference of the below."""
def validate_username(self, value):
"""Check that the username is not already taken by searching for it in the database via model.objects.get(). If a user with that username is found then raise a validation erro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserSerializer:
"""Currently unused in preference of the below."""
def validate_username(self, value):
"""Check that the username is not already taken by searching for it in the database via model.objects.get(). If a user with that username is found then raise a validation error."""
... | the_stack_v2_python_sparse | rfa/core/serializers.py | sarwar1995/clone-rfa | train | 0 |
fc7fb2bb1932094a1e50126c68fab3839f8c2f71 | [
"self.dbDir = dbDir\nself.dbName = dbName\nself.dbExtens = dbExtens\nself.nodither = nodither\nself.fieldType = fieldType\nself.RAmin = RAmin\nself.RAmax = RAmax\nself.Decmin = Decmin\nself.Decmax = Decmax\nself.nside = nside\nself.nprocs = nprocs\nself.saveData = saveData\nself.genDir(outDir)\nobservations, patche... | <|body_start_0|>
self.dbDir = dbDir
self.dbName = dbName
self.dbExtens = dbExtens
self.nodither = nodither
self.fieldType = fieldType
self.RAmin = RAmin
self.RAmax = RAmax
self.Decmin = Decmin
self.Decmax = Decmax
self.nside = nside
... | procObsPixels | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class procObsPixels:
def __init__(self, outDir, dbDir, dbName, dbExtens, nodither, fieldType, RAmin, RAmax, Decmin, Decmax, nside, nprocs, saveData=False):
"""Class to process obs <-> pixels on a patch of the sky Parameters -------------- outDir: str output dir name dbDir: str dir where the ob... | stack_v2_sparse_classes_36k_train_020023 | 11,138 | permissive | [
{
"docstring": "Class to process obs <-> pixels on a patch of the sky Parameters -------------- outDir: str output dir name dbDir: str dir where the observing strategy db are located dbName: str name of the observing strategy dbExtens: str extension (db or npy) of the observing strategy file nodither: bool to r... | 5 | stack_v2_sparse_classes_30k_train_003777 | Implement the Python class `procObsPixels` described below.
Class description:
Implement the procObsPixels class.
Method signatures and docstrings:
- def __init__(self, outDir, dbDir, dbName, dbExtens, nodither, fieldType, RAmin, RAmax, Decmin, Decmax, nside, nprocs, saveData=False): Class to process obs <-> pixels o... | Implement the Python class `procObsPixels` described below.
Class description:
Implement the procObsPixels class.
Method signatures and docstrings:
- def __init__(self, outDir, dbDir, dbName, dbExtens, nodither, fieldType, RAmin, RAmax, Decmin, Decmax, nside, nprocs, saveData=False): Class to process obs <-> pixels o... | d42c7490ba5ff8c52f62e70a20c922172a6baff1 | <|skeleton|>
class procObsPixels:
def __init__(self, outDir, dbDir, dbName, dbExtens, nodither, fieldType, RAmin, RAmax, Decmin, Decmax, nside, nprocs, saveData=False):
"""Class to process obs <-> pixels on a patch of the sky Parameters -------------- outDir: str output dir name dbDir: str dir where the ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class procObsPixels:
def __init__(self, outDir, dbDir, dbName, dbExtens, nodither, fieldType, RAmin, RAmax, Decmin, Decmax, nside, nprocs, saveData=False):
"""Class to process obs <-> pixels on a patch of the sky Parameters -------------- outDir: str output dir name dbDir: str dir where the observing strate... | the_stack_v2_python_sparse | run_scripts/obs_pixelize/run_obs_to_pixels.py | LSSTDESC/sn_pipe | train | 1 | |
438ae01caa5b2eaa5f187c9d0f92d3b1f4a641c4 | [
"print('Creating a folder here: {}'.format(self.error_log_directory))\nif not os.path.exists(self.error_folder_name):\n os.makedirs(self.error_folder_name)\n print('ERROR LOG CREATED')\nelse:\n print('ERROR LOG ALREADY EXISTS')\ntry:\n f = open(self.log_file_path)\n print('File exists')\n f.close(... | <|body_start_0|>
print('Creating a folder here: {}'.format(self.error_log_directory))
if not os.path.exists(self.error_folder_name):
os.makedirs(self.error_folder_name)
print('ERROR LOG CREATED')
else:
print('ERROR LOG ALREADY EXISTS')
try:
... | The purpose of this class is to make a folder to store error messages in. Attributes: error_log_directory (String) Address of the log directory. error_folder_name (String) Name of the error logs folder. now (DateTime) Current DateTime object. date (String) Just the date of the current DateTime object error_file_name (S... | ErrorLogger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorLogger:
"""The purpose of this class is to make a folder to store error messages in. Attributes: error_log_directory (String) Address of the log directory. error_folder_name (String) Name of the error logs folder. now (DateTime) Current DateTime object. date (String) Just the date of the cur... | stack_v2_sparse_classes_36k_train_020024 | 2,279 | no_license | [
{
"docstring": "Creates a folder for error logs if not already created.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Logs an error message to the error file. Parameters: error (String) Description of what error happened.",
"name": "log_error",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_003748 | Implement the Python class `ErrorLogger` described below.
Class description:
The purpose of this class is to make a folder to store error messages in. Attributes: error_log_directory (String) Address of the log directory. error_folder_name (String) Name of the error logs folder. now (DateTime) Current DateTime object.... | Implement the Python class `ErrorLogger` described below.
Class description:
The purpose of this class is to make a folder to store error messages in. Attributes: error_log_directory (String) Address of the log directory. error_folder_name (String) Name of the error logs folder. now (DateTime) Current DateTime object.... | d184e7cc2f4cc6f339186a85057922706fc69a8a | <|skeleton|>
class ErrorLogger:
"""The purpose of this class is to make a folder to store error messages in. Attributes: error_log_directory (String) Address of the log directory. error_folder_name (String) Name of the error logs folder. now (DateTime) Current DateTime object. date (String) Just the date of the cur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ErrorLogger:
"""The purpose of this class is to make a folder to store error messages in. Attributes: error_log_directory (String) Address of the log directory. error_folder_name (String) Name of the error logs folder. now (DateTime) Current DateTime object. date (String) Just the date of the current DateTime... | the_stack_v2_python_sparse | src/error_reporting/error_logger.py | gowhale/braille-pi | train | 0 |
22ffbcdb55d5b85444db52b13d0829318ecd3f46 | [
"if self.visited[i][j] == 0:\n self.visited[i][j] = 1\n self.res.append(matrix[i][j])\nretry = 0\nwhile retry < 4:\n if last % 4 == 0:\n if j + 1 <= self.n - 1 and self.visited[i][j + 1] == 0:\n self.bfs(matrix, i, j + 1, last)\n elif last % 4 == 1:\n if i + 1 <= self.m - 1 and ... | <|body_start_0|>
if self.visited[i][j] == 0:
self.visited[i][j] = 1
self.res.append(matrix[i][j])
retry = 0
while retry < 4:
if last % 4 == 0:
if j + 1 <= self.n - 1 and self.visited[i][j + 1] == 0:
self.bfs(matrix, i, j + 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bfs(self, matrix, i, j, last=0):
""":type matrix: List[List[int]] :type i: int current row index :type j: int current column index :rtype: void"""
<|body_0|>
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|... | stack_v2_sparse_classes_36k_train_020025 | 1,595 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type i: int current row index :type j: int current column index :rtype: void",
"name": "bfs",
"signature": "def bfs(self, matrix, i, j, last=0)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "spiralOrder",
"sig... | 2 | stack_v2_sparse_classes_30k_train_002310 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bfs(self, matrix, i, j, last=0): :type matrix: List[List[int]] :type i: int current row index :type j: int current column index :rtype: void
- def spiralOrder(self, matrix): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bfs(self, matrix, i, j, last=0): :type matrix: List[List[int]] :type i: int current row index :type j: int current column index :rtype: void
- def spiralOrder(self, matrix): ... | 1dd5192e8beae28d7c08346133e3f47797c42b5a | <|skeleton|>
class Solution:
def bfs(self, matrix, i, j, last=0):
""":type matrix: List[List[int]] :type i: int current row index :type j: int current column index :rtype: void"""
<|body_0|>
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def bfs(self, matrix, i, j, last=0):
""":type matrix: List[List[int]] :type i: int current row index :type j: int current column index :rtype: void"""
if self.visited[i][j] == 0:
self.visited[i][j] = 1
self.res.append(matrix[i][j])
retry = 0
wh... | the_stack_v2_python_sparse | python/leet_054.py | wolaoa/leetcode | train | 0 | |
441a13a3359174644eab0deca73e2743880ee24e | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(ExpenseForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = 'Nazwa'\nself.fields['company'].label = 'Firma'\nself.fields['company'].required = False\nself.fields['company'].queryset = Company.objects.filter(caffe=self._ca... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(ExpenseForm, self).__init__(*args, **kwargs)
self.fields['name'].label = 'Nazwa'
self.fields['company'].label = 'Firma'
self.fields['company'].required = False
self.fiel... | Responsible for creating an object a cafe pays for during the day. | ExpenseForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpenseForm:
"""Responsible for creating an object a cafe pays for during the day."""
def __init__(self, *args, **kwargs):
"""Initialize all Expense's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commi... | stack_v2_sparse_classes_36k_train_020026 | 4,623 | permissive | [
{
"docstring": "Initialize all Expense's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Override of save method, to add Caffe rela... | 3 | stack_v2_sparse_classes_30k_train_007306 | Implement the Python class `ExpenseForm` described below.
Class description:
Responsible for creating an object a cafe pays for during the day.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Expense's fields.
- def clean_name(self): Check name field.
- def save(self, commit=Tr... | Implement the Python class `ExpenseForm` described below.
Class description:
Responsible for creating an object a cafe pays for during the day.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Expense's fields.
- def clean_name(self): Check name field.
- def save(self, commit=Tr... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class ExpenseForm:
"""Responsible for creating an object a cafe pays for during the day."""
def __init__(self, *args, **kwargs):
"""Initialize all Expense's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpenseForm:
"""Responsible for creating an object a cafe pays for during the day."""
def __init__(self, *args, **kwargs):
"""Initialize all Expense's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(ExpenseForm, self).__init__(*args... | the_stack_v2_python_sparse | caffe/cash/forms.py | VirrageS/io-kawiarnie | train | 3 |
cdbb4260cc79270824a70bd38f7d88d202bea3ea | [
"super(SpatialTransformer, self).__init__()\nsize = volsize\nvectors = [torch.arange(0, s) for s in size]\ngrids = torch.meshgrid(vectors)\ngrid = torch.stack(grids)\ngrid = torch.unsqueeze(grid, 0)\ngrid = grid.type(torch.FloatTensor).cuda() if gpu_use else grid.type(torch.FloatTensor)\nself.register_buffer('grid'... | <|body_start_0|>
super(SpatialTransformer, self).__init__()
size = volsize
vectors = [torch.arange(0, s) for s in size]
grids = torch.meshgrid(vectors)
grid = torch.stack(grids)
grid = torch.unsqueeze(grid, 0)
grid = grid.type(torch.FloatTensor).cuda() if gpu_use ... | [SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample | SpatialTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, volsize, mode='bilinear'):
"""Instiatiate the bloc... | stack_v2_sparse_classes_36k_train_020027 | 11,379 | permissive | [
{
"docstring": "Instiatiate the block :param size: size of input to the spatial transformer block :param mode: method of interpolation for grid_sampler",
"name": "__init__",
"signature": "def __init__(self, volsize, mode='bilinear')"
},
{
"docstring": "Push the src and flow through the spatial t... | 2 | stack_v2_sparse_classes_30k_train_004223 | Implement the Python class `SpatialTransformer` described below.
Class description:
[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample
Method signatures and docstrings:
- def __ini... | Implement the Python class `SpatialTransformer` described below.
Class description:
[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample
Method signatures and docstrings:
- def __ini... | ae368ea39b4049afb4b54cb3447d26107c3a8ab1 | <|skeleton|>
class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, volsize, mode='bilinear'):
"""Instiatiate the bloc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, volsize, mode='bilinear'):
"""Instiatiate the block :param size... | the_stack_v2_python_sparse | UMF-CMGR/models/layers.py | Linfeng-Tang/VIF-Benchmark | train | 29 |
6347ab4ef1ac777104444b8ba2eb96f9ef280896 | [
"token = request.cookies.get('token')\nif token:\n try:\n uuid = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['user_id']\n user = User.query.filter_by(uuid=uuid).first()\n except:\n return make_response(render_template('login.html'), 419)\n flash('You already autho... | <|body_start_0|>
token = request.cookies.get('token')
if token:
try:
uuid = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['user_id']
user = User.query.filter_by(uuid=uuid).first()
except:
return make_response(ren... | Login resource Сontains login form Authentication is not required and shouldn't be done | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
"""Login resource Сontains login form Authentication is not required and shouldn't be done"""
def get(self):
"""Get method Return "login.html" In case of exception can return main page"""
<|body_0|>
def post(self):
"""Post method Return redirect to "main.h... | stack_v2_sparse_classes_36k_train_020028 | 2,820 | no_license | [
{
"docstring": "Get method Return \"login.html\" In case of exception can return main page",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Post method Return redirect to \"main.html\" if session joining was successful In case of exception can return login page",
"name": "pos... | 2 | stack_v2_sparse_classes_30k_train_014717 | Implement the Python class `Login` described below.
Class description:
Login resource Сontains login form Authentication is not required and shouldn't be done
Method signatures and docstrings:
- def get(self): Get method Return "login.html" In case of exception can return main page
- def post(self): Post method Retur... | Implement the Python class `Login` described below.
Class description:
Login resource Сontains login form Authentication is not required and shouldn't be done
Method signatures and docstrings:
- def get(self): Get method Return "login.html" In case of exception can return main page
- def post(self): Post method Retur... | a09780621357957e5575aba36391bef161b5137d | <|skeleton|>
class Login:
"""Login resource Сontains login form Authentication is not required and shouldn't be done"""
def get(self):
"""Get method Return "login.html" In case of exception can return main page"""
<|body_0|>
def post(self):
"""Post method Return redirect to "main.h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Login:
"""Login resource Сontains login form Authentication is not required and shouldn't be done"""
def get(self):
"""Get method Return "login.html" In case of exception can return main page"""
token = request.cookies.get('token')
if token:
try:
uuid =... | the_stack_v2_python_sparse | src/resources/login.py | meg4ik/epam_final_project | train | 0 |
32270ee873a97ac12629847dfce705d5f8caa22c | [
"if not root:\n return []\ndq = deque([root])\nanswer = ['#']\nwhile dq:\n curr = dq.popleft()\n if curr:\n answer.append(str(curr.val))\n dq.append(curr.left)\n dq.append(curr.right)\n else:\n answer.append('#')\nwhile answer[-1] == 'null':\n answer.pop()\nreturn ' '.join... | <|body_start_0|>
if not root:
return []
dq = deque([root])
answer = ['#']
while dq:
curr = dq.popleft()
if curr:
answer.append(str(curr.val))
dq.append(curr.left)
dq.append(curr.right)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_020029 | 1,647 | 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:... | dd28a842709ae00c3793741e411f2cb8e5086fda | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
dq = deque([root])
answer = ['#']
while dq:
curr = dq.popleft()
if curr:
answer.append(... | the_stack_v2_python_sparse | leetcode/297.py | ceuity/algorithm | train | 1 | |
88c54fa14c81e4d2282030add0daa2df4b68a4a2 | [
"minprice1, minprice2, maxprofit1, maxprofit2 = (10 ** 9, 10 ** 9, 0, 0)\nfor price in prices:\n minprice1 = min(price, minprice1)\n maxprofit1 = max(maxprofit1, price - minprice1)\n minprice2 = min(minprice2, price - maxprofit1)\n maxprofit2 = max(maxprofit2, price - minprice2)\nprint(maxprofit1, maxpr... | <|body_start_0|>
minprice1, minprice2, maxprofit1, maxprofit2 = (10 ** 9, 10 ** 9, 0, 0)
for price in prices:
minprice1 = min(price, minprice1)
maxprofit1 = max(maxprofit1, price - minprice1)
minprice2 = min(minprice2, price - maxprofit1)
maxprofit2 = max(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit1(self, prices: List[int]) -> int:
"""贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_020030 | 5,624 | no_license | [
{
"docstring": "贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices: List[int]) -> int... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices: List[int]) -> int: 贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices: List[int]) -> int: 贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def maxProfit1(self, prices: List[int]) -> int:
"""贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit1(self, prices: List[int]) -> int:
"""贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。"""
minprice1, minprice2, maxp... | the_stack_v2_python_sparse | LeetCode_practice/DynamicProgramming/0123.BestTimeToBuyAndSellStock_3.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
e28e80b23443159a5f419b15ea8a1cd5a8596982 | [
"super(Transformer, self).__init__()\nself.drop = nn.Dropout(dropout)\nself.emb = nn.Embedding(ntokens, hidden_size)\nif pos_emb:\n self.pos_emb = nn.Embedding(500, hidden_size)\nself.layers = nn.ModuleList([layers.TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout, dropatt=dropatt, relative_bias=rela... | <|body_start_0|>
super(Transformer, self).__init__()
self.drop = nn.Dropout(dropout)
self.emb = nn.Embedding(ntokens, hidden_size)
if pos_emb:
self.pos_emb = nn.Embedding(500, hidden_size)
self.layers = nn.ModuleList([layers.TransformerLayer(hidden_size, nhead, hidden... | Transformer model. | Transformer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""Transformer model."""
def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0):
"""Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number ... | stack_v2_sparse_classes_36k_train_020031 | 12,717 | permissive | [
{
"docstring": "Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number of output categories nhead: number of self-attention heads dropout: dropout rate dropatt: drop attention rate relative_bias: bool, indicate whether use a relative position based att... | 5 | null | Implement the Python class `Transformer` described below.
Class description:
Transformer model.
Method signatures and docstrings:
- def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0): Initialization. Args: hidden_size: dimension of inputs and... | Implement the Python class `Transformer` described below.
Class description:
Transformer model.
Method signatures and docstrings:
- def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0): Initialization. Args: hidden_size: dimension of inputs and... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Transformer:
"""Transformer model."""
def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0):
"""Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""Transformer model."""
def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0):
"""Initialization. Args: hidden_size: dimension of inputs and hidden states nlayers: number of layers ntokens: number of output cat... | the_stack_v2_python_sparse | structformer/structformer.py | Jimmy-INL/google-research | train | 1 |
0616137592cff8e8c8011b2db8916615de96a07e | [
"res = {}\nut_obj = self.env['l10n.ut']\nfor iwdl_brw in self.browse(self.ids):\n f_xc = ut_obj.sxc(iwdl_brw.invoice_id.company_id.currency_id.id, iwdl_brw.invoice_id.currency_id.id, iwdl_brw.islr_wh_doc_id.date_uid)\n res[iwdl_brw.id] = {'amount': iwdl_brw.base_amount * (iwdl_brw.retencion_islr / 100.0) or 0... | <|body_start_0|>
res = {}
ut_obj = self.env['l10n.ut']
for iwdl_brw in self.browse(self.ids):
f_xc = ut_obj.sxc(iwdl_brw.invoice_id.company_id.currency_id.id, iwdl_brw.invoice_id.currency_id.id, iwdl_brw.islr_wh_doc_id.date_uid)
res[iwdl_brw.id] = {'amount': iwdl_brw.base... | IslrWhDocLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IslrWhDocLine:
def _amount_all(self):
"""Return all amount relating to the invoices lines."""
<|body_0|>
def _retention_rate(self):
"""Return the retention rate of each line."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = {}
ut_obj = ... | stack_v2_sparse_classes_36k_train_020032 | 9,154 | no_license | [
{
"docstring": "Return all amount relating to the invoices lines.",
"name": "_amount_all",
"signature": "def _amount_all(self)"
},
{
"docstring": "Return the retention rate of each line.",
"name": "_retention_rate",
"signature": "def _retention_rate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019665 | Implement the Python class `IslrWhDocLine` described below.
Class description:
Implement the IslrWhDocLine class.
Method signatures and docstrings:
- def _amount_all(self): Return all amount relating to the invoices lines.
- def _retention_rate(self): Return the retention rate of each line. | Implement the Python class `IslrWhDocLine` described below.
Class description:
Implement the IslrWhDocLine class.
Method signatures and docstrings:
- def _amount_all(self): Return all amount relating to the invoices lines.
- def _retention_rate(self): Return the retention rate of each line.
<|skeleton|>
class IslrWh... | 9a492c006d9c0aab68d0b095281dafda97ebdfda | <|skeleton|>
class IslrWhDocLine:
def _amount_all(self):
"""Return all amount relating to the invoices lines."""
<|body_0|>
def _retention_rate(self):
"""Return the retention rate of each line."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IslrWhDocLine:
def _amount_all(self):
"""Return all amount relating to the invoices lines."""
res = {}
ut_obj = self.env['l10n.ut']
for iwdl_brw in self.browse(self.ids):
f_xc = ut_obj.sxc(iwdl_brw.invoice_id.company_id.currency_id.id, iwdl_brw.invoice_id.currency_i... | the_stack_v2_python_sparse | loca_13/l10n_ve_withholding_islr/models/islr_wh_doc.py | hjrhjr/entrenamiento_13_odoo_ref | train | 0 | |
f3dfca092894902a32bcede13550df83662b2c97 | [
"u = rolemanage(self.driver)\nu.open_rolemanage()\nself.assertEqual(u.verify(), True)\nu.modify_obj()\nself.assertEqual(u.sub_tagname(), '角色管理-修改')\nu.clear_name()\nu.add_role('Update', '')\nself.assertEqual(u.company_status(), False)\nu.add_save()\nself.assertEqual(u.success(), True)\nfunction.screenshot(self.driv... | <|body_start_0|>
u = rolemanage(self.driver)
u.open_rolemanage()
self.assertEqual(u.verify(), True)
u.modify_obj()
self.assertEqual(u.sub_tagname(), '角色管理-修改')
u.clear_name()
u.add_role('Update', '')
self.assertEqual(u.company_status(), False)
u.ad... | Test016_Role_Modify_P1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test016_Role_Modify_P1:
def test_modify_name(self):
"""修改角色名称"""
<|body_0|>
def test_modify_description(self):
"""修改角色备注"""
<|body_1|>
def test_modify_type(self):
"""修改角色类型"""
<|body_2|>
def test_modify_back(self):
"""修改角色并返回... | stack_v2_sparse_classes_36k_train_020033 | 2,067 | no_license | [
{
"docstring": "修改角色名称",
"name": "test_modify_name",
"signature": "def test_modify_name(self)"
},
{
"docstring": "修改角色备注",
"name": "test_modify_description",
"signature": "def test_modify_description(self)"
},
{
"docstring": "修改角色类型",
"name": "test_modify_type",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_008304 | Implement the Python class `Test016_Role_Modify_P1` described below.
Class description:
Implement the Test016_Role_Modify_P1 class.
Method signatures and docstrings:
- def test_modify_name(self): 修改角色名称
- def test_modify_description(self): 修改角色备注
- def test_modify_type(self): 修改角色类型
- def test_modify_back(self): 修改角色... | Implement the Python class `Test016_Role_Modify_P1` described below.
Class description:
Implement the Test016_Role_Modify_P1 class.
Method signatures and docstrings:
- def test_modify_name(self): 修改角色名称
- def test_modify_description(self): 修改角色备注
- def test_modify_type(self): 修改角色类型
- def test_modify_back(self): 修改角色... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test016_Role_Modify_P1:
def test_modify_name(self):
"""修改角色名称"""
<|body_0|>
def test_modify_description(self):
"""修改角色备注"""
<|body_1|>
def test_modify_type(self):
"""修改角色类型"""
<|body_2|>
def test_modify_back(self):
"""修改角色并返回... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test016_Role_Modify_P1:
def test_modify_name(self):
"""修改角色名称"""
u = rolemanage(self.driver)
u.open_rolemanage()
self.assertEqual(u.verify(), True)
u.modify_obj()
self.assertEqual(u.sub_tagname(), '角色管理-修改')
u.clear_name()
u.add_role('Update', ''... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/Manage_Role/Test016_role_modify_P1.py | rrmiracle/GlxssLive | train | 0 | |
9ab1cfe79d6bc45b22124f9e4e3451b5fec51767 | [
"self.auctioneer = Auctioneer()\nfor bidder in bidders:\n self.auctioneer.register_bidder(bidder)",
"print(f'Auctioning {item} starting at {start_price}')\nself.auctioneer.set_highest_bid(start_price)\nself.auctioneer.begin_auction()\nauction_result = {x.get_name(): x.get_highest_bid() for x in self.auctioneer... | <|body_start_0|>
self.auctioneer = Auctioneer()
for bidder in bidders:
self.auctioneer.register_bidder(bidder)
<|end_body_0|>
<|body_start_1|>
print(f'Auctioning {item} starting at {start_price}')
self.auctioneer.set_highest_bid(start_price)
self.auctioneer.begin_auc... | Simulates an auction. Is responsible for driving the auctioneer and the bidders. | Auction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
... | stack_v2_sparse_classes_36k_train_020034 | 8,798 | no_license | [
{
"docstring": "Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder",
"name": "__init__",
"signature": "def __init__(self, bidders)"
},
{
"docstring": "Starts the auction for the given item at the g... | 2 | stack_v2_sparse_classes_30k_train_015997 | Implement the Python class `Auction` described below.
Class description:
Simulates an auction. Is responsible for driving the auctioneer and the bidders.
Method signatures and docstrings:
- def __init__(self, bidders): Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :para... | Implement the Python class `Auction` described below.
Class description:
Simulates an auction. Is responsible for driving the auctioneer and the bidders.
Method signatures and docstrings:
- def __init__(self, bidders): Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :para... | c25009c0dd19de18706ff21fe5610c77c5cd89cf | <|skeleton|>
class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
self.auc... | the_stack_v2_python_sparse | Labs/Lab6/auction_simulator.py | gonuxxiv/3522_A01200216 | train | 0 |
13c2070910709952904bde6c9c10bcc81d0ec81d | [
"nx, ny = np.shape(mass_map)\nif nx != ny:\n raise ValueError('Shape of mass map needs to be square!, set as %s %s' % (nx, ny))\nself._mass_map = mass_map\nself._grid_spacing = grid_spacing\nself._redshift = redshift\nself._f_x_mass, self._f_y_mass = convergence_integrals.deflection_from_kappa_grid(self._mass_ma... | <|body_start_0|>
nx, ny = np.shape(mass_map)
if nx != ny:
raise ValueError('Shape of mass map needs to be square!, set as %s %s' % (nx, ny))
self._mass_map = mass_map
self._grid_spacing = grid_spacing
self._redshift = redshift
self._f_x_mass, self._f_y_mass = ... | class to describe a single mass slice | MassSlice | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MassSlice:
"""class to describe a single mass slice"""
def __init__(self, mass_map, grid_spacing, redshift):
""":param mass_map: 2d numpy array of mass map (in units physical Msol) :param grid_spacing: grid spacing of the mass map (in units physical Mpc) :param redshift: redshift"""
... | stack_v2_sparse_classes_36k_train_020035 | 5,293 | permissive | [
{
"docstring": ":param mass_map: 2d numpy array of mass map (in units physical Msol) :param grid_spacing: grid spacing of the mass map (in units physical Mpc) :param redshift: redshift",
"name": "__init__",
"signature": "def __init__(self, mass_map, grid_spacing, redshift)"
},
{
"docstring": "sc... | 2 | stack_v2_sparse_classes_30k_train_006209 | Implement the Python class `MassSlice` described below.
Class description:
class to describe a single mass slice
Method signatures and docstrings:
- def __init__(self, mass_map, grid_spacing, redshift): :param mass_map: 2d numpy array of mass map (in units physical Msol) :param grid_spacing: grid spacing of the mass ... | Implement the Python class `MassSlice` described below.
Class description:
class to describe a single mass slice
Method signatures and docstrings:
- def __init__(self, mass_map, grid_spacing, redshift): :param mass_map: 2d numpy array of mass map (in units physical Msol) :param grid_spacing: grid spacing of the mass ... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class MassSlice:
"""class to describe a single mass slice"""
def __init__(self, mass_map, grid_spacing, redshift):
""":param mass_map: 2d numpy array of mass map (in units physical Msol) :param grid_spacing: grid spacing of the mass map (in units physical Mpc) :param redshift: redshift"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MassSlice:
"""class to describe a single mass slice"""
def __init__(self, mass_map, grid_spacing, redshift):
""":param mass_map: 2d numpy array of mass map (in units physical Msol) :param grid_spacing: grid spacing of the mass map (in units physical Mpc) :param redshift: redshift"""
nx, n... | the_stack_v2_python_sparse | lenstronomy/LensModel/LightConeSim/light_cone.py | lenstronomy/lenstronomy | train | 41 |
b7fec3ac43a445d48f63d973612fa938d64ac075 | [
"self._store = store\nself._session_length = session_length\nself._session_cache_expiration = session_cache_expiration",
"session_key = user_data.username\ndata = self._store.get(session_key)\nnow = arrow.utcnow().float_timestamp\nif data:\n deserialized_data = json.loads(data)\n if now < deserialized_data[... | <|body_start_0|>
self._store = store
self._session_length = session_length
self._session_cache_expiration = session_cache_expiration
<|end_body_0|>
<|body_start_1|>
session_key = user_data.username
data = self._store.get(session_key)
now = arrow.utcnow().float_timestamp
... | KeyValueSessionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyValueSessionHandler:
def __init__(self, store: KeyValueStore, session_length: int, session_cache_expiration: int) -> None:
"""A SessionHandler backed by a key-value store. Args: store: KeyValueStore, a storage structure for the session data. currently this is assumed to take and retur... | stack_v2_sparse_classes_36k_train_020036 | 2,896 | permissive | [
{
"docstring": "A SessionHandler backed by a key-value store. Args: store: KeyValueStore, a storage structure for the session data. currently this is assumed to take and return json blobs session_length: int, the lifetime of a session in seconds session_cache_expiration: int, the time before the cache should ev... | 3 | stack_v2_sparse_classes_30k_train_009112 | Implement the Python class `KeyValueSessionHandler` described below.
Class description:
Implement the KeyValueSessionHandler class.
Method signatures and docstrings:
- def __init__(self, store: KeyValueStore, session_length: int, session_cache_expiration: int) -> None: A SessionHandler backed by a key-value store. Ar... | Implement the Python class `KeyValueSessionHandler` described below.
Class description:
Implement the KeyValueSessionHandler class.
Method signatures and docstrings:
- def __init__(self, store: KeyValueStore, session_length: int, session_cache_expiration: int) -> None: A SessionHandler backed by a key-value store. Ar... | 4f40eb770b57bfc01b68013b24c523d7056e4f5b | <|skeleton|>
class KeyValueSessionHandler:
def __init__(self, store: KeyValueStore, session_length: int, session_cache_expiration: int) -> None:
"""A SessionHandler backed by a key-value store. Args: store: KeyValueStore, a storage structure for the session data. currently this is assumed to take and retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyValueSessionHandler:
def __init__(self, store: KeyValueStore, session_length: int, session_cache_expiration: int) -> None:
"""A SessionHandler backed by a key-value store. Args: store: KeyValueStore, a storage structure for the session data. currently this is assumed to take and return json blobs s... | the_stack_v2_python_sparse | chupacabra_server/app/dbs/keyvalue_session.py | lopez86/chupacabra | train | 0 | |
7ce86d0803c3cd67ffac1aaf8287870203055df0 | [
"self.game_title_name = '飞机大战1.0'\nself.screen_width = 450\nself.screen_height = 750\nself.bg_color = (112, 146, 190)\nself.bg_image_path = 'resources/'\nself.ship_limit = 3\nself.bullet_width = 3\nself.bullet_height = 15\nself.bullet_color = (237, 28, 36)\nself.bullets_allowed = 5\nself.alien_image_path = 'resourc... | <|body_start_0|>
self.game_title_name = '飞机大战1.0'
self.screen_width = 450
self.screen_height = 750
self.bg_color = (112, 146, 190)
self.bg_image_path = 'resources/'
self.ship_limit = 3
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color... | 存储所有的设置类 | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""存储所有的设置类"""
def __init__(self):
"""初始化游戏的静态设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""初始化活动参数"""
<|body_1|>
def speed_up(self):
"""随着游戏的进行(当游戏分数达到某一数值时) 加速"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_020037 | 1,564 | no_license | [
{
"docstring": "初始化游戏的静态设置",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "初始化活动参数",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstring": "随着游戏的进行(当游戏分数达到某一数值时) 加速",
"name": "speed_up",
"s... | 3 | stack_v2_sparse_classes_30k_train_012357 | Implement the Python class `Settings` described below.
Class description:
存储所有的设置类
Method signatures and docstrings:
- def __init__(self): 初始化游戏的静态设置
- def initialize_dynamic_settings(self): 初始化活动参数
- def speed_up(self): 随着游戏的进行(当游戏分数达到某一数值时) 加速 | Implement the Python class `Settings` described below.
Class description:
存储所有的设置类
Method signatures and docstrings:
- def __init__(self): 初始化游戏的静态设置
- def initialize_dynamic_settings(self): 初始化活动参数
- def speed_up(self): 随着游戏的进行(当游戏分数达到某一数值时) 加速
<|skeleton|>
class Settings:
"""存储所有的设置类"""
def __init__(self)... | e83cb5535d6c653e0d4453443b334671cd352192 | <|skeleton|>
class Settings:
"""存储所有的设置类"""
def __init__(self):
"""初始化游戏的静态设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""初始化活动参数"""
<|body_1|>
def speed_up(self):
"""随着游戏的进行(当游戏分数达到某一数值时) 加速"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""存储所有的设置类"""
def __init__(self):
"""初始化游戏的静态设置"""
self.game_title_name = '飞机大战1.0'
self.screen_width = 450
self.screen_height = 750
self.bg_color = (112, 146, 190)
self.bg_image_path = 'resources/'
self.ship_limit = 3
self.bullet... | the_stack_v2_python_sparse | 内容分类/pygame/alien_vs_ships/settings.py | Lunarstaff/Diary | train | 0 |
27ab6ff5584175ef2073fb1c1c1b10a85a90178d | [
"super(ObfEncoder, self).__init__()\nself.n = n_word\nself.m = m_emb\nself.word_ids = word_ids\nself.new_id = {self.word_ids[reid]: reid for reid in range(n_word)}\nself.embedder = nn.Embedding(n_word, m_emb, padding_idx=-1, _weight=emb_weight)\nself.embedder.weight.requires_grad = False\nself.MLP = nn.Sequential(n... | <|body_start_0|>
super(ObfEncoder, self).__init__()
self.n = n_word
self.m = m_emb
self.word_ids = word_ids
self.new_id = {self.word_ids[reid]: reid for reid in range(n_word)}
self.embedder = nn.Embedding(n_word, m_emb, padding_idx=-1, _weight=emb_weight)
self.emb... | ObfEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObfEncoder:
def __init__(self, n_word, m_emb, word_ids, emb_weight):
"""emb_weight of (n_word, m_emb) is the tensor of the embedding of proper noun or noun of number n_word, m_emb is the embedded dimension, in this most simplistic setting, we use a MLP to select the word to be changed :p... | stack_v2_sparse_classes_36k_train_020038 | 9,621 | no_license | [
{
"docstring": "emb_weight of (n_word, m_emb) is the tensor of the embedding of proper noun or noun of number n_word, m_emb is the embedded dimension, in this most simplistic setting, we use a MLP to select the word to be changed :param n_word: :param m_emb: :param emb_weight:",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_013554 | Implement the Python class `ObfEncoder` described below.
Class description:
Implement the ObfEncoder class.
Method signatures and docstrings:
- def __init__(self, n_word, m_emb, word_ids, emb_weight): emb_weight of (n_word, m_emb) is the tensor of the embedding of proper noun or noun of number n_word, m_emb is the em... | Implement the Python class `ObfEncoder` described below.
Class description:
Implement the ObfEncoder class.
Method signatures and docstrings:
- def __init__(self, n_word, m_emb, word_ids, emb_weight): emb_weight of (n_word, m_emb) is the tensor of the embedding of proper noun or noun of number n_word, m_emb is the em... | aa1da79dea82c36bc1b8d4d83e1d8ad40871d330 | <|skeleton|>
class ObfEncoder:
def __init__(self, n_word, m_emb, word_ids, emb_weight):
"""emb_weight of (n_word, m_emb) is the tensor of the embedding of proper noun or noun of number n_word, m_emb is the embedded dimension, in this most simplistic setting, we use a MLP to select the word to be changed :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObfEncoder:
def __init__(self, n_word, m_emb, word_ids, emb_weight):
"""emb_weight of (n_word, m_emb) is the tensor of the embedding of proper noun or noun of number n_word, m_emb is the embedded dimension, in this most simplistic setting, we use a MLP to select the word to be changed :param n_word: :... | the_stack_v2_python_sparse | net/encoder.py | ichn-hu/Parsing-Obfuscation | train | 3 | |
1cb10c41d4f9d7a769f4f038005cf1fc737ce22a | [
"if isinstance(value, int):\n value = str(value)\nif value.isdigit():\n return queryset.filter(device=value)\nelse:\n return queryset.filter(device__hostname=value)",
"if isinstance(value, int):\n value = str(value)\nif value.isdigit():\n return queryset.filter(type=value)\nelse:\n return querys... | <|body_start_0|>
if isinstance(value, int):
value = str(value)
if value.isdigit():
return queryset.filter(device=value)
else:
return queryset.filter(device__hostname=value)
<|end_body_0|>
<|body_start_1|>
if isinstance(value, int):
value =... | Filter for Protocol objects. | ProtocolFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtocolFilter:
"""Filter for Protocol objects."""
def filter_device(self, queryset, name, value):
"""Overload to use natural key."""
<|body_0|>
def filter_type(self, queryset, name, value):
"""Overload to use natural key."""
<|body_1|>
def filter_in... | stack_v2_sparse_classes_36k_train_020039 | 8,091 | permissive | [
{
"docstring": "Overload to use natural key.",
"name": "filter_device",
"signature": "def filter_device(self, queryset, name, value)"
},
{
"docstring": "Overload to use natural key.",
"name": "filter_type",
"signature": "def filter_type(self, queryset, name, value)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_013627 | Implement the Python class `ProtocolFilter` described below.
Class description:
Filter for Protocol objects.
Method signatures and docstrings:
- def filter_device(self, queryset, name, value): Overload to use natural key.
- def filter_type(self, queryset, name, value): Overload to use natural key.
- def filter_interf... | Implement the Python class `ProtocolFilter` described below.
Class description:
Filter for Protocol objects.
Method signatures and docstrings:
- def filter_device(self, queryset, name, value): Overload to use natural key.
- def filter_type(self, queryset, name, value): Overload to use natural key.
- def filter_interf... | 941b11f84f5c0d210f638654a6ed34a5610af22a | <|skeleton|>
class ProtocolFilter:
"""Filter for Protocol objects."""
def filter_device(self, queryset, name, value):
"""Overload to use natural key."""
<|body_0|>
def filter_type(self, queryset, name, value):
"""Overload to use natural key."""
<|body_1|>
def filter_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtocolFilter:
"""Filter for Protocol objects."""
def filter_device(self, queryset, name, value):
"""Overload to use natural key."""
if isinstance(value, int):
value = str(value)
if value.isdigit():
return queryset.filter(device=value)
else:
... | the_stack_v2_python_sparse | nsot/api/filters.py | dropbox/nsot | train | 414 |
0d3eeafc0dbe7e846f5f495a6b42664103882eaf | [
"if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.positive_weights = all((edge.weight >= 0 for edge in self.graph.iteredges()))\nself.distance = None",
"if self.positive_weights:\n self._new_graph = self.graph\nelse:\n self._new_graph = self.graph.__cl... | <|body_start_0|>
if not graph.is_directed():
raise ValueError('the graph is not directed')
self.graph = graph
self.positive_weights = all((edge.weight >= 0 for edge in self.graph.iteredges()))
self.distance = None
<|end_body_0|>
<|body_start_1|>
if self.positive_weig... | The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from graphtheory.structures.edges import Edge >... | JohnsonFaster | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JohnsonFaster:
"""The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from g... | stack_v2_sparse_classes_36k_train_020040 | 6,802 | permissive | [
{
"docstring": "The algorithm initialization. Parameters ---------- graph : directed weighted graph",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Finding all shortest paths.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000335 | Implement the Python class `JohnsonFaster` described below.
Class description:
The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instanc... | Implement the Python class `JohnsonFaster` described below.
Class description:
The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instanc... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class JohnsonFaster:
"""The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JohnsonFaster:
"""The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from graphtheory.st... | the_stack_v2_python_sparse | graphtheory/shortestpaths/johnson.py | kgashok/graphs-dict | train | 0 |
06a70b6dbc6b7f96f5f0e54756bb20f98e64dc00 | [
"if not root:\n return\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n current = queue.popleft()\n left = current.left\n right = current.right\n current.left = right\n current.right = left\n if left:\n queue.append(left)\n if right:\n queue.append(right)\nretur... | <|body_start_0|>
if not root:
return
queue = collections.deque()
queue.append(root)
while queue:
current = queue.popleft()
left = current.left
right = current.right
current.left = right
current.right = left
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def invertTree_recursive(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
retu... | stack_v2_sparse_classes_36k_train_020041 | 1,080 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree",
"signature": "def invertTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree_recursive",
"signature": "def invertTree_recursive(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013408 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def invertTree_recursive(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def invertTree_recursive(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class Solution:
... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def invertTree_recursive(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
if not root:
return
queue = collections.deque()
queue.append(root)
while queue:
current = queue.popleft()
left = current.left
right = curren... | the_stack_v2_python_sparse | Algorithm/226_Invert_Binary_Tree.py | Gi1ia/TechNoteBook | train | 7 | |
2775a516ff89b9063062c9217b4ab619a03f763f | [
"super().__init__()\nself.num_classes = num_classes\nself.num_grid = num_grid\nself.num_bbox = num_bbox\nself.image_shapes = image_shapes\nself.num_threshold = num_threshold",
"dtype = yolo_bbox.dtype\ndevice = yolo_bbox.device\nH, W = image_shape\ngrid_idx = torch.arange(self.num_grid, dtype=dtype, device=device... | <|body_start_0|>
super().__init__()
self.num_classes = num_classes
self.num_grid = num_grid
self.num_bbox = num_bbox
self.image_shapes = image_shapes
self.num_threshold = num_threshold
<|end_body_0|>
<|body_start_1|>
dtype = yolo_bbox.dtype
device = yolo_... | YOLOv1Postprocess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YOLOv1Postprocess:
def __init__(self, num_classes, num_grid, num_bbox, image_shapes, num_threshold):
"""Constructor for YOLOv1Postprocess"""
<|body_0|>
def boxes_decode(self, yolo_bbox, image_shape):
"""Args: yolo_bbox: (Tensor[num_grid**2, 5]) image_shape: Tuple(hei... | stack_v2_sparse_classes_36k_train_020042 | 10,177 | permissive | [
{
"docstring": "Constructor for YOLOv1Postprocess",
"name": "__init__",
"signature": "def __init__(self, num_classes, num_grid, num_bbox, image_shapes, num_threshold)"
},
{
"docstring": "Args: yolo_bbox: (Tensor[num_grid**2, 5]) image_shape: Tuple(height, weight) Returns: transformed_boxes: (Ten... | 4 | stack_v2_sparse_classes_30k_train_008933 | Implement the Python class `YOLOv1Postprocess` described below.
Class description:
Implement the YOLOv1Postprocess class.
Method signatures and docstrings:
- def __init__(self, num_classes, num_grid, num_bbox, image_shapes, num_threshold): Constructor for YOLOv1Postprocess
- def boxes_decode(self, yolo_bbox, image_sh... | Implement the Python class `YOLOv1Postprocess` described below.
Class description:
Implement the YOLOv1Postprocess class.
Method signatures and docstrings:
- def __init__(self, num_classes, num_grid, num_bbox, image_shapes, num_threshold): Constructor for YOLOv1Postprocess
- def boxes_decode(self, yolo_bbox, image_sh... | 667488e41878d7f0376142a7ae9e1b43c0edd68a | <|skeleton|>
class YOLOv1Postprocess:
def __init__(self, num_classes, num_grid, num_bbox, image_shapes, num_threshold):
"""Constructor for YOLOv1Postprocess"""
<|body_0|>
def boxes_decode(self, yolo_bbox, image_shape):
"""Args: yolo_bbox: (Tensor[num_grid**2, 5]) image_shape: Tuple(hei... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YOLOv1Postprocess:
def __init__(self, num_classes, num_grid, num_bbox, image_shapes, num_threshold):
"""Constructor for YOLOv1Postprocess"""
super().__init__()
self.num_classes = num_classes
self.num_grid = num_grid
self.num_bbox = num_bbox
self.image_shapes = i... | the_stack_v2_python_sparse | cvmodels/models/yolo_v1.py | welkin-feng/ComputerVision | train | 3 | |
f148e743bb4383215204e8589fc5d3e0870ec399 | [
"shop = ShopService.get_by_id(id)\ncontact_list = ShopContactService.get_by_shop_id(id)\nfee_list = ShopFeeService.get_fee_by_shop_id(id)\nshop['contact_list'] = contact_list\nshop['fee_list'] = fee_list\nreturn api_response(data=shop)",
"parsed_data = self.parsed_data\ntry:\n ShopService.update_shop_by_id(id,... | <|body_start_0|>
shop = ShopService.get_by_id(id)
contact_list = ShopContactService.get_by_shop_id(id)
fee_list = ShopFeeService.get_fee_by_shop_id(id)
shop['contact_list'] = contact_list
shop['fee_list'] = fee_list
return api_response(data=shop)
<|end_body_0|>
<|body_st... | ShopApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShopApi:
def get(self, id):
"""根据ID查询店铺"""
<|body_0|>
def put(self, id):
"""根据ID修改店铺信息"""
<|body_1|>
def delete(self, id):
"""根据ID删除店铺"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
shop = ShopService.get_by_id(id)
cont... | stack_v2_sparse_classes_36k_train_020043 | 8,580 | no_license | [
{
"docstring": "根据ID查询店铺",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "根据ID修改店铺信息",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "根据ID删除店铺",
"name": "delete",
"signature": "def delete(self, id)"
}
] | 3 | stack_v2_sparse_classes_30k_train_006713 | Implement the Python class `ShopApi` described below.
Class description:
Implement the ShopApi class.
Method signatures and docstrings:
- def get(self, id): 根据ID查询店铺
- def put(self, id): 根据ID修改店铺信息
- def delete(self, id): 根据ID删除店铺 | Implement the Python class `ShopApi` described below.
Class description:
Implement the ShopApi class.
Method signatures and docstrings:
- def get(self, id): 根据ID查询店铺
- def put(self, id): 根据ID修改店铺信息
- def delete(self, id): 根据ID删除店铺
<|skeleton|>
class ShopApi:
def get(self, id):
"""根据ID查询店铺"""
<|b... | e87f98f5fbe42c465473d83cb2a535209a8e8287 | <|skeleton|>
class ShopApi:
def get(self, id):
"""根据ID查询店铺"""
<|body_0|>
def put(self, id):
"""根据ID修改店铺信息"""
<|body_1|>
def delete(self, id):
"""根据ID删除店铺"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShopApi:
def get(self, id):
"""根据ID查询店铺"""
shop = ShopService.get_by_id(id)
contact_list = ShopContactService.get_by_shop_id(id)
fee_list = ShopFeeService.get_fee_by_shop_id(id)
shop['contact_list'] = contact_list
shop['fee_list'] = fee_list
return api_r... | the_stack_v2_python_sparse | creole/wsgi/api/v1/endpoint/shop.py | Creoles/creole | train | 0 | |
18ede653690d0701a8b95b1ebacd1eecf87ce8bc | [
"n = len(nums)\nfor idx in range(n):\n if nums[idx] <= 0:\n nums[idx] = n + 1\nfor idx, num in enumerate(nums):\n num = abs(num)\n if num <= n:\n nums[num - 1] = -abs(nums[num - 1])\nfor idx, num in enumerate(nums):\n if num > 0:\n return idx + 1\nreturn n + 1",
"n = len(nums)\nfo... | <|body_start_0|>
n = len(nums)
for idx in range(n):
if nums[idx] <= 0:
nums[idx] = n + 1
for idx, num in enumerate(nums):
num = abs(num)
if num <= n:
nums[num - 1] = -abs(nums[num - 1])
for idx, num in enumerate(nums):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
"""利用数组构建哈希表"""
<|body_0|>
def firstMissingPositiveSwap(self, nums: List[int]) -> int:
"""交换元素"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
for idx in range(n... | stack_v2_sparse_classes_36k_train_020044 | 1,713 | no_license | [
{
"docstring": "利用数组构建哈希表",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums: List[int]) -> int"
},
{
"docstring": "交换元素",
"name": "firstMissingPositiveSwap",
"signature": "def firstMissingPositiveSwap(self, nums: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_010149 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums: List[int]) -> int: 利用数组构建哈希表
- def firstMissingPositiveSwap(self, nums: List[int]) -> int: 交换元素 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums: List[int]) -> int: 利用数组构建哈希表
- def firstMissingPositiveSwap(self, nums: List[int]) -> int: 交换元素
<|skeleton|>
class Solution:
def firstM... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
"""利用数组构建哈希表"""
<|body_0|>
def firstMissingPositiveSwap(self, nums: List[int]) -> int:
"""交换元素"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
"""利用数组构建哈希表"""
n = len(nums)
for idx in range(n):
if nums[idx] <= 0:
nums[idx] = n + 1
for idx, num in enumerate(nums):
num = abs(num)
if num <= n:
... | the_stack_v2_python_sparse | 41.缺失的第一个正数/solution.py | QtTao/daily_leetcode | train | 0 | |
184bacff7cc4eb7a9394f64f55ec53948a843542 | [
"if MOT_NUM == 'A':\n self.EN_A = pyb.Pin(pyb.Pin.board.PA10, pyb.Pin.OUT_PP)\n self.IN1A = pyb.Pin(pyb.Pin.board.PB4, pyb.Pin.OUT_PP)\n self.IN2A = pyb.Pin(pyb.Pin.board.PB5, pyb.Pin.OUT_PP)\n self.EN_A.high()\n self.IN1A.low()\n self.IN2A.low()\n self.tim3 = pyb.Timer(3, freq=20000)\n self... | <|body_start_0|>
if MOT_NUM == 'A':
self.EN_A = pyb.Pin(pyb.Pin.board.PA10, pyb.Pin.OUT_PP)
self.IN1A = pyb.Pin(pyb.Pin.board.PB4, pyb.Pin.OUT_PP)
self.IN2A = pyb.Pin(pyb.Pin.board.PB5, pyb.Pin.OUT_PP)
self.EN_A.high()
self.IN1A.low()
self.... | This class implements a motor driver for the ME405 board. | MotorDriver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotorDriver:
"""This class implements a motor driver for the ME405 board."""
def __init__(self, MOT_NUM):
"""Creates a motor driver by initializing GPIO pins and turning the motor off for safety."""
<|body_0|>
def set_duty_cycle(self, level):
"""This method sets ... | stack_v2_sparse_classes_36k_train_020045 | 2,152 | no_license | [
{
"docstring": "Creates a motor driver by initializing GPIO pins and turning the motor off for safety.",
"name": "__init__",
"signature": "def __init__(self, MOT_NUM)"
},
{
"docstring": "This method sets the duty cycle to be sent to the motor to the given level. Positive values cause torque in o... | 2 | stack_v2_sparse_classes_30k_train_018695 | Implement the Python class `MotorDriver` described below.
Class description:
This class implements a motor driver for the ME405 board.
Method signatures and docstrings:
- def __init__(self, MOT_NUM): Creates a motor driver by initializing GPIO pins and turning the motor off for safety.
- def set_duty_cycle(self, leve... | Implement the Python class `MotorDriver` described below.
Class description:
This class implements a motor driver for the ME405 board.
Method signatures and docstrings:
- def __init__(self, MOT_NUM): Creates a motor driver by initializing GPIO pins and turning the motor off for safety.
- def set_duty_cycle(self, leve... | d27d7f7ae21f36cf1cb6d3933bb733dfca9906dc | <|skeleton|>
class MotorDriver:
"""This class implements a motor driver for the ME405 board."""
def __init__(self, MOT_NUM):
"""Creates a motor driver by initializing GPIO pins and turning the motor off for safety."""
<|body_0|>
def set_duty_cycle(self, level):
"""This method sets ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MotorDriver:
"""This class implements a motor driver for the ME405 board."""
def __init__(self, MOT_NUM):
"""Creates a motor driver by initializing GPIO pins and turning the motor off for safety."""
if MOT_NUM == 'A':
self.EN_A = pyb.Pin(pyb.Pin.board.PA10, pyb.Pin.OUT_PP)
... | the_stack_v2_python_sparse | ME-405_Final_Project/motor.py | skylin008/ME405 | train | 0 |
4d327ac80543bfe91c965268f1c76536df532cc8 | [
"self.LAST_GPS_ID = '$GPRMC'\nself.gps_df = pd.DataFrame(columns=['dt', 'nmea'])\nself.adcp_list = []\nself.batch_write = bytes()\nself.load_gps_dir(gps_folder_path)\nself.load_adcp_dir(adcp_folder_path)",
"if not os.path.exists(folder_path):\n print('GPS Folder does not exist')\n return\ngps_files = [f for... | <|body_start_0|>
self.LAST_GPS_ID = '$GPRMC'
self.gps_df = pd.DataFrame(columns=['dt', 'nmea'])
self.adcp_list = []
self.batch_write = bytes()
self.load_gps_dir(gps_folder_path)
self.load_adcp_dir(adcp_folder_path)
<|end_body_0|>
<|body_start_1|>
if not os.path.e... | Merage the ADCP and GPS data. Put the ADCP data in a folder. Put the GPS data in a separate folder. Give to the two folder paths. It will then map all the GPS data to a time. It will then read in the ADCP and match the time from the GPS and the ADCP. | MergeAdcpGps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeAdcpGps:
"""Merage the ADCP and GPS data. Put the ADCP data in a folder. Put the GPS data in a separate folder. Give to the two folder paths. It will then map all the GPS data to a time. It will then read in the ADCP and match the time from the GPS and the ADCP."""
def __init__(self, gp... | stack_v2_sparse_classes_36k_train_020046 | 9,424 | no_license | [
{
"docstring": "Give the GPS folder and ADCP folder paths. It will then read in all the GPS data and map it to a time. It will then read in all the ADCP data and add the GPS data to the ADCP data. :param self: :param gps_folder_path: GPS Folder :param adcp_folder_path: ADCP Folder :return:",
"name": "__init... | 6 | null | Implement the Python class `MergeAdcpGps` described below.
Class description:
Merage the ADCP and GPS data. Put the ADCP data in a folder. Put the GPS data in a separate folder. Give to the two folder paths. It will then map all the GPS data to a time. It will then read in the ADCP and match the time from the GPS and ... | Implement the Python class `MergeAdcpGps` described below.
Class description:
Merage the ADCP and GPS data. Put the ADCP data in a folder. Put the GPS data in a separate folder. Give to the two folder paths. It will then map all the GPS data to a time. It will then read in the ADCP and match the time from the GPS and ... | 384edef9c14ae5296d7e123eec473b29905a8a58 | <|skeleton|>
class MergeAdcpGps:
"""Merage the ADCP and GPS data. Put the ADCP data in a folder. Put the GPS data in a separate folder. Give to the two folder paths. It will then map all the GPS data to a time. It will then read in the ADCP and match the time from the GPS and the ADCP."""
def __init__(self, gp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeAdcpGps:
"""Merage the ADCP and GPS data. Put the ADCP data in a folder. Put the GPS data in a separate folder. Give to the two folder paths. It will then map all the GPS data to a time. It will then read in the ADCP and match the time from the GPS and the ADCP."""
def __init__(self, gps_folder_path... | the_stack_v2_python_sparse | Utilities/merge_adcp_gps.py | ricorx7/rti_python-1 | train | 0 |
2e75f3f70ab13799d3b163d4f2873035a0de5839 | [
"clickndrag.Plane.__init__(self, name, rect, draggable=False, grab=False)\nself.background_color = self.cached_color = self.current_color = BACKGROUND_COLOR\nif background_color is not None:\n self.background_color = self.cached_color = self.current_color = background_color\nif text is not None:\n self.text =... | <|body_start_0|>
clickndrag.Plane.__init__(self, name, rect, draggable=False, grab=False)
self.background_color = self.cached_color = self.current_color = BACKGROUND_COLOR
if background_color is not None:
self.background_color = self.cached_color = self.current_color = background_col... | A clickndrag.Plane which displays a text. Additional attributes: Label.text The text to be written on the Label Label.cached_text Cache to catch changes Label.background_color The original background color for this Label Label.current_color The current background color Label.cached_color A cache for color changes | Label | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Label:
"""A clickndrag.Plane which displays a text. Additional attributes: Label.text The text to be written on the Label Label.cached_text Cache to catch changes Label.background_color The original background color for this Label Label.current_color The current background color Label.cached_colo... | stack_v2_sparse_classes_36k_train_020047 | 27,668 | permissive | [
{
"docstring": "Initialise the Label. text is the text to be written on the Label. If text is None, it is replaced by an empty string.",
"name": "__init__",
"signature": "def __init__(self, name, text, rect, background_color=None)"
},
{
"docstring": "Renew the text on the label, then call the ba... | 3 | stack_v2_sparse_classes_30k_train_008460 | Implement the Python class `Label` described below.
Class description:
A clickndrag.Plane which displays a text. Additional attributes: Label.text The text to be written on the Label Label.cached_text Cache to catch changes Label.background_color The original background color for this Label Label.current_color The cur... | Implement the Python class `Label` described below.
Class description:
A clickndrag.Plane which displays a text. Additional attributes: Label.text The text to be written on the Label Label.cached_text Cache to catch changes Label.background_color The original background color for this Label Label.current_color The cur... | c2fc3d4e9beedb8487cfa4bfa13bdf55ec36af97 | <|skeleton|>
class Label:
"""A clickndrag.Plane which displays a text. Additional attributes: Label.text The text to be written on the Label Label.cached_text Cache to catch changes Label.background_color The original background color for this Label Label.current_color The current background color Label.cached_colo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Label:
"""A clickndrag.Plane which displays a text. Additional attributes: Label.text The text to be written on the Label Label.cached_text Cache to catch changes Label.background_color The original background color for this Label Label.current_color The current background color Label.cached_color A cache for... | the_stack_v2_python_sparse | reference_scripts/clickndrag-0.4.1/clickndrag/gui.py | stivosaurus/rpi-snippets | train | 1 |
e99df0a6a19f135618627f9b45e90722114e133e | [
"if pr_number and (not update_git):\n logging.error(f'Cannot have --pr-number={pr_number} without --update-git')\n sys.exit(1)\nif not export_ts_id:\n export_ts_id = datetime.datetime.now().strftime('%Y%m%d_%H%M')\nif export and (not export_bucket_name):\n logging.error('Cannot have --export without --e... | <|body_start_0|>
if pr_number and (not update_git):
logging.error(f'Cannot have --pr-number={pr_number} without --update-git')
sys.exit(1)
if not export_ts_id:
export_ts_id = datetime.datetime.now().strftime('%Y%m%d_%H%M')
if export and (not export_bucket_name... | Commands to run the CI scripts in a container environment similar to the one used by the CI | Local_CI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Local_CI:
"""Commands to run the CI scripts in a container environment similar to the one used by the CI"""
def run(self, ci_command, pr_number=None, git_repo='https://github.com/openshift-psap/ci-artifacts', git_ref='main', namespace='ci-artifacts', istag='ci-artifacts:main', pod_name='ci-a... | stack_v2_sparse_classes_36k_train_020048 | 6,167 | permissive | [
{
"docstring": "Runs a given CI command Args: git_repo: The Github repo to use. git_ref: The Github ref to use. pr_number: The ID of the PR to use for the repository. ci_command: The CI command to run. namespace: The namespace in which the image. istag: The imagestream tag to use. pod_name: The name to give to ... | 2 | null | Implement the Python class `Local_CI` described below.
Class description:
Commands to run the CI scripts in a container environment similar to the one used by the CI
Method signatures and docstrings:
- def run(self, ci_command, pr_number=None, git_repo='https://github.com/openshift-psap/ci-artifacts', git_ref='main',... | Implement the Python class `Local_CI` described below.
Class description:
Commands to run the CI scripts in a container environment similar to the one used by the CI
Method signatures and docstrings:
- def run(self, ci_command, pr_number=None, git_repo='https://github.com/openshift-psap/ci-artifacts', git_ref='main',... | 024d2a756399887a329e18fedd4fbc466a264340 | <|skeleton|>
class Local_CI:
"""Commands to run the CI scripts in a container environment similar to the one used by the CI"""
def run(self, ci_command, pr_number=None, git_repo='https://github.com/openshift-psap/ci-artifacts', git_ref='main', namespace='ci-artifacts', istag='ci-artifacts:main', pod_name='ci-a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Local_CI:
"""Commands to run the CI scripts in a container environment similar to the one used by the CI"""
def run(self, ci_command, pr_number=None, git_repo='https://github.com/openshift-psap/ci-artifacts', git_ref='main', namespace='ci-artifacts', istag='ci-artifacts:main', pod_name='ci-artifacts', se... | the_stack_v2_python_sparse | toolbox/local_ci.py | dagrayvid/ci-artifacts | train | 0 |
9404efa039a7ea19d5d1dae6f9badfc5ba8dc9b9 | [
"if request.path.startswith(htk_setting('HTK_PATH_ADMIN')) or request.path.startswith(htk_setting('HTK_PATH_ADMINTOOLS')):\n pass\nelif is_allowed_to_emulate_users(request.user):\n from htk.apps.accounts.utils import get_user_by_id\n from htk.apps.accounts.utils import get_user_by_username\n user_id = r... | <|body_start_0|>
if request.path.startswith(htk_setting('HTK_PATH_ADMIN')) or request.path.startswith(htk_setting('HTK_PATH_ADMINTOOLS')):
pass
elif is_allowed_to_emulate_users(request.user):
from htk.apps.accounts.utils import get_user_by_id
from htk.apps.accounts.ut... | HtkEmulateUserMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtkEmulateUserMiddleware:
def process_request(self, request):
"""Replace the authenticated `request.user` if properly emulating"""
<|body_0|>
def process_response(self, request, response):
"""Delete user emulation cookies if they should not be set"""
<|body_1... | stack_v2_sparse_classes_36k_train_020049 | 2,679 | permissive | [
{
"docstring": "Replace the authenticated `request.user` if properly emulating",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Delete user emulation cookies if they should not be set",
"name": "process_response",
"signature": "def process... | 2 | stack_v2_sparse_classes_30k_val_000599 | Implement the Python class `HtkEmulateUserMiddleware` described below.
Class description:
Implement the HtkEmulateUserMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Replace the authenticated `request.user` if properly emulating
- def process_response(self, request, response)... | Implement the Python class `HtkEmulateUserMiddleware` described below.
Class description:
Implement the HtkEmulateUserMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Replace the authenticated `request.user` if properly emulating
- def process_response(self, request, response)... | e80acbf5057a273028b006167d12194977365066 | <|skeleton|>
class HtkEmulateUserMiddleware:
def process_request(self, request):
"""Replace the authenticated `request.user` if properly emulating"""
<|body_0|>
def process_response(self, request, response):
"""Delete user emulation cookies if they should not be set"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtkEmulateUserMiddleware:
def process_request(self, request):
"""Replace the authenticated `request.user` if properly emulating"""
if request.path.startswith(htk_setting('HTK_PATH_ADMIN')) or request.path.startswith(htk_setting('HTK_PATH_ADMINTOOLS')):
pass
elif is_allowed_... | the_stack_v2_python_sparse | admintools/middleware.py | pkkup/django-htk | train | 1 | |
8b99a2243ebd5dee1bc76d694a9e93ec328b5709 | [
"x = y = ''\nwhile l1 or l2:\n if l1:\n x = x + str(l1.val)\n l1 = l1.next\n if l2:\n y = y + str(l2.val)\n l2 = l2.next\nx, y = (x[::-1], y[::-1])\nret = str(int(x) + int(y))[::-1]\nself = head = ListNode(0)\nfor c in ret:\n head.next = ListNode(int(c))\n head = head.next\nr... | <|body_start_0|>
x = y = ''
while l1 or l2:
if l1:
x = x + str(l1.val)
l1 = l1.next
if l2:
y = y + str(l2.val)
l2 = l2.next
x, y = (x[::-1], y[::-1])
ret = str(int(x) + int(y))[::-1]
self = he... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""使用字符串拼接的方式来实现"""
<|body_0|>
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
"""使用初等数学的加法来实现,短的链表高位的值可以用0来代替"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_020050 | 1,512 | no_license | [
{
"docstring": "使用字符串拼接的方式来实现",
"name": "addTwoNumbers_1",
"signature": "def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "使用初等数学的加法来实现,短的链表高位的值可以用0来代替",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> List... | 2 | stack_v2_sparse_classes_30k_test_000487 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode: 使用字符串拼接的方式来实现
- def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 使用初等数学的加法来实现,短的链表高位的值可以用0来代替 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode: 使用字符串拼接的方式来实现
- def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 使用初等数学的加法来实现,短的链表高位的值可以用0来代替
... | 41d6d4c748a6543d1c4027badb17ffbb64b43f2d | <|skeleton|>
class Solution:
def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""使用字符串拼接的方式来实现"""
<|body_0|>
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
"""使用初等数学的加法来实现,短的链表高位的值可以用0来代替"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""使用字符串拼接的方式来实现"""
x = y = ''
while l1 or l2:
if l1:
x = x + str(l1.val)
l1 = l1.next
if l2:
y = y + str(l2.val)
l2 = l2... | the_stack_v2_python_sparse | learn/2.py | xiaoqiangjava/python-algorithm | train | 0 | |
16c3c2469b6f31aae5220c7c2ad830d196c5c0fc | [
"data = memcache.get(sid)\nif not data:\n session = ndb.model.Key(cls, sid).get()\n if session:\n data = session.data\n memcache.set(sid, data)\nreturn data",
"usersessions = Session.query(Session.user_id == int(user_id)).fetch()\nlogging.info(usersessions)\nfor session in usersessions:\n s... | <|body_start_0|>
data = memcache.get(sid)
if not data:
session = ndb.model.Key(cls, sid).get()
if session:
data = session.data
memcache.set(sid, data)
return data
<|end_body_0|>
<|body_start_1|>
usersessions = Session.query(Session... | Session | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Session:
def get_by_sid(cls, sid):
"""Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity."""
<|body_0|>
def delete_by_user_id(cls, self, user_id):
"""Returns a ``Session`` instance by session id. :param si... | stack_v2_sparse_classes_36k_train_020051 | 7,647 | no_license | [
{
"docstring": "Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity.",
"name": "get_by_sid",
"signature": "def get_by_sid(cls, sid)"
},
{
"docstring": "Returns a ``Session`` instance by session id. :param sid: A session id. :returns: A... | 2 | stack_v2_sparse_classes_30k_train_005109 | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def get_by_sid(cls, sid): Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity.
- def delete_by_user_id(cls, self, user_... | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def get_by_sid(cls, sid): Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity.
- def delete_by_user_id(cls, self, user_... | 2dd85af47312c4a229c927b28ca02d443d03053e | <|skeleton|>
class Session:
def get_by_sid(cls, sid):
"""Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity."""
<|body_0|>
def delete_by_user_id(cls, self, user_id):
"""Returns a ``Session`` instance by session id. :param si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Session:
def get_by_sid(cls, sid):
"""Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity."""
data = memcache.get(sid)
if not data:
session = ndb.model.Key(cls, sid).get()
if session:
d... | the_stack_v2_python_sparse | models.py | resida/cointemplebotph1 | train | 1 | |
ad817589c8a0344ed687beb385b63cad7b1757ab | [
"super().__init__()\nchannels, img_size, _ = img_shape\n\ndef discriminator_block(in_filters, out_filters):\n \"\"\"Returns downsampling layers of each discriminator block\"\"\"\n layers = [torch.nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1), torch.nn.LeakyReLU(0.01)]\n return layers\nlayers =... | <|body_start_0|>
super().__init__()
channels, img_size, _ = img_shape
def discriminator_block(in_filters, out_filters):
"""Returns downsampling layers of each discriminator block"""
layers = [torch.nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1), torch.nn.Leak... | A Discriminative model with an auxiliary classification task | Discriminator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Discriminator:
"""A Discriminative model with an auxiliary classification task"""
def __init__(self, img_shape=(3, 128, 128), c_dim=5, n_strided=6):
"""Parameters ---------- img_shape : tuple the shape of the input images (should include the channels and exclude the batch dimension) ... | stack_v2_sparse_classes_36k_train_020052 | 6,187 | permissive | [
{
"docstring": "Parameters ---------- img_shape : tuple the shape of the input images (should include the channels and exclude the batch dimension) c_dim : int the size of the code dimension for encoded attributes n_strided : int number of strided convolutions",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_001466 | Implement the Python class `Discriminator` described below.
Class description:
A Discriminative model with an auxiliary classification task
Method signatures and docstrings:
- def __init__(self, img_shape=(3, 128, 128), c_dim=5, n_strided=6): Parameters ---------- img_shape : tuple the shape of the input images (shou... | Implement the Python class `Discriminator` described below.
Class description:
A Discriminative model with an auxiliary classification task
Method signatures and docstrings:
- def __init__(self, img_shape=(3, 128, 128), c_dim=5, n_strided=6): Parameters ---------- img_shape : tuple the shape of the input images (shou... | 1078f5030b8aac2bf022daf5fa14d66f74c3c893 | <|skeleton|>
class Discriminator:
"""A Discriminative model with an auxiliary classification task"""
def __init__(self, img_shape=(3, 128, 128), c_dim=5, n_strided=6):
"""Parameters ---------- img_shape : tuple the shape of the input images (should include the channels and exclude the batch dimension) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Discriminator:
"""A Discriminative model with an auxiliary classification task"""
def __init__(self, img_shape=(3, 128, 128), c_dim=5, n_strided=6):
"""Parameters ---------- img_shape : tuple the shape of the input images (should include the channels and exclude the batch dimension) c_dim : int t... | the_stack_v2_python_sparse | dlutils/models/gans/star/models.py | justusschock/dl-utils | train | 15 |
30497cd61ffc7f4cb05e1627c2f22a3cfbeda795 | [
"match_pattern = '{{0: <{}}} from {{1}}'.format(longest_match_len - 1)\nmatches = sorted((match for match in matches))\nsession.write_line()\nwith use_ipopo(context) as ipopo:\n for factory_name in matches:\n factory_name = factory_name.strip()\n bnd = ipopo.get_factory_bundle(factory_name)\n ... | <|body_start_0|>
match_pattern = '{{0: <{}}} from {{1}}'.format(longest_match_len - 1)
matches = sorted((match for match in matches))
session.write_line()
with use_ipopo(context) as ipopo:
for factory_name in matches:
factory_name = factory_name.strip()
... | Completes an iPOPO Component factory name | ComponentFactoryCompleter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentFactoryCompleter:
"""Completes an iPOPO Component factory name"""
def display_hook(prompt, session, context, matches, longest_match_len):
"""Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell sessi... | stack_v2_sparse_classes_36k_train_020053 | 10,339 | permissive | [
{
"docstring": "Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the larges... | 2 | null | Implement the Python class `ComponentFactoryCompleter` described below.
Class description:
Completes an iPOPO Component factory name
Method signatures and docstrings:
- def display_hook(prompt, session, context, matches, longest_match_len): Displays the available services matches and the service details :param prompt... | Implement the Python class `ComponentFactoryCompleter` described below.
Class description:
Completes an iPOPO Component factory name
Method signatures and docstrings:
- def display_hook(prompt, session, context, matches, longest_match_len): Displays the available services matches and the service details :param prompt... | 1d0add361ca219da8fdf72bb9ba8cb0ade01ad2f | <|skeleton|>
class ComponentFactoryCompleter:
"""Completes an iPOPO Component factory name"""
def display_hook(prompt, session, context, matches, longest_match_len):
"""Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell sessi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComponentFactoryCompleter:
"""Completes an iPOPO Component factory name"""
def display_hook(prompt, session, context, matches, longest_match_len):
"""Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for displ... | the_stack_v2_python_sparse | pelix/shell/completion/ipopo.py | tcalmant/ipopo | train | 67 |
9dff19832ffc2e73d7da91c593a43dbae11123fd | [
"super(LSTMAttention, self).__init__()\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.batch_first = batch_first\nself.lstm_cell = nn.LSTMCell(input_size, hidden_size)\nif attn_type == 'soft':\n self.attention_layer = SoftDotAttention(hidden_size)\nelif attn_type == 'mlp':\n self.attention... | <|body_start_0|>
super(LSTMAttention, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.batch_first = batch_first
self.lstm_cell = nn.LSTMCell(input_size, hidden_size)
if attn_type == 'soft':
self.attention_layer = SoftDotAttent... | A long short-term memory (LSTM) cell with attention. | LSTMAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMAttention:
"""A long short-term memory (LSTM) cell with attention."""
def __init__(self, input_size, hidden_size, batch_first=True, attn_type='soft'):
"""Initialize params."""
<|body_0|>
def forward(self, input, hidden, ctx, ctx_mask=None, return_logattn=False):
... | stack_v2_sparse_classes_36k_train_020054 | 8,483 | permissive | [
{
"docstring": "Initialize params.",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden_size, batch_first=True, attn_type='soft')"
},
{
"docstring": "Propagate input through the network.",
"name": "forward",
"signature": "def forward(self, input, hidden, ctx, ctx_mas... | 2 | stack_v2_sparse_classes_30k_train_012182 | Implement the Python class `LSTMAttention` described below.
Class description:
A long short-term memory (LSTM) cell with attention.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, batch_first=True, attn_type='soft'): Initialize params.
- def forward(self, input, hidden, ctx, ctx_mask=N... | Implement the Python class `LSTMAttention` described below.
Class description:
A long short-term memory (LSTM) cell with attention.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, batch_first=True, attn_type='soft'): Initialize params.
- def forward(self, input, hidden, ctx, ctx_mask=N... | c530c9af647d521262b56b717bcc38b0cfc5f1b8 | <|skeleton|>
class LSTMAttention:
"""A long short-term memory (LSTM) cell with attention."""
def __init__(self, input_size, hidden_size, batch_first=True, attn_type='soft'):
"""Initialize params."""
<|body_0|>
def forward(self, input, hidden, ctx, ctx_mask=None, return_logattn=False):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTMAttention:
"""A long short-term memory (LSTM) cell with attention."""
def __init__(self, input_size, hidden_size, batch_first=True, attn_type='soft'):
"""Initialize params."""
super(LSTMAttention, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_... | the_stack_v2_python_sparse | stanza/models/common/seq2seq_modules.py | stanfordnlp/stanza | train | 4,281 |
ead3177246d2c42e92f5d2830552894fdc49e386 | [
"self.u_href = u_href\nself.h_ref = h_ref\nself.z_0 = z_0\nself.mask = mask\narray_sizes = [np.size(u_href), np.size(h_ref), np.size(z_0), np.size(mask)]\nif not all((x == array_sizes[0] for x in array_sizes)):\n raise ValueError('Different size input arrays u_href, h_ref, z_0, mask')",
"ustar = np.full(self.u... | <|body_start_0|>
self.u_href = u_href
self.h_ref = h_ref
self.z_0 = z_0
self.mask = mask
array_sizes = [np.size(u_href), np.size(h_ref), np.size(z_0), np.size(mask)]
if not all((x == array_sizes[0] for x in array_sizes)):
raise ValueError('Different size input... | Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0. | FrictionVelocity | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrictionVelocity:
"""Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0."""
def __init__(self, u_href: ndarray, h_ref: ndarray, ... | stack_v2_sparse_classes_36k_train_020055 | 37,222 | permissive | [
{
"docstring": "Initialise the class. Args: u_href: A 2D array of float32 for the wind speed at h_ref h_ref: A 2D array of float32 for the reference heights z_0: A 2D array of float32 for the vegetative roughness lengths mask: A 2D array of booleans where True indicates calculate u* Notes: * z_0 and h_ref need ... | 2 | stack_v2_sparse_classes_30k_train_021247 | Implement the Python class `FrictionVelocity` described below.
Class description:
Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0.
Method signatures an... | Implement the Python class `FrictionVelocity` described below.
Class description:
Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0.
Method signatures an... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class FrictionVelocity:
"""Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0."""
def __init__(self, u_href: ndarray, h_ref: ndarray, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrictionVelocity:
"""Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0."""
def __init__(self, u_href: ndarray, h_ref: ndarray, z_0: ndarray,... | the_stack_v2_python_sparse | improver/wind_calculations/wind_downscaling.py | metoppv/improver | train | 101 |
2b9a9ee0b49fb000be15190543892ac2ed410413 | [
"super(TrajLoss, self).__init__()\nself.use_variance = use_variance\nself.cls_loss_weight = cls_loss_weight\nself.nll_loss_weight = nll_loss_weight\nself.loss_weight_minade = loss_weight_minade\nself.loss_weight_minfde = loss_weight_minfde",
"traj = traj_preds\nlog_probs = traj_prob\ntraj_gt = gt_future_traj\nbat... | <|body_start_0|>
super(TrajLoss, self).__init__()
self.use_variance = use_variance
self.cls_loss_weight = cls_loss_weight
self.nll_loss_weight = nll_loss_weight
self.loss_weight_minade = loss_weight_minade
self.loss_weight_minfde = loss_weight_minfde
<|end_body_0|>
<|bod... | MTP loss modified to include variances. Uses MSE for mode selection. Can also be used with Multipath outputs, with residuals added to anchors. | TrajLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrajLoss:
"""MTP loss modified to include variances. Uses MSE for mode selection. Can also be used with Multipath outputs, with residuals added to anchors."""
def __init__(self, use_variance=False, cls_loss_weight=1.0, nll_loss_weight=1.0, loss_weight_minade=0.0, loss_weight_minfde=1.0, loss... | stack_v2_sparse_classes_36k_train_020056 | 8,891 | permissive | [
{
"docstring": "Initialize MTP loss :param args: Dictionary with the following (optional) keys use_variance: bool, whether or not to use variances for computing regression component of loss, default: False alpha: float, relative weight assigned to classification component, compared to regression component of lo... | 2 | stack_v2_sparse_classes_30k_train_012776 | Implement the Python class `TrajLoss` described below.
Class description:
MTP loss modified to include variances. Uses MSE for mode selection. Can also be used with Multipath outputs, with residuals added to anchors.
Method signatures and docstrings:
- def __init__(self, use_variance=False, cls_loss_weight=1.0, nll_l... | Implement the Python class `TrajLoss` described below.
Class description:
MTP loss modified to include variances. Uses MSE for mode selection. Can also be used with Multipath outputs, with residuals added to anchors.
Method signatures and docstrings:
- def __init__(self, use_variance=False, cls_loss_weight=1.0, nll_l... | 2f38ff1357d3956af11c5609d5275db56c559c20 | <|skeleton|>
class TrajLoss:
"""MTP loss modified to include variances. Uses MSE for mode selection. Can also be used with Multipath outputs, with residuals added to anchors."""
def __init__(self, use_variance=False, cls_loss_weight=1.0, nll_loss_weight=1.0, loss_weight_minade=0.0, loss_weight_minfde=1.0, loss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrajLoss:
"""MTP loss modified to include variances. Uses MSE for mode selection. Can also be used with Multipath outputs, with residuals added to anchors."""
def __init__(self, use_variance=False, cls_loss_weight=1.0, nll_loss_weight=1.0, loss_weight_minade=0.0, loss_weight_minfde=1.0, loss_weight_mr=1.... | the_stack_v2_python_sparse | projects/mmdet3d_plugin/losses/traj_loss.py | OpenDriveLab/UniAD | train | 2,156 |
3aa288bcb6ff8ca58a13eb63fec9961fb2fe910e | [
"prog = sf.Program(1)\nG = G(A)\nwith prog.context:\n G | 0\n G.H | 0\nprog.optimize()\nassert len(prog) == 0",
"prog = sf.Program(1)\nG1 = G(A)\nG2 = G(-A)\nwith prog.context:\n G1 | 0\n G2 | 0\nprog.optimize()\nassert len(prog) == 0",
"prog = sf.Program(3)\nwith prog.context:\n for G in permute... | <|body_start_0|>
prog = sf.Program(1)
G = G(A)
with prog.context:
G | 0
G.H | 0
prog.optimize()
assert len(prog) == 0
<|end_body_0|>
<|body_start_1|>
prog = sf.Program(1)
G1 = G(A)
G2 = G(-A)
with prog.context:
... | Tests for the Program optimizer | TestOptimizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOptimizer:
"""Tests for the Program optimizer"""
def test_merge_dagger(self, G):
"""Optimizer merging single-mode gates with their daggered versions."""
<|body_0|>
def test_merge_negated(self, G):
"""Optimizer merging single-mode gates with their negated vers... | stack_v2_sparse_classes_36k_train_020057 | 19,472 | permissive | [
{
"docstring": "Optimizer merging single-mode gates with their daggered versions.",
"name": "test_merge_dagger",
"signature": "def test_merge_dagger(self, G)"
},
{
"docstring": "Optimizer merging single-mode gates with their negated versions.",
"name": "test_merge_negated",
"signature": ... | 6 | null | Implement the Python class `TestOptimizer` described below.
Class description:
Tests for the Program optimizer
Method signatures and docstrings:
- def test_merge_dagger(self, G): Optimizer merging single-mode gates with their daggered versions.
- def test_merge_negated(self, G): Optimizer merging single-mode gates wi... | Implement the Python class `TestOptimizer` described below.
Class description:
Tests for the Program optimizer
Method signatures and docstrings:
- def test_merge_dagger(self, G): Optimizer merging single-mode gates with their daggered versions.
- def test_merge_negated(self, G): Optimizer merging single-mode gates wi... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class TestOptimizer:
"""Tests for the Program optimizer"""
def test_merge_dagger(self, G):
"""Optimizer merging single-mode gates with their daggered versions."""
<|body_0|>
def test_merge_negated(self, G):
"""Optimizer merging single-mode gates with their negated vers... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestOptimizer:
"""Tests for the Program optimizer"""
def test_merge_dagger(self, G):
"""Optimizer merging single-mode gates with their daggered versions."""
prog = sf.Program(1)
G = G(A)
with prog.context:
G | 0
G.H | 0
prog.optimize()
... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_backup/strawberryfields/strawberryfields#90/after/test_program.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
ffab28c7146255e16c435e134be71713068f8968 | [
"user = User.query.filter(User.email == g.user.email).first()\nif not user:\n return abort(401, 'token is not valid')\nreturn jsonify(dict(success=True, token=user.getToken(), data=user.to_json()))",
"args = UserParser.parse_args()\nuser = User.query.filter(User.email == g.user.email).first()\nif not user:\n ... | <|body_start_0|>
user = User.query.filter(User.email == g.user.email).first()
if not user:
return abort(401, 'token is not valid')
return jsonify(dict(success=True, token=user.getToken(), data=user.to_json()))
<|end_body_0|>
<|body_start_1|>
args = UserParser.parse_args()
... | GetMe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetMe:
def get(self):
"""get me info"""
<|body_0|>
def put(self):
"""update user settings"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = User.query.filter(User.email == g.user.email).first()
if not user:
return abort(401,... | stack_v2_sparse_classes_36k_train_020058 | 9,160 | no_license | [
{
"docstring": "get me info",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "update user settings",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010838 | Implement the Python class `GetMe` described below.
Class description:
Implement the GetMe class.
Method signatures and docstrings:
- def get(self): get me info
- def put(self): update user settings | Implement the Python class `GetMe` described below.
Class description:
Implement the GetMe class.
Method signatures and docstrings:
- def get(self): get me info
- def put(self): update user settings
<|skeleton|>
class GetMe:
def get(self):
"""get me info"""
<|body_0|>
def put(self):
... | 1c7d812e214590e0f4759e6c5be411bd64f8e3c4 | <|skeleton|>
class GetMe:
def get(self):
"""get me info"""
<|body_0|>
def put(self):
"""update user settings"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetMe:
def get(self):
"""get me info"""
user = User.query.filter(User.email == g.user.email).first()
if not user:
return abort(401, 'token is not valid')
return jsonify(dict(success=True, token=user.getToken(), data=user.to_json()))
def put(self):
"""up... | the_stack_v2_python_sparse | apis/auth.py | ajutor-app/backend | train | 0 | |
c3b402ab320a620a5e212fab6370f331aaf11275 | [
"m, n, p = (len(s1), len(s2), len(s3))\nif m + n != p:\n return False\ndp = [[False for j in range(n + 1)] for i in range(m + 1)]\ndp[0][0] = True\nfor j in range(1, n + 1):\n dp[0][j] = dp[0][j - 1] and s3[j - 1] == s2[j - 1]\nfor i in range(1, m + 1):\n dp[i][0] = dp[i - 1][0] and s3[i - 1] == s1[i - 1]\... | <|body_start_0|>
m, n, p = (len(s1), len(s2), len(s3))
if m + n != p:
return False
dp = [[False for j in range(n + 1)] for i in range(m + 1)]
dp[0][0] = True
for j in range(1, n + 1):
dp[0][j] = dp[0][j - 1] and s3[j - 1] == s2[j - 1]
for i in rang... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_0|>
def isInterleave2(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_020059 | 3,558 | no_license | [
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool",
"name": "isInterleave",
"signature": "def isInterleave(self, s1, s2, s3)"
},
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool",
"name": "isInterleave2",
"signature": "def isInterleave2(self, s1... | 2 | stack_v2_sparse_classes_30k_train_007877 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool
- def isInterleave2(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool
- def isInterleave2(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_0|>
def isInterleave2(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
m, n, p = (len(s1), len(s2), len(s3))
if m + n != p:
return False
dp = [[False for j in range(n + 1)] for i in range(m + 1)]
dp[0][0] = True
fo... | the_stack_v2_python_sparse | code97InterleavingString.py | cybelewang/leetcode-python | train | 0 | |
f5f0966e6a5072378b68d6c5cf544f63a355dc2c | [
"super(Span_Pos_CLS, self).__init__()\nself.sequence_encoder = sequence_encoder\nself.num_labels = len(tag2id)\nself.tag2id = tag2id\nself.id2tag = {}\nfor tag, tid in tag2id.items():\n self.id2tag[tid] = tag\nif use_lstm:\n self.bilstm = nn.LSTM(input_size=sequence_encoder.hidden_size, hidden_size=sequence_e... | <|body_start_0|>
super(Span_Pos_CLS, self).__init__()
self.sequence_encoder = sequence_encoder
self.num_labels = len(tag2id)
self.tag2id = tag2id
self.id2tag = {}
for tag, tid in tag2id.items():
self.id2tag[tid] = tag
if use_lstm:
self.bils... | Span_Pos_CLS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Span_Pos_CLS:
def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, dropout_rate=0.1):
"""Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. Defaults to False. compress_se... | stack_v2_sparse_classes_36k_train_020060 | 14,475 | permissive | [
{
"docstring": "Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. Defaults to False. compress_seq (bool, optional): whether compress sequence for lstm. Defaults to True. soft_label (bool, optional): use one hot if soft_la... | 3 | stack_v2_sparse_classes_30k_train_000155 | Implement the Python class `Span_Pos_CLS` described below.
Class description:
Implement the Span_Pos_CLS class.
Method signatures and docstrings:
- def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, dropout_rate=0.1): Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict):... | Implement the Python class `Span_Pos_CLS` described below.
Class description:
Implement the Span_Pos_CLS class.
Method signatures and docstrings:
- def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, dropout_rate=0.1): Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict):... | b4c049fd30db39b67984edfadc49b4354d52be83 | <|skeleton|>
class Span_Pos_CLS:
def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, dropout_rate=0.1):
"""Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. Defaults to False. compress_se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Span_Pos_CLS:
def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, dropout_rate=0.1):
"""Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. Defaults to False. compress_seq (bool, optio... | the_stack_v2_python_sparse | pasaie/pasaner/model/span_cls.py | tracy-talent/AIPolicy | train | 0 | |
0f1c311df19463008dff8dbea2803aacd7a5aa03 | [
"def cb(n):\n if n == 1 or n == 0:\n return 1\n else:\n return cb(n - 1) + cb(n - 2)\nreturn cb(n)",
"use = {0: 1, 1: 1}\n\ndef cb(n, use):\n if n in use.keys():\n return use[n]\n else:\n rst = cb(n - 1, use) + cb(n - 2, use)\n use[n] = rst\n return use[n]\nre... | <|body_start_0|>
def cb(n):
if n == 1 or n == 0:
return 1
else:
return cb(n - 1) + cb(n - 2)
return cb(n)
<|end_body_0|>
<|body_start_1|>
use = {0: 1, 1: 1}
def cb(n, use):
if n in use.keys():
return us... | 假设你正在爬楼梯。需要n阶你才能到达楼顶。 每次你可以爬1或2个台阶。 你有多少种不同的方法可以爬到楼顶呢? 注意:给定n是一个正整数。 实例1: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""假设你正在爬楼梯。需要n阶你才能到达楼顶。 每次你可以爬1或2个台阶。 你有多少种不同的方法可以爬到楼顶呢? 注意:给定n是一个正整数。 实例1: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶"""
def climbStairs(self, n: int) -> int:
"""斐波那契数列 :param n: :return:"""
<|body_0|>
def climbStairs_1(self, n,... | stack_v2_sparse_classes_36k_train_020061 | 1,524 | no_license | [
{
"docstring": "斐波那契数列 :param n: :return:",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
},
{
"docstring": "记忆化递归 :param n:输入阶梯数 :param use: 已计算过的值 :return:",
"name": "climbStairs_1",
"signature": "def climbStairs_1(self, n, use)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009517 | Implement the Python class `Solution` described below.
Class description:
假设你正在爬楼梯。需要n阶你才能到达楼顶。 每次你可以爬1或2个台阶。 你有多少种不同的方法可以爬到楼顶呢? 注意:给定n是一个正整数。 实例1: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: 斐波那契数列 :param n: :retu... | Implement the Python class `Solution` described below.
Class description:
假设你正在爬楼梯。需要n阶你才能到达楼顶。 每次你可以爬1或2个台阶。 你有多少种不同的方法可以爬到楼顶呢? 注意:给定n是一个正整数。 实例1: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: 斐波那契数列 :param n: :retu... | de86b04b1f874c50613c33e969ec7a7590cceaff | <|skeleton|>
class Solution:
"""假设你正在爬楼梯。需要n阶你才能到达楼顶。 每次你可以爬1或2个台阶。 你有多少种不同的方法可以爬到楼顶呢? 注意:给定n是一个正整数。 实例1: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶"""
def climbStairs(self, n: int) -> int:
"""斐波那契数列 :param n: :return:"""
<|body_0|>
def climbStairs_1(self, n,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""假设你正在爬楼梯。需要n阶你才能到达楼顶。 每次你可以爬1或2个台阶。 你有多少种不同的方法可以爬到楼顶呢? 注意:给定n是一个正整数。 实例1: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶"""
def climbStairs(self, n: int) -> int:
"""斐波那契数列 :param n: :return:"""
def cb(n):
if n == 1 or n == 0:
... | the_stack_v2_python_sparse | m70_Easy_ClimbingStairs.py | CGump/leetcode-everyday | train | 0 |
8f26a9ef79dcaee617d46a6bc01391edee27c226 | [
"oauth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&{1}&response_type=code&scope={2}&state={3}#wechat_redirect'\nredirect_param = parse.urlencode({'redirect_uri': redirect_uri})\nurl = oauth_url.format(self.app_id, redirect_param, scope, state)\nreturn url",
"oauth_token_url = 'https://api... | <|body_start_0|>
oauth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&{1}&response_type=code&scope={2}&state={3}#wechat_redirect'
redirect_param = parse.urlencode({'redirect_uri': redirect_uri})
url = oauth_url.format(self.app_id, redirect_param, scope, state)
retur... | WxOAuthManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WxOAuthManager:
def oauth_url(self, redirect_uri, state=None, scope='snsapi_base'):
"""微信认证网址"""
<|body_0|>
def oauth_openid(self, code):
"""获取用户的openid"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
oauth_url = 'https://open.weixin.qq.com/connect/... | stack_v2_sparse_classes_36k_train_020062 | 1,034 | no_license | [
{
"docstring": "微信认证网址",
"name": "oauth_url",
"signature": "def oauth_url(self, redirect_uri, state=None, scope='snsapi_base')"
},
{
"docstring": "获取用户的openid",
"name": "oauth_openid",
"signature": "def oauth_openid(self, code)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003811 | Implement the Python class `WxOAuthManager` described below.
Class description:
Implement the WxOAuthManager class.
Method signatures and docstrings:
- def oauth_url(self, redirect_uri, state=None, scope='snsapi_base'): 微信认证网址
- def oauth_openid(self, code): 获取用户的openid | Implement the Python class `WxOAuthManager` described below.
Class description:
Implement the WxOAuthManager class.
Method signatures and docstrings:
- def oauth_url(self, redirect_uri, state=None, scope='snsapi_base'): 微信认证网址
- def oauth_openid(self, code): 获取用户的openid
<|skeleton|>
class WxOAuthManager:
def oa... | 7316880e2444a8af02e2f44af38dd7ae708ccbb6 | <|skeleton|>
class WxOAuthManager:
def oauth_url(self, redirect_uri, state=None, scope='snsapi_base'):
"""微信认证网址"""
<|body_0|>
def oauth_openid(self, code):
"""获取用户的openid"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WxOAuthManager:
def oauth_url(self, redirect_uri, state=None, scope='snsapi_base'):
"""微信认证网址"""
oauth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&{1}&response_type=code&scope={2}&state={3}#wechat_redirect'
redirect_param = parse.urlencode({'redirect_uri': redi... | the_stack_v2_python_sparse | web_flask/weixin/oauth.py | aiportal/zb123 | train | 0 | |
8c79dce2d61b8774568e31abf9e6151247e43208 | [
"self.x = cam_pos[0]\nself.y = cam_pos[1]\nself.z = cam_pos[2]\nself.xdir = cam_dir[0]\nself.ydir = cam_dir[1]\nself.zdir = cam_dir[2]\nself.xup = cam_up[0]\nself.yup = cam_up[1]\nself.zup = cam_up[2]\nself.u3_camera = np.array([self.xdir, self.ydir, self.zdir])\nself.u2_camera = np.array([self.xup, self.yup, self.... | <|body_start_0|>
self.x = cam_pos[0]
self.y = cam_pos[1]
self.z = cam_pos[2]
self.xdir = cam_dir[0]
self.ydir = cam_dir[1]
self.zdir = cam_dir[2]
self.xup = cam_up[0]
self.yup = cam_up[1]
self.zup = cam_up[2]
self.u3_camera = np.array([self... | Camera | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Camera:
def __init__(self, cam_pos, cam_dir, cam_up):
""":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction consider... | stack_v2_sparse_classes_36k_train_020063 | 17,705 | permissive | [
{
"docstring": ":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction considered up for the camera, in cartesian coordinates :return: set the v... | 4 | stack_v2_sparse_classes_30k_train_006751 | Implement the Python class `Camera` described below.
Class description:
Implement the Camera class.
Method signatures and docstrings:
- def __init__(self, cam_pos, cam_dir, cam_up): :param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the c... | Implement the Python class `Camera` described below.
Class description:
Implement the Camera class.
Method signatures and docstrings:
- def __init__(self, cam_pos, cam_dir, cam_up): :param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the c... | 5c76276ff658582061dbdf10cadee7cfc3940526 | <|skeleton|>
class Camera:
def __init__(self, cam_pos, cam_dir, cam_up):
""":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction consider... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Camera:
def __init__(self, cam_pos, cam_dir, cam_up):
""":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction considered up for the ... | the_stack_v2_python_sparse | translate_coordinates.py | gsnyder206/mock-surveys | train | 7 | |
a3791a17b18ff05cb6db872be03e904578063431 | [
"self.minNumberOfDecimalPlaces = minNumberOfDecimalPlaces\nself.maxNumberOfDecimalPlaces = maxNumberOfDecimalPlaces\nself.__inRangeValidator = IsInRange()",
"value = _toDecimal(value)\ntupleRepr = value.as_tuple()\nif tupleRepr[2] >= 0:\n decimalPlaces = 0\nelse:\n absolutExponent = abs(tupleRepr[2])\n p... | <|body_start_0|>
self.minNumberOfDecimalPlaces = minNumberOfDecimalPlaces
self.maxNumberOfDecimalPlaces = maxNumberOfDecimalPlaces
self.__inRangeValidator = IsInRange()
<|end_body_0|>
<|body_start_1|>
value = _toDecimal(value)
tupleRepr = value.as_tuple()
if tupleRepr[2]... | Checks whether the number of decimal places which was specified is in a specific range. | IsNumberOfDecimalPlacesInRange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsNumberOfDecimalPlacesInRange:
"""Checks whether the number of decimal places which was specified is in a specific range."""
def __init__(self, minNumberOfDecimalPlaces=None, maxNumberOfDecimalPlaces=None):
"""@param minNumberOfDecimalPlaces: The lower bound. @type minNumberOfDecima... | stack_v2_sparse_classes_36k_train_020064 | 13,874 | no_license | [
{
"docstring": "@param minNumberOfDecimalPlaces: The lower bound. @type minNumberOfDecimalPlaces: C{int} @param maxNumberOfDecimalPlaces: The upper bound. @type maxNumberOfDecimalPlaces: C{int}",
"name": "__init__",
"signature": "def __init__(self, minNumberOfDecimalPlaces=None, maxNumberOfDecimalPlaces... | 2 | null | Implement the Python class `IsNumberOfDecimalPlacesInRange` described below.
Class description:
Checks whether the number of decimal places which was specified is in a specific range.
Method signatures and docstrings:
- def __init__(self, minNumberOfDecimalPlaces=None, maxNumberOfDecimalPlaces=None): @param minNumber... | Implement the Python class `IsNumberOfDecimalPlacesInRange` described below.
Class description:
Checks whether the number of decimal places which was specified is in a specific range.
Method signatures and docstrings:
- def __init__(self, minNumberOfDecimalPlaces=None, maxNumberOfDecimalPlaces=None): @param minNumber... | 958fda4f3064f9f6b2034da396a20ac9d9abd52f | <|skeleton|>
class IsNumberOfDecimalPlacesInRange:
"""Checks whether the number of decimal places which was specified is in a specific range."""
def __init__(self, minNumberOfDecimalPlaces=None, maxNumberOfDecimalPlaces=None):
"""@param minNumberOfDecimalPlaces: The lower bound. @type minNumberOfDecima... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsNumberOfDecimalPlacesInRange:
"""Checks whether the number of decimal places which was specified is in a specific range."""
def __init__(self, minNumberOfDecimalPlaces=None, maxNumberOfDecimalPlaces=None):
"""@param minNumberOfDecimalPlaces: The lower bound. @type minNumberOfDecimalPlaces: C{in... | the_stack_v2_python_sparse | src/datafinder/core/configuration/properties/validators/base_validators.py | DLR-SC/DataFinder | train | 9 |
8483d5a94d70326dd20ee6998d007f4ed83a4370 | [
"super().__init__(policy)\nself.repeat = repeat\nself.perturb_fn = perturb_fn\nself.limit_fraction = limit_fraction",
"batch = convert_ma_batch_to_sample_batch(batch)\nobs_batch = batch['obs']\nn_features = obs_batch.shape[-1]\nimportance = np.zeros((self.repeat, n_features))\nref_actions, _, _ = self.policy.comp... | <|body_start_0|>
super().__init__(policy)
self.repeat = repeat
self.perturb_fn = perturb_fn
self.limit_fraction = limit_fraction
<|end_body_0|>
<|body_start_1|>
batch = convert_ma_batch_to_sample_batch(batch)
obs_batch = batch['obs']
n_features = obs_batch.shape[... | FeatureImportance | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureImportance:
def __init__(self, policy: Policy, repeat: int=1, limit_fraction: float=1.0, perturb_fn: Callable[[pd.DataFrame, int], pd.DataFrame]=_perturb_df):
"""Feature importance in a model inspection technique that can be used for any fitted predictor when the data is tablular.... | stack_v2_sparse_classes_36k_train_020065 | 10,680 | permissive | [
{
"docstring": "Feature importance in a model inspection technique that can be used for any fitted predictor when the data is tablular. This implementation is also known as permutation importance that is defined to be the variation of the model's prediction when a single feature value is randomly shuffled. In R... | 3 | null | Implement the Python class `FeatureImportance` described below.
Class description:
Implement the FeatureImportance class.
Method signatures and docstrings:
- def __init__(self, policy: Policy, repeat: int=1, limit_fraction: float=1.0, perturb_fn: Callable[[pd.DataFrame, int], pd.DataFrame]=_perturb_df): Feature impor... | Implement the Python class `FeatureImportance` described below.
Class description:
Implement the FeatureImportance class.
Method signatures and docstrings:
- def __init__(self, policy: Policy, repeat: int=1, limit_fraction: float=1.0, perturb_fn: Callable[[pd.DataFrame, int], pd.DataFrame]=_perturb_df): Feature impor... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class FeatureImportance:
def __init__(self, policy: Policy, repeat: int=1, limit_fraction: float=1.0, perturb_fn: Callable[[pd.DataFrame, int], pd.DataFrame]=_perturb_df):
"""Feature importance in a model inspection technique that can be used for any fitted predictor when the data is tablular.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureImportance:
def __init__(self, policy: Policy, repeat: int=1, limit_fraction: float=1.0, perturb_fn: Callable[[pd.DataFrame, int], pd.DataFrame]=_perturb_df):
"""Feature importance in a model inspection technique that can be used for any fitted predictor when the data is tablular. This implemen... | the_stack_v2_python_sparse | rllib/offline/feature_importance.py | ray-project/ray | train | 29,482 | |
31b240656482cd043fba95c42643caa459e30ca3 | [
"self.mat = mat\nm, n = mat.shape\nif k == None or k == min(m, n):\n self.svd_type = 0\nelif k > min(m, n):\n raise Exception('k can not bigger than the number of rows and columns of mat')\nelif 0 < k < min(m, n):\n self.svd_type = 1\n self.k = k",
"eigval, eigvec = np.linalg.eig(self.mat.T @ self.mat... | <|body_start_0|>
self.mat = mat
m, n = mat.shape
if k == None or k == min(m, n):
self.svd_type = 0
elif k > min(m, n):
raise Exception('k can not bigger than the number of rows and columns of mat')
elif 0 < k < min(m, n):
self.svd_type = 1
... | svd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class svd:
def __init__(self, mat, k=None):
""":param mat: m*n matrix :param k: Int representing the number of singular values we'll keep. Default None, which means full svd."""
<|body_0|>
def decompose(self):
"""Desc: Do A = U @ M @ V"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_020066 | 1,922 | no_license | [
{
"docstring": ":param mat: m*n matrix :param k: Int representing the number of singular values we'll keep. Default None, which means full svd.",
"name": "__init__",
"signature": "def __init__(self, mat, k=None)"
},
{
"docstring": "Desc: Do A = U @ M @ V",
"name": "decompose",
"signature... | 2 | stack_v2_sparse_classes_30k_test_000678 | Implement the Python class `svd` described below.
Class description:
Implement the svd class.
Method signatures and docstrings:
- def __init__(self, mat, k=None): :param mat: m*n matrix :param k: Int representing the number of singular values we'll keep. Default None, which means full svd.
- def decompose(self): Desc... | Implement the Python class `svd` described below.
Class description:
Implement the svd class.
Method signatures and docstrings:
- def __init__(self, mat, k=None): :param mat: m*n matrix :param k: Int representing the number of singular values we'll keep. Default None, which means full svd.
- def decompose(self): Desc... | 20fa401fedb3b92cee6cae8e9f5a4f096f811b53 | <|skeleton|>
class svd:
def __init__(self, mat, k=None):
""":param mat: m*n matrix :param k: Int representing the number of singular values we'll keep. Default None, which means full svd."""
<|body_0|>
def decompose(self):
"""Desc: Do A = U @ M @ V"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class svd:
def __init__(self, mat, k=None):
""":param mat: m*n matrix :param k: Int representing the number of singular values we'll keep. Default None, which means full svd."""
self.mat = mat
m, n = mat.shape
if k == None or k == min(m, n):
self.svd_type = 0
elif... | the_stack_v2_python_sparse | core/unsupervise/svd.py | bboyGit/statsLearning | train | 6 | |
391af6a1837f5d04167b8d4cc9719901658a7d93 | [
"self.table = table\nself.player = player\nself.samples = samples",
"x, y = self.table.payout\nblackjack_payout = x / y\nfor count in range(self.samples):\n self.player.reset()\n while self.player.stake > 0 and self.player.rounds > 0:\n self.player.rounds -= 1\n outcome = random.random()\n ... | <|body_start_0|>
self.table = table
self.player = player
self.samples = samples
<|end_body_0|>
<|body_start_1|>
x, y = self.table.payout
blackjack_payout = x / y
for count in range(self.samples):
self.player.reset()
while self.player.stake > 0 and... | Simulate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulate:
def __init__(self, table: Table, player: Player, samples: int) -> None:
"""Define table, player and number of samples."""
<|body_0|>
def __iter__(self) -> Iterator[Tuple]:
"""Yield statistical samples."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_020067 | 3,541 | permissive | [
{
"docstring": "Define table, player and number of samples.",
"name": "__init__",
"signature": "def __init__(self, table: Table, player: Player, samples: int) -> None"
},
{
"docstring": "Yield statistical samples.",
"name": "__iter__",
"signature": "def __iter__(self) -> Iterator[Tuple]"... | 2 | stack_v2_sparse_classes_30k_val_000908 | Implement the Python class `Simulate` described below.
Class description:
Implement the Simulate class.
Method signatures and docstrings:
- def __init__(self, table: Table, player: Player, samples: int) -> None: Define table, player and number of samples.
- def __iter__(self) -> Iterator[Tuple]: Yield statistical sam... | Implement the Python class `Simulate` described below.
Class description:
Implement the Simulate class.
Method signatures and docstrings:
- def __init__(self, table: Table, player: Player, samples: int) -> None: Define table, player and number of samples.
- def __iter__(self) -> Iterator[Tuple]: Yield statistical sam... | f6d6517952d51e75c5e086f4c19d1e52500cf261 | <|skeleton|>
class Simulate:
def __init__(self, table: Table, player: Player, samples: int) -> None:
"""Define table, player and number of samples."""
<|body_0|>
def __iter__(self) -> Iterator[Tuple]:
"""Yield statistical samples."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulate:
def __init__(self, table: Table, player: Player, samples: int) -> None:
"""Define table, player and number of samples."""
self.table = table
self.player = player
self.samples = samples
def __iter__(self) -> Iterator[Tuple]:
"""Yield statistical samples.""... | the_stack_v2_python_sparse | Chapter_13/simulation_model.py | PacktPublishing/Mastering-Object-Oriented-Python-Second-Edition | train | 139 | |
7dd1822b730aa7c21e28c2e2f5266bb296329369 | [
"self.max_len = min(trace_len, max_evaluations)\nself.iteration = []\nself.fitness = []\nself.next_iteration = 0\nif self.max_len > 0:\n self.interval = max_evaluations // self.max_len",
"if self.max_len > 0:\n if iteration >= self.next_iteration:\n self.fitness.append(fitness)\n self.iteratio... | <|body_start_0|>
self.max_len = min(trace_len, max_evaluations)
self.iteration = []
self.fitness = []
self.next_iteration = 0
if self.max_len > 0:
self.interval = max_evaluations // self.max_len
<|end_body_0|>
<|body_start_1|>
if self.max_len > 0:
... | 记录不同iteration对应的fitness | FitnessTrace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be perform... | stack_v2_sparse_classes_36k_train_020068 | 3,090 | no_license | [
{
"docstring": "Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be performed. :return: Object instance.",
"name": "__init__",
"signature": "def __init__(self, trace_len, max... | 2 | stack_v2_sparse_classes_30k_train_006774 | Implement the Python class `FitnessTrace` described below.
Class description:
记录不同iteration对应的fitness
Method signatures and docstrings:
- def __init__(self, trace_len, max_evaluations): Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluation... | Implement the Python class `FitnessTrace` described below.
Class description:
记录不同iteration对应的fitness
Method signatures and docstrings:
- def __init__(self, trace_len, max_evaluations): Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluation... | 1157e5abc004af624f182879105f9284f97ef08c | <|skeleton|>
class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be perform... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be performed. :return: ... | the_stack_v2_python_sparse | Programme/python/two qubit gate/CZgate/IBM/Qubits module/swarmops/FitnessTrace.py | ChenZha/Quantum-Computation | train | 6 |
e3dd8f8cf6f5e1cce2b5f45f08d0a82f47b824c4 | [
"i, j = (0, len(nums) - 1)\nnums.sort()\nres = 0\nwhile i < j:\n res += nums[j] - nums[i]\n i += 1\n j -= 1\nreturn res",
"if not nums:\n return 0\nsum_ = sum(nums)\nif sum_ < 0:\n base = -int(-sum_ / len(nums) + 0.5)\nelse:\n base = int(sum_ / len(nums) + 0.5)\nres = 0\nfor num in nums:\n re... | <|body_start_0|>
i, j = (0, len(nums) - 1)
nums.sort()
res = 0
while i < j:
res += nums[j] - nums[i]
i += 1
j -= 1
return res
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
sum_ = sum(nums)
if sum_ < ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMoves2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def minMoves2_wrong(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i, j = (0, len(nums) - 1)
nums.sort... | stack_v2_sparse_classes_36k_train_020069 | 1,756 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "minMoves2",
"signature": "def minMoves2(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "minMoves2_wrong",
"signature": "def minMoves2_wrong(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMoves2(self, nums): :type nums: List[int] :rtype: int
- def minMoves2_wrong(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMoves2(self, nums): :type nums: List[int] :rtype: int
- def minMoves2_wrong(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def minMoves2... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def minMoves2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def minMoves2_wrong(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minMoves2(self, nums):
""":type nums: List[int] :rtype: int"""
i, j = (0, len(nums) - 1)
nums.sort()
res = 0
while i < j:
res += nums[j] - nums[i]
i += 1
j -= 1
return res
def minMoves2_wrong(self, nums):
... | the_stack_v2_python_sparse | code462MinimumMovesToEqualArrayElementsII.py | cybelewang/leetcode-python | train | 0 | |
93d687b7ec9a79d1c8525ceabb979b9dbe821a05 | [
"self.file_name = ''\nself.urls = []\nself.rev = None\nself.hashes = {}\nself.acl = []\nself._metadata = {}\nself.size = None\nself.merge_indexd()",
"urls = []\nfor url in self.urls:\n if url.startswith('s3://'):\n url = f\"{current_app.config['GEN3_URL']}/data/{self.latest_did}\"\n urls.append(url)\... | <|body_start_0|>
self.file_name = ''
self.urls = []
self.rev = None
self.hashes = {}
self.acl = []
self._metadata = {}
self.size = None
self.merge_indexd()
<|end_body_0|>
<|body_start_1|>
urls = []
for url in self.urls:
if url.... | Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the file, a response containing a did (dig... | IndexdFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexdFile:
"""Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the ... | stack_v2_sparse_classes_36k_train_020070 | 7,013 | permissive | [
{
"docstring": "Builds the object by initializing properties and updating them from indexd.",
"name": "constructor",
"signature": "def constructor(self)"
},
{
"docstring": "Access urls should contain only links out to gen3 data endpoints that are used to download the files themselves. For urls t... | 3 | stack_v2_sparse_classes_30k_train_006671 | Implement the Python class `IndexdFile` described below.
Class description:
Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the se... | Implement the Python class `IndexdFile` described below.
Class description:
Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the se... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class IndexdFile:
"""Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexdFile:
"""Field reflection for objects that are stored in indexd # Creation When an indexd file is created, an instance of the orm model here is created, and when persisted to the database, a request is sent to Gen3 indexd to register the file in the service. Upon successful registry of the file, a respo... | the_stack_v2_python_sparse | dataservice/api/common/model.py | kids-first/kf-api-dataservice | train | 9 |
f60161dbc8cc60e950011e1ffbae2a3862de4e0d | [
"self.nums = nums\nself.cacheRange = defaultdict(dict)\nself.cacheRange[0] = nums\nmaxStep = len(str(len(nums)))\nfor i in range(1, maxStep):\n span = 10 ** i\n preSpan = 10 ** (i - 1)\n for j in range(0, len(nums), span):\n self.cacheRange[i][j] = 0\n for k in range(j, j + span, preSpan):\n ... | <|body_start_0|>
self.nums = nums
self.cacheRange = defaultdict(dict)
self.cacheRange[0] = nums
maxStep = len(str(len(nums)))
for i in range(1, maxStep):
span = 10 ** i
preSpan = 10 ** (i - 1)
for j in range(0, len(nums), span):
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_020071 | 1,453 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, ... | 2 | stack_v2_sparse_classes_30k_train_002390 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | 4eee28430754dd5187cd3f9e86a81be3f6664f46 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
self.nums = nums
self.cacheRange = defaultdict(dict)
self.cacheRange[0] = nums
maxStep = len(str(len(nums)))
for i in range(1, maxStep):
span = 10 **... | the_stack_v2_python_sparse | leetcode/python/easy/range_sum_query_immutable.py | 13leaf/exercises | train | 0 | |
3f590307c4e50d1541efba93db3325a8e347bd33 | [
"port_tags = {}\nlast_offset = 0\nport = None\nfor line in lines[1:]:\n line = line.rstrip()\n key, val = line.split(None, 1)\n offset = len(line) - len(line.lstrip())\n if port is None:\n if key.lower() == 'port':\n port = val.strip('\"')\n last_offset = offset\n ... | <|body_start_0|>
port_tags = {}
last_offset = 0
port = None
for line in lines[1:]:
line = line.rstrip()
key, val = line.split(None, 1)
offset = len(line) - len(line.lstrip())
if port is None:
if key.lower() == 'port':
... | Check that port tags aren't change after ovs-agent restart | TestPortTags | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPortTags:
"""Check that port tags aren't change after ovs-agent restart"""
def get_ports_tags_data(self, lines):
"""Returns dict with ports as keys and tags as values"""
<|body_0|>
def test_port_tags_immutable(self):
"""Check that ports tags don't change thei... | stack_v2_sparse_classes_36k_train_020072 | 41,546 | no_license | [
{
"docstring": "Returns dict with ports as keys and tags as values",
"name": "get_ports_tags_data",
"signature": "def get_ports_tags_data(self, lines)"
},
{
"docstring": "Check that ports tags don't change their values after ovs-agents restart Scenario: 1. Collect ovs-vsctl tags before test 2. D... | 2 | stack_v2_sparse_classes_30k_train_010495 | Implement the Python class `TestPortTags` described below.
Class description:
Check that port tags aren't change after ovs-agent restart
Method signatures and docstrings:
- def get_ports_tags_data(self, lines): Returns dict with ports as keys and tags as values
- def test_port_tags_immutable(self): Check that ports t... | Implement the Python class `TestPortTags` described below.
Class description:
Check that port tags aren't change after ovs-agent restart
Method signatures and docstrings:
- def get_ports_tags_data(self, lines): Returns dict with ports as keys and tags as values
- def test_port_tags_immutable(self): Check that ports t... | 8aced2855b78b5f123195d188c80e27b43888a2e | <|skeleton|>
class TestPortTags:
"""Check that port tags aren't change after ovs-agent restart"""
def get_ports_tags_data(self, lines):
"""Returns dict with ports as keys and tags as values"""
<|body_0|>
def test_port_tags_immutable(self):
"""Check that ports tags don't change thei... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPortTags:
"""Check that port tags aren't change after ovs-agent restart"""
def get_ports_tags_data(self, lines):
"""Returns dict with ports as keys and tags as values"""
port_tags = {}
last_offset = 0
port = None
for line in lines[1:]:
line = line.r... | the_stack_v2_python_sparse | mos_tests/neutron/python_tests/test_ovs_restart.py | Mirantis/mos-integration-tests | train | 16 |
8d691c210a10487c9a59ae99e732d6d4b3edd9e1 | [
"file_entry = parser_mediator.GetFileEntry()\nfile_system = file_entry.GetFileSystem()\npath_segments = file_system.SplitPath(file_entry.path_spec.location)\nreturn path_segments[-2]",
"command = None\ncontainer_configuration = self._GetJSONValue(json_dict, 'container_config')\nif container_configuration:\n co... | <|body_start_0|>
file_entry = parser_mediator.GetFileEntry()
file_system = file_entry.GetFileSystem()
path_segments = file_system.SplitPath(file_entry.path_spec.location)
return path_segments[-2]
<|end_body_0|>
<|body_start_1|>
command = None
container_configuration = se... | JSON-L parser plugin for Docker layer configuration files. This parser handles per Docker layer configuration files stored in: DOCKER_DIR/graph/<layer_identifier>/json | DockerLayerConfigurationJSONLPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DockerLayerConfigurationJSONLPlugin:
"""JSON-L parser plugin for Docker layer configuration files. This parser handles per Docker layer configuration files stored in: DOCKER_DIR/graph/<layer_identifier>/json"""
def _GetLayerIdentifierFromPath(self, parser_mediator):
"""Extracts a lay... | stack_v2_sparse_classes_36k_train_020073 | 3,407 | permissive | [
{
"docstring": "Extracts a layer (or graph) identifier from a path. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. Returns: str: layer identifier.",
"name": "_GetLayerIdentifierFromPath",
"signature": "def _GetLayerIdentifie... | 3 | stack_v2_sparse_classes_30k_train_007260 | Implement the Python class `DockerLayerConfigurationJSONLPlugin` described below.
Class description:
JSON-L parser plugin for Docker layer configuration files. This parser handles per Docker layer configuration files stored in: DOCKER_DIR/graph/<layer_identifier>/json
Method signatures and docstrings:
- def _GetLayer... | Implement the Python class `DockerLayerConfigurationJSONLPlugin` described below.
Class description:
JSON-L parser plugin for Docker layer configuration files. This parser handles per Docker layer configuration files stored in: DOCKER_DIR/graph/<layer_identifier>/json
Method signatures and docstrings:
- def _GetLayer... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class DockerLayerConfigurationJSONLPlugin:
"""JSON-L parser plugin for Docker layer configuration files. This parser handles per Docker layer configuration files stored in: DOCKER_DIR/graph/<layer_identifier>/json"""
def _GetLayerIdentifierFromPath(self, parser_mediator):
"""Extracts a lay... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DockerLayerConfigurationJSONLPlugin:
"""JSON-L parser plugin for Docker layer configuration files. This parser handles per Docker layer configuration files stored in: DOCKER_DIR/graph/<layer_identifier>/json"""
def _GetLayerIdentifierFromPath(self, parser_mediator):
"""Extracts a layer (or graph)... | the_stack_v2_python_sparse | plaso/parsers/jsonl_plugins/docker_layer_config.py | log2timeline/plaso | train | 1,506 |
dd23d9f9d7b74cc7d386071996172e58d533b47c | [
"length = len(nums)\nfor i in range(length):\n for j in range(i + 1, length):\n if nums[j] == target - nums[i]:\n return [i, j]",
"length, values = (len(nums), {})\nfor i in range(length):\n values[nums[i]] = i\nfor i in range(length):\n complement = target - nums[i]\n if complement ... | <|body_start_0|>
length = len(nums)
for i in range(length):
for j in range(i + 1, length):
if nums[j] == target - nums[i]:
return [i, j]
<|end_body_0|>
<|body_start_1|>
length, values = (len(nums), {})
for i in range(length):
v... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum1(self, nums: List[int], target: int) -> List[int]:
"""暴力枚举"""
<|body_0|>
def twoSum2(self, nums: List[int], target: int) -> List[int]:
"""双通道哈希表"""
<|body_1|>
def twoSum3(self, nums: List[int], target: int) -> List[int]:
"""单... | stack_v2_sparse_classes_36k_train_020074 | 1,307 | no_license | [
{
"docstring": "暴力枚举",
"name": "twoSum1",
"signature": "def twoSum1(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "双通道哈希表",
"name": "twoSum2",
"signature": "def twoSum2(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "单次哈希表",
"name": ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum1(self, nums: List[int], target: int) -> List[int]: 暴力枚举
- def twoSum2(self, nums: List[int], target: int) -> List[int]: 双通道哈希表
- def twoSum3(self, nums: List[int], tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum1(self, nums: List[int], target: int) -> List[int]: 暴力枚举
- def twoSum2(self, nums: List[int], target: int) -> List[int]: 双通道哈希表
- def twoSum3(self, nums: List[int], tar... | 2828811ae2f905865b4f391672693375c124c185 | <|skeleton|>
class Solution:
def twoSum1(self, nums: List[int], target: int) -> List[int]:
"""暴力枚举"""
<|body_0|>
def twoSum2(self, nums: List[int], target: int) -> List[int]:
"""双通道哈希表"""
<|body_1|>
def twoSum3(self, nums: List[int], target: int) -> List[int]:
"""单... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum1(self, nums: List[int], target: int) -> List[int]:
"""暴力枚举"""
length = len(nums)
for i in range(length):
for j in range(i + 1, length):
if nums[j] == target - nums[i]:
return [i, j]
def twoSum2(self, nums: List[i... | the_stack_v2_python_sparse | LeetCode/Problems/1. Two Sum/code.py | koking0/Algorithm | train | 35 | |
a68332211053628541de082c67385e96c19ce178 | [
"data = pd.read_csv(dataPath, sep=',', index_col=0, header=0)\ndata = data.fillna(0)\nreturn data",
"if not isinstance(data, pd.DataFrame):\n data = pd.DataFrame(data)\nreturn data",
"df = self.isDataFrame(matrix)\ndf = df.to_dict(orient='index')\ndf = [[key1, key2, df[key1][key2]] for key1 in df.keys() for ... | <|body_start_0|>
data = pd.read_csv(dataPath, sep=',', index_col=0, header=0)
data = data.fillna(0)
return data
<|end_body_0|>
<|body_start_1|>
if not isinstance(data, pd.DataFrame):
data = pd.DataFrame(data)
return data
<|end_body_1|>
<|body_start_2|>
df = ... | 数据读入基类 | utils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class utils:
"""数据读入基类"""
def loadData(self, dataPath):
"""文件加载函数 @param: dataPath 文件的存储路径 @return: DataFrame 返回一个补全的DataFrame"""
<|body_0|>
def isDataFrame(self, data):
"""判断输入是否为DataFrame,如果不是则将其转换为DataFrame @param: data 传入数据 @return: DataFrame 返回DataFrame"""
... | stack_v2_sparse_classes_36k_train_020075 | 29,298 | no_license | [
{
"docstring": "文件加载函数 @param: dataPath 文件的存储路径 @return: DataFrame 返回一个补全的DataFrame",
"name": "loadData",
"signature": "def loadData(self, dataPath)"
},
{
"docstring": "判断输入是否为DataFrame,如果不是则将其转换为DataFrame @param: data 传入数据 @return: DataFrame 返回DataFrame",
"name": "isDataFrame",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_014982 | Implement the Python class `utils` described below.
Class description:
数据读入基类
Method signatures and docstrings:
- def loadData(self, dataPath): 文件加载函数 @param: dataPath 文件的存储路径 @return: DataFrame 返回一个补全的DataFrame
- def isDataFrame(self, data): 判断输入是否为DataFrame,如果不是则将其转换为DataFrame @param: data 传入数据 @return: DataFrame 返... | Implement the Python class `utils` described below.
Class description:
数据读入基类
Method signatures and docstrings:
- def loadData(self, dataPath): 文件加载函数 @param: dataPath 文件的存储路径 @return: DataFrame 返回一个补全的DataFrame
- def isDataFrame(self, data): 判断输入是否为DataFrame,如果不是则将其转换为DataFrame @param: data 传入数据 @return: DataFrame 返... | 39aa42cc01e9b1bf54a358819433c68db961b3e9 | <|skeleton|>
class utils:
"""数据读入基类"""
def loadData(self, dataPath):
"""文件加载函数 @param: dataPath 文件的存储路径 @return: DataFrame 返回一个补全的DataFrame"""
<|body_0|>
def isDataFrame(self, data):
"""判断输入是否为DataFrame,如果不是则将其转换为DataFrame @param: data 传入数据 @return: DataFrame 返回DataFrame"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class utils:
"""数据读入基类"""
def loadData(self, dataPath):
"""文件加载函数 @param: dataPath 文件的存储路径 @return: DataFrame 返回一个补全的DataFrame"""
data = pd.read_csv(dataPath, sep=',', index_col=0, header=0)
data = data.fillna(0)
return data
def isDataFrame(self, data):
"""判断输入是否为Da... | the_stack_v2_python_sparse | window.py | LikeWind99/BEELINE_UI | train | 2 |
1c3a372f0da17db15955d9446dfc6d943c784be8 | [
"output = [torch.empty_like(input) for _ in range(dist.get_world_size())]\ndist.all_gather(output, input)\nreturn tuple(output)",
"rank = dist.get_rank()\nmerged = torch.stack(grads)\ndist.all_reduce(merged)\nreturn merged[rank]"
] | <|body_start_0|>
output = [torch.empty_like(input) for _ in range(dist.get_world_size())]
dist.all_gather(output, input)
return tuple(output)
<|end_body_0|>
<|body_start_1|>
rank = dist.get_rank()
merged = torch.stack(grads)
dist.all_reduce(merged)
return merged[... | Gather tensors from all GPUS, supporting backward propagation. See more details in torch.distributed.all_gather and torch.distributed.all_reduce. | GatherTensors | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GatherTensors:
"""Gather tensors from all GPUS, supporting backward propagation. See more details in torch.distributed.all_gather and torch.distributed.all_reduce."""
def forward(ctx: Any, input: torch.Tensor) -> Tuple[Any, ...]:
"""Forward function. It must accept a context ctx as t... | stack_v2_sparse_classes_36k_train_020076 | 2,154 | permissive | [
{
"docstring": "Forward function. It must accept a context ctx as the first argument. The context can be used to store tensors that can be then retrieved during the backward pass. Args: ctx (Any): Context to be used for forward propagation. input (torch.Tensor): Tensor to be broadcast from current process.",
... | 2 | null | Implement the Python class `GatherTensors` described below.
Class description:
Gather tensors from all GPUS, supporting backward propagation. See more details in torch.distributed.all_gather and torch.distributed.all_reduce.
Method signatures and docstrings:
- def forward(ctx: Any, input: torch.Tensor) -> Tuple[Any, ... | Implement the Python class `GatherTensors` described below.
Class description:
Gather tensors from all GPUS, supporting backward propagation. See more details in torch.distributed.all_gather and torch.distributed.all_reduce.
Method signatures and docstrings:
- def forward(ctx: Any, input: torch.Tensor) -> Tuple[Any, ... | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | <|skeleton|>
class GatherTensors:
"""Gather tensors from all GPUS, supporting backward propagation. See more details in torch.distributed.all_gather and torch.distributed.all_reduce."""
def forward(ctx: Any, input: torch.Tensor) -> Tuple[Any, ...]:
"""Forward function. It must accept a context ctx as t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GatherTensors:
"""Gather tensors from all GPUS, supporting backward propagation. See more details in torch.distributed.all_gather and torch.distributed.all_reduce."""
def forward(ctx: Any, input: torch.Tensor) -> Tuple[Any, ...]:
"""Forward function. It must accept a context ctx as the first argu... | the_stack_v2_python_sparse | cv/distiller/CWD/pytorch/mmrazor/mmrazor/models/architectures/ops/gather_tensors.py | Deep-Spark/DeepSparkHub | train | 7 |
2dd4f6e20db4d88065973a37c85d97d1f5c66709 | [
"self.conf = conf\nself.transport = transport\nself.target = target\nself.RPC = self.target.topic_class",
"check_interval = self.conf.messaging_server.check_interval\ntime.sleep(check_interval)\nif self.conf.messaging_server.debug:\n LOG.debug('Checking status for message {} method {} on topic {}'.format(rpc_i... | <|body_start_0|>
self.conf = conf
self.transport = transport
self.target = target
self.RPC = self.target.topic_class
<|end_body_0|>
<|body_start_1|>
check_interval = self.conf.messaging_server.check_interval
time.sleep(check_interval)
if self.conf.messaging_serve... | Returns an RPC client using Music as a transport. The RPC client is responsible for sending method invocations to remote servers via a messaging transport. A method invocation consists of a request context dictionary a method name, and a dictionary of arguments. A cast() invocation just sends the request and returns im... | RPCClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPCClient:
"""Returns an RPC client using Music as a transport. The RPC client is responsible for sending method invocations to remote servers via a messaging transport. A method invocation consists of a request context dictionary a method name, and a dictionary of arguments. A cast() invocation ... | stack_v2_sparse_classes_36k_train_020077 | 18,894 | permissive | [
{
"docstring": "Set the transport and target",
"name": "__init__",
"signature": "def __init__(self, conf, transport, target)"
},
{
"docstring": "Check status for a given message id",
"name": "__check_rpc_status",
"signature": "def __check_rpc_status(self, rpc_id, rpc_method)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_007028 | Implement the Python class `RPCClient` described below.
Class description:
Returns an RPC client using Music as a transport. The RPC client is responsible for sending method invocations to remote servers via a messaging transport. A method invocation consists of a request context dictionary a method name, and a dictio... | Implement the Python class `RPCClient` described below.
Class description:
Returns an RPC client using Music as a transport. The RPC client is responsible for sending method invocations to remote servers via a messaging transport. A method invocation consists of a request context dictionary a method name, and a dictio... | 9c828b70d48d6c7d6668eda4d61239cfb2b28570 | <|skeleton|>
class RPCClient:
"""Returns an RPC client using Music as a transport. The RPC client is responsible for sending method invocations to remote servers via a messaging transport. A method invocation consists of a request context dictionary a method name, and a dictionary of arguments. A cast() invocation ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RPCClient:
"""Returns an RPC client using Music as a transport. The RPC client is responsible for sending method invocations to remote servers via a messaging transport. A method invocation consists of a request context dictionary a method name, and a dictionary of arguments. A cast() invocation just sends th... | the_stack_v2_python_sparse | conductor/conductor/common/music/messaging/component.py | onap/optf-has | train | 5 |
f54c70bccf53b3a61009efc4e4c59dec03e03fc0 | [
"super().__init__(**kwds)\nlayout = parent.layout()\nself.channels = []\nself.which_checked = []\nfor i, channel in enumerate(channels):\n self.powers.append(0.0)\n self.which_checked.append(False)\n channel_text = QtWidgets.QLabel(parent)\n channel_text.setText(channel)\n layout.addWidget(channel_te... | <|body_start_0|>
super().__init__(**kwds)
layout = parent.layout()
self.channels = []
self.which_checked = []
for i, channel in enumerate(channels):
self.powers.append(0.0)
self.which_checked.append(False)
channel_text = QtWidgets.QLabel(parent... | Channels class for mathematical progressions (linear, exponential). | MathChannels | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MathChannels:
"""Channels class for mathematical progressions (linear, exponential)."""
def __init__(self, configuration=None, channels=None, parent=None, **kwds):
"""Called to layout the GUI for math channels. These channels match the channels of the illumination."""
<|body_... | stack_v2_sparse_classes_36k_train_020078 | 25,535 | permissive | [
{
"docstring": "Called to layout the GUI for math channels. These channels match the channels of the illumination.",
"name": "__init__",
"signature": "def __init__(self, configuration=None, channels=None, parent=None, **kwds)"
},
{
"docstring": "This is called by an external program to specify t... | 4 | null | Implement the Python class `MathChannels` described below.
Class description:
Channels class for mathematical progressions (linear, exponential).
Method signatures and docstrings:
- def __init__(self, configuration=None, channels=None, parent=None, **kwds): Called to layout the GUI for math channels. These channels m... | Implement the Python class `MathChannels` described below.
Class description:
Channels class for mathematical progressions (linear, exponential).
Method signatures and docstrings:
- def __init__(self, configuration=None, channels=None, parent=None, **kwds): Called to layout the GUI for math channels. These channels m... | f185df3d23b231a26c46f33b0b91fffa86356dc4 | <|skeleton|>
class MathChannels:
"""Channels class for mathematical progressions (linear, exponential)."""
def __init__(self, configuration=None, channels=None, parent=None, **kwds):
"""Called to layout the GUI for math channels. These channels match the channels of the illumination."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MathChannels:
"""Channels class for mathematical progressions (linear, exponential)."""
def __init__(self, configuration=None, channels=None, parent=None, **kwds):
"""Called to layout the GUI for math channels. These channels match the channels of the illumination."""
super().__init__(**k... | the_stack_v2_python_sparse | storm_control/hal4000/progressions/progressions.py | ZhuangLab/storm-control | train | 54 |
ca7068bc9be6708994a8d72d2bc6b64cc0ea7923 | [
"param_modifiers = [('low_layer', lambda _, param: param.clamp(min=0)), ('high_layer', lambda _, param: param.clamp(max=0))]\nsuper().__init__(layer, param_modifiers)\nself.low: torch.Tensor = low.to(device=DEVICE)\nself.high: torch.Tensor = high.to(device=DEVICE)\nself.low.requires_grad = True\nself.high.requires_... | <|body_start_0|>
param_modifiers = [('low_layer', lambda _, param: param.clamp(min=0)), ('high_layer', lambda _, param: param.clamp(max=0))]
super().__init__(layer, param_modifiers)
self.low: torch.Tensor = low.to(device=DEVICE)
self.high: torch.Tensor = high.to(device=DEVICE)
se... | LRP-Z-Box rule. Source: Algorithm 7 in Appendix B section A. in https://arxiv.org/abs/2003.07631v1 | LrpZBoxRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LrpZBoxRule:
"""LRP-Z-Box rule. Source: Algorithm 7 in Appendix B section A. in https://arxiv.org/abs/2003.07631v1"""
def __init__(self, layer: torch.nn.Module, low: torch.Tensor, high: torch.Tensor) -> None:
"""Define parameter modifiers for the layer. Excerpt from the paper: "The f... | stack_v2_sparse_classes_36k_train_020079 | 6,104 | permissive | [
{
"docstring": "Define parameter modifiers for the layer. Excerpt from the paper: \"The functions f1+ and f1− are forward passes on copies of the first layer whose parameters have been processed by the functions max(0, ·) and min(0, ·) respectively.\" :param layer: Layer to be modified :param low: Tensor with l... | 2 | stack_v2_sparse_classes_30k_train_012151 | Implement the Python class `LrpZBoxRule` described below.
Class description:
LRP-Z-Box rule. Source: Algorithm 7 in Appendix B section A. in https://arxiv.org/abs/2003.07631v1
Method signatures and docstrings:
- def __init__(self, layer: torch.nn.Module, low: torch.Tensor, high: torch.Tensor) -> None: Define paramete... | Implement the Python class `LrpZBoxRule` described below.
Class description:
LRP-Z-Box rule. Source: Algorithm 7 in Appendix B section A. in https://arxiv.org/abs/2003.07631v1
Method signatures and docstrings:
- def __init__(self, layer: torch.nn.Module, low: torch.Tensor, high: torch.Tensor) -> None: Define paramete... | a2b6bd164df3e7f44e96f534e16b3df2ff8224ac | <|skeleton|>
class LrpZBoxRule:
"""LRP-Z-Box rule. Source: Algorithm 7 in Appendix B section A. in https://arxiv.org/abs/2003.07631v1"""
def __init__(self, layer: torch.nn.Module, low: torch.Tensor, high: torch.Tensor) -> None:
"""Define parameter modifiers for the layer. Excerpt from the paper: "The f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LrpZBoxRule:
"""LRP-Z-Box rule. Source: Algorithm 7 in Appendix B section A. in https://arxiv.org/abs/2003.07631v1"""
def __init__(self, layer: torch.nn.Module, low: torch.Tensor, high: torch.Tensor) -> None:
"""Define parameter modifiers for the layer. Excerpt from the paper: "The functions f1+ ... | the_stack_v2_python_sparse | lrp/rules.py | rodrigobdz/lrp | train | 5 |
5c9d303fde033b873add786a62964a98f0c2aa84 | [
"if not root1:\n return root2\nif not root2:\n return root1\nnode = TreeNode(val=root1.val + root2.val)\nnode.left = self.mergeTrees(root1.left, root2.left)\nnode.right = self.mergeTrees(root1.right, root2.right)\nreturn node",
"if not root1:\n return root2\nif not root2:\n return root1\nroot = TreeNo... | <|body_start_0|>
if not root1:
return root2
if not root2:
return root1
node = TreeNode(val=root1.val + root2.val)
node.left = self.mergeTrees(root1.left, root2.left)
node.right = self.mergeTrees(root1.right, root2.right)
return node
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
"""DFS"""
<|body_0|>
def mergeTreesBFS(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
"""BFS"""
<|body_1|>
def notnone_node(self, node):
"""非 Node 节点"""
<... | stack_v2_sparse_classes_36k_train_020080 | 1,995 | no_license | [
{
"docstring": "DFS",
"name": "mergeTrees",
"signature": "def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode"
},
{
"docstring": "BFS",
"name": "mergeTreesBFS",
"signature": "def mergeTreesBFS(self, root1: TreeNode, root2: TreeNode) -> TreeNode"
},
{
"docstring": "... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: DFS
- def mergeTreesBFS(self, root1: TreeNode, root2: TreeNode) -> TreeNode: BFS
- def notnone_node(self, node... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: DFS
- def mergeTreesBFS(self, root1: TreeNode, root2: TreeNode) -> TreeNode: BFS
- def notnone_node(self, node... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
"""DFS"""
<|body_0|>
def mergeTreesBFS(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
"""BFS"""
<|body_1|>
def notnone_node(self, node):
"""非 Node 节点"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
"""DFS"""
if not root1:
return root2
if not root2:
return root1
node = TreeNode(val=root1.val + root2.val)
node.left = self.mergeTrees(root1.left, root2.left)
n... | the_stack_v2_python_sparse | 617.合并二叉树/solution.py | QtTao/daily_leetcode | train | 0 | |
69b8a0fe365bf686fc14be0dfd42519d81e73c34 | [
"self.is_up_metric = True\nself.metric = Gauge('postgresql_up', 'PostgreSQL exporter UP status', registry=registry)\nsuper().__init__()",
"with app.app_context():\n if db_util.is_port_open():\n self.metric.set(1)\n LOGGER.info('PostgreSQLDB is UP')\n else:\n self.metric.set(0)\n ... | <|body_start_0|>
self.is_up_metric = True
self.metric = Gauge('postgresql_up', 'PostgreSQL exporter UP status', registry=registry)
super().__init__()
<|end_body_0|>
<|body_start_1|>
with app.app_context():
if db_util.is_port_open():
self.metric.set(1)
... | Up | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Up:
def __init__(self, registry, dbVersion):
"""Initialize query and metrics"""
<|body_0|>
def collect(self, app):
"""Collect from the query result :param rows: query result :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.is_up_metric ... | stack_v2_sparse_classes_36k_train_020081 | 921 | permissive | [
{
"docstring": "Initialize query and metrics",
"name": "__init__",
"signature": "def __init__(self, registry, dbVersion)"
},
{
"docstring": "Collect from the query result :param rows: query result :return:",
"name": "collect",
"signature": "def collect(self, app)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005842 | Implement the Python class `Up` described below.
Class description:
Implement the Up class.
Method signatures and docstrings:
- def __init__(self, registry, dbVersion): Initialize query and metrics
- def collect(self, app): Collect from the query result :param rows: query result :return: | Implement the Python class `Up` described below.
Class description:
Implement the Up class.
Method signatures and docstrings:
- def __init__(self, registry, dbVersion): Initialize query and metrics
- def collect(self, app): Collect from the query result :param rows: query result :return:
<|skeleton|>
class Up:
... | 2998e2baaed315c6f545879e03f13430c024e01e | <|skeleton|>
class Up:
def __init__(self, registry, dbVersion):
"""Initialize query and metrics"""
<|body_0|>
def collect(self, app):
"""Collect from the query result :param rows: query result :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Up:
def __init__(self, registry, dbVersion):
"""Initialize query and metrics"""
self.is_up_metric = True
self.metric = Gauge('postgresql_up', 'PostgreSQL exporter UP status', registry=registry)
super().__init__()
def collect(self, app):
"""Collect from the query re... | the_stack_v2_python_sparse | app/prom/metrics/general/up.py | IntershopCommunicationsAG/ish-monitoring-postgresqldb-exporter | train | 1 | |
ef71b7721e9da0238a27f588c77f7059afa8a1ff | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Manages comments | CommentsServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentsServiceServicer:
"""Manages comments"""
def CommentOnVideo(self, request, context):
"""Add a new comment to a video"""
<|body_0|>
def GetUserComments(self, request, context):
"""Get comments made by a user"""
<|body_1|>
def GetVideoComments(s... | stack_v2_sparse_classes_36k_train_020082 | 3,367 | permissive | [
{
"docstring": "Add a new comment to a video",
"name": "CommentOnVideo",
"signature": "def CommentOnVideo(self, request, context)"
},
{
"docstring": "Get comments made by a user",
"name": "GetUserComments",
"signature": "def GetUserComments(self, request, context)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_017169 | Implement the Python class `CommentsServiceServicer` described below.
Class description:
Manages comments
Method signatures and docstrings:
- def CommentOnVideo(self, request, context): Add a new comment to a video
- def GetUserComments(self, request, context): Get comments made by a user
- def GetVideoComments(self,... | Implement the Python class `CommentsServiceServicer` described below.
Class description:
Manages comments
Method signatures and docstrings:
- def CommentOnVideo(self, request, context): Add a new comment to a video
- def GetUserComments(self, request, context): Get comments made by a user
- def GetVideoComments(self,... | 55a610c97fd53c405edb2459c2722fc03857cb83 | <|skeleton|>
class CommentsServiceServicer:
"""Manages comments"""
def CommentOnVideo(self, request, context):
"""Add a new comment to a video"""
<|body_0|>
def GetUserComments(self, request, context):
"""Get comments made by a user"""
<|body_1|>
def GetVideoComments(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentsServiceServicer:
"""Manages comments"""
def CommentOnVideo(self, request, context):
"""Add a new comment to a video"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!'... | the_stack_v2_python_sparse | killrvideo/comments/comments_service_pb2_grpc.py | krzysztof-adamski/killrvideo-python | train | 0 |
40bcfafa21c3ca7b5460447beb018a09eb520a02 | [
"super(FeatureImportanceAndBilinearFeatureInteractionNetwork, self).__init__()\nself.senet = SENETLayer(num_fields, senet_reduction)\nself.emb_bilinear = BilinearInteractionLayer(embed_size, num_fields, bilinear_type, bilinear_bias)\nself.senet_bilinear = BilinearInteractionLayer(embed_size, num_fields, bilinear_ty... | <|body_start_0|>
super(FeatureImportanceAndBilinearFeatureInteractionNetwork, self).__init__()
self.senet = SENETLayer(num_fields, senet_reduction)
self.emb_bilinear = BilinearInteractionLayer(embed_size, num_fields, bilinear_type, bilinear_bias)
self.senet_bilinear = BilinearInteraction... | Model class of Feature-Importance and Bilinear-Feature-Interaction Network (FiBiNet). Feature-Importance and Bilinear-Feature-Interaction Network was proposed by Tongwen Huang in Sina Weibo Inc. in 2019, which is: #. to implement a famous computer vision algorithm `SENET` on recommendation system. #. to apply bilinear ... | FeatureImportanceAndBilinearFeatureInteractionNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureImportanceAndBilinearFeatureInteractionNetwork:
"""Model class of Feature-Importance and Bilinear-Feature-Interaction Network (FiBiNet). Feature-Importance and Bilinear-Feature-Interaction Network was proposed by Tongwen Huang in Sina Weibo Inc. in 2019, which is: #. to implement a famous ... | stack_v2_sparse_classes_36k_train_020083 | 5,507 | permissive | [
{
"docstring": "Initialize FeatureImportanceAndBilinearFeatureInteractionNetwork Args: embed_size (int): Size of embedding tensor num_fields (int): Number of inputs' fields senet_reduction (int): Size of reduction in dense layer of senet. deep_output_size (int): Output size of dense network deep_layer_sizes (Li... | 2 | stack_v2_sparse_classes_30k_train_016658 | Implement the Python class `FeatureImportanceAndBilinearFeatureInteractionNetwork` described below.
Class description:
Model class of Feature-Importance and Bilinear-Feature-Interaction Network (FiBiNet). Feature-Importance and Bilinear-Feature-Interaction Network was proposed by Tongwen Huang in Sina Weibo Inc. in 20... | Implement the Python class `FeatureImportanceAndBilinearFeatureInteractionNetwork` described below.
Class description:
Model class of Feature-Importance and Bilinear-Feature-Interaction Network (FiBiNet). Feature-Importance and Bilinear-Feature-Interaction Network was proposed by Tongwen Huang in Sina Weibo Inc. in 20... | 07a6a38c7eb44225f2b22f332081f697c3b92894 | <|skeleton|>
class FeatureImportanceAndBilinearFeatureInteractionNetwork:
"""Model class of Feature-Importance and Bilinear-Feature-Interaction Network (FiBiNet). Feature-Importance and Bilinear-Feature-Interaction Network was proposed by Tongwen Huang in Sina Weibo Inc. in 2019, which is: #. to implement a famous ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureImportanceAndBilinearFeatureInteractionNetwork:
"""Model class of Feature-Importance and Bilinear-Feature-Interaction Network (FiBiNet). Feature-Importance and Bilinear-Feature-Interaction Network was proposed by Tongwen Huang in Sina Weibo Inc. in 2019, which is: #. to implement a famous computer visi... | the_stack_v2_python_sparse | torecsys/models/ctr/feature_importance_and_bilinear_feature_interaction_network.py | zwcdp/torecsys | train | 0 |
33c738213ff3c79d8886ef0125037cc0f807d3c4 | [
"candidates = [i for i in range(9, 0, -1)]\nlst = self.combSum3(candidates, n)\nreturn [i for i in lst if len(i) == k]",
"if len(cand) == 0 or target < 0:\n return []\nlst = []\nif cand[0] < target:\n lst += self.combSum3(cand[1:], target - cand[0])\nelif cand[0] == target:\n lst += [[]]\n[i.append(cand[... | <|body_start_0|>
candidates = [i for i in range(9, 0, -1)]
lst = self.combSum3(candidates, n)
return [i for i in lst if len(i) == k]
<|end_body_0|>
<|body_start_1|>
if len(cand) == 0 or target < 0:
return []
lst = []
if cand[0] < target:
lst += se... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]] reuse combinationSum2, just filter solution whose length is K >>> sln = Solution() >>> sln.combinationSum3(3, 7) [[1, 2, 4]] >>> sln.combinationSum3(3, 9) [[1, 2, 6], [1, 3, 5], [2, 3, 4]]"""
... | stack_v2_sparse_classes_36k_train_020084 | 1,070 | permissive | [
{
"docstring": ":type k: int :type n: int :rtype: List[List[int]] reuse combinationSum2, just filter solution whose length is K >>> sln = Solution() >>> sln.combinationSum3(3, 7) [[1, 2, 4]] >>> sln.combinationSum3(3, 9) [[1, 2, 6], [1, 3, 5], [2, 3, 4]]",
"name": "combinationSum3",
"signature": "def co... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[int]] reuse combinationSum2, just filter solution whose length is K >>> sln = Solution() >>> sln.comb... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[int]] reuse combinationSum2, just filter solution whose length is K >>> sln = Solution() >>> sln.comb... | 9a154e0161a1a33baad53f7223ee72e702532001 | <|skeleton|>
class Solution:
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]] reuse combinationSum2, just filter solution whose length is K >>> sln = Solution() >>> sln.combinationSum3(3, 7) [[1, 2, 4]] >>> sln.combinationSum3(3, 9) [[1, 2, 6], [1, 3, 5], [2, 3, 4]]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]] reuse combinationSum2, just filter solution whose length is K >>> sln = Solution() >>> sln.combinationSum3(3, 7) [[1, 2, 4]] >>> sln.combinationSum3(3, 9) [[1, 2, 6], [1, 3, 5], [2, 3, 4]]"""
candid... | the_stack_v2_python_sparse | lang/c/leetcode/combSum3.py | liuyang1/test | train | 9 | |
86a60d68fc0f446ea3d69e05852b07040350b4c0 | [
"dic = {}\nfor i in range(n):\n dic[i] = set()\nfor each in relation:\n dic[each[0]].add(each[1])\n\ndef dfs(d, j):\n \"\"\"\n :param d: 深度\n :param j: 当前索引\n :return:\n \"\"\"\n if d == k:\n if n - 1 == j:\n return 1\n else:\n ... | <|body_start_0|>
dic = {}
for i in range(n):
dic[i] = set()
for each in relation:
dic[each[0]].add(each[1])
def dfs(d, j):
"""
:param d: 深度
:param j: 当前索引
:return:
"""
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
"""创建表, dfs 最大的编号为n-1, 经过k轮 :param n: :param relation: :param k: :return:"""
<|body_0|>
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
"""创建表, bfs 最大的编号为n-1, 经过k轮 :pa... | stack_v2_sparse_classes_36k_train_020085 | 4,806 | no_license | [
{
"docstring": "创建表, dfs 最大的编号为n-1, 经过k轮 :param n: :param relation: :param k: :return:",
"name": "numWays",
"signature": "def numWays(self, n: int, relation: List[List[int]], k: int) -> int"
},
{
"docstring": "创建表, bfs 最大的编号为n-1, 经过k轮 :param n: :param relation: :param k: :return:",
"name": "... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numWays(self, n: int, relation: List[List[int]], k: int) -> int: 创建表, dfs 最大的编号为n-1, 经过k轮 :param n: :param relation: :param k: :return:
- def numWays(self, n: int, relation: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numWays(self, n: int, relation: List[List[int]], k: int) -> int: 创建表, dfs 最大的编号为n-1, 经过k轮 :param n: :param relation: :param k: :return:
- def numWays(self, n: int, relation: ... | b1680014ce3f55ba952a1e64241c0cbb783cc436 | <|skeleton|>
class Solution:
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
"""创建表, dfs 最大的编号为n-1, 经过k轮 :param n: :param relation: :param k: :return:"""
<|body_0|>
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
"""创建表, bfs 最大的编号为n-1, 经过k轮 :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
"""创建表, dfs 最大的编号为n-1, 经过k轮 :param n: :param relation: :param k: :return:"""
dic = {}
for i in range(n):
dic[i] = set()
for each in relation:
dic[each[0]].add(each[1])
... | the_stack_v2_python_sparse | LCP_7.py | sun510001/leetcode_jianzhi_offer_2 | train | 0 | |
57be4b5e99f737b889427350d5a8620cbb852957 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ParticipantInfo()",
"from .endpoint_type import EndpointType\nfrom .identity_set import IdentitySet\nfrom .endpoint_type import EndpointType\nfrom .identity_set import IdentitySet\nfields: Dict[str, Callable[[Any], None]] = {'countryCo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ParticipantInfo()
<|end_body_0|>
<|body_start_1|>
from .endpoint_type import EndpointType
from .identity_set import IdentitySet
from .endpoint_type import EndpointType
fr... | ParticipantInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k_train_020086 | 4,296 | 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: ParticipantInfo",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_017621 | Implement the Python class `ParticipantInfo` described below.
Class description:
Implement the ParticipantInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `ParticipantInfo` described below.
Class description:
Implement the ParticipantInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo:
"""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: Particip... | the_stack_v2_python_sparse | msgraph/generated/models/participant_info.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a5125fe7233f6bb9016442383815ecb0044624b0 | [
"result = {}\nfor key in dir(self):\n if key.startswith('_') or (fields_to_ignore and key in fields_to_ignore):\n continue\n attr = getattr(self, key)\n if callable(attr):\n continue\n if isinstance(attr, datetime.date):\n result[key] = attr.strftime('%Y-%m-%d')\n elif attr == ma... | <|body_start_0|>
result = {}
for key in dir(self):
if key.startswith('_') or (fields_to_ignore and key in fields_to_ignore):
continue
attr = getattr(self, key)
if callable(attr):
continue
if isinstance(attr, datetime.date):
... | The base staged object | StagedObject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StagedObject:
"""The base staged object"""
def get_all_fields(self, fields_to_ignore: Optional[set]=None) -> Dict[str, Any]:
"""Converts any kind of staging object to a dictionary to save out to json :param fields_to_ignore: Fields that shouldn't be serialized out :return: The staged... | stack_v2_sparse_classes_36k_train_020087 | 24,552 | no_license | [
{
"docstring": "Converts any kind of staging object to a dictionary to save out to json :param fields_to_ignore: Fields that shouldn't be serialized out :return: The staged object as a dictionary",
"name": "get_all_fields",
"signature": "def get_all_fields(self, fields_to_ignore: Optional[set]=None) -> ... | 3 | null | Implement the Python class `StagedObject` described below.
Class description:
The base staged object
Method signatures and docstrings:
- def get_all_fields(self, fields_to_ignore: Optional[set]=None) -> Dict[str, Any]: Converts any kind of staging object to a dictionary to save out to json :param fields_to_ignore: Fi... | Implement the Python class `StagedObject` described below.
Class description:
The base staged object
Method signatures and docstrings:
- def get_all_fields(self, fields_to_ignore: Optional[set]=None) -> Dict[str, Any]: Converts any kind of staging object to a dictionary to save out to json :param fields_to_ignore: Fi... | d7d46b0fc75ff04c4c3313e0af027302936a6c3f | <|skeleton|>
class StagedObject:
"""The base staged object"""
def get_all_fields(self, fields_to_ignore: Optional[set]=None) -> Dict[str, Any]:
"""Converts any kind of staging object to a dictionary to save out to json :param fields_to_ignore: Fields that shouldn't be serialized out :return: The staged... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StagedObject:
"""The base staged object"""
def get_all_fields(self, fields_to_ignore: Optional[set]=None) -> Dict[str, Any]:
"""Converts any kind of staging object to a dictionary to save out to json :param fields_to_ignore: Fields that shouldn't be serialized out :return: The staged object as a ... | the_stack_v2_python_sparse | sylvan_library/data_import/staging.py | marshl/sylvan_library | train | 7 |
2a63e783aa329e612bdef626f99f1045af5cef8b | [
"prev_dict = {}\nwhile True:\n if n == 1:\n return True\n try:\n if prev_dict[n]:\n return False\n except KeyError:\n prev_dict[n] = True\n n = self.nextN(n)",
"sum_of_each_dec_pos_val_squared = 0\ndec_pos_val = 0\nwhile n > 0:\n dec_pos_val = n % 10\n sum_of_each... | <|body_start_0|>
prev_dict = {}
while True:
if n == 1:
return True
try:
if prev_dict[n]:
return False
except KeyError:
prev_dict[n] = True
n = self.nextN(n)
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def nextN(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
prev_dict = {}
while True:
if n == 1:
retu... | stack_v2_sparse_classes_36k_train_020088 | 2,542 | no_license | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isHappy",
"signature": "def isHappy(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nextN",
"signature": "def nextN(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000256 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): :type n: int :rtype: bool
- def nextN(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 isHappy(self, n): :type n: int :rtype: bool
- def nextN(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: int :r... | b155895c90169ec97372b2517f556fd50deac2bc | <|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def nextN(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
prev_dict = {}
while True:
if n == 1:
return True
try:
if prev_dict[n]:
return False
except KeyError:
prev_dict[n] = T... | the_stack_v2_python_sparse | happy_number.py | claytonjwong/Sandbox-Python | train | 0 | |
fab8bd509b0d4774c66453d62af882200d726019 | [
"re_basic = re.compile('^\\\\d+$')\nre_white = re.compile('^(?:.*[bB])*(.+)[wW](?:.*[bB])*$')\nre_black = re.compile('^(?:.*[wW])*(.+)[bB](?:.*[wW])*$')\nre_extract = re.compile('^(\\\\d+)(?:u(\\\\d+))*(?:a(\\\\d+))*$')\nm = re_basic.match(expression)\nif m:\n self.bc = self.wc = int(m.group(0))\n self.wuntil... | <|body_start_0|>
re_basic = re.compile('^\\d+$')
re_white = re.compile('^(?:.*[bB])*(.+)[wW](?:.*[bB])*$')
re_black = re.compile('^(?:.*[wW])*(.+)[bB](?:.*[wW])*$')
re_extract = re.compile('^(\\d+)(?:u(\\d+))*(?:a(\\d+))*$')
m = re_basic.match(expression)
if m:
... | Cutoff | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cutoff:
def __init__(self, expression):
"""Create a cutoff from an expression."""
<|body_0|>
def cut_pvs(self, pvs, move, color):
"""Eliminate pvs based on cutoff expression"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
re_basic = re.compile('^\\d... | stack_v2_sparse_classes_36k_train_020089 | 3,309 | permissive | [
{
"docstring": "Create a cutoff from an expression.",
"name": "__init__",
"signature": "def __init__(self, expression)"
},
{
"docstring": "Eliminate pvs based on cutoff expression",
"name": "cut_pvs",
"signature": "def cut_pvs(self, pvs, move, color)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012612 | Implement the Python class `Cutoff` described below.
Class description:
Implement the Cutoff class.
Method signatures and docstrings:
- def __init__(self, expression): Create a cutoff from an expression.
- def cut_pvs(self, pvs, move, color): Eliminate pvs based on cutoff expression | Implement the Python class `Cutoff` described below.
Class description:
Implement the Cutoff class.
Method signatures and docstrings:
- def __init__(self, expression): Create a cutoff from an expression.
- def cut_pvs(self, pvs, move, color): Eliminate pvs based on cutoff expression
<|skeleton|>
class Cutoff:
d... | f3f24e4587cf623e8b7d19a8e5682c7b6d0efaf4 | <|skeleton|>
class Cutoff:
def __init__(self, expression):
"""Create a cutoff from an expression."""
<|body_0|>
def cut_pvs(self, pvs, move, color):
"""Eliminate pvs based on cutoff expression"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cutoff:
def __init__(self, expression):
"""Create a cutoff from an expression."""
re_basic = re.compile('^\\d+$')
re_white = re.compile('^(?:.*[bB])*(.+)[wW](?:.*[bB])*$')
re_black = re.compile('^(?:.*[wW])*(.+)[bB](?:.*[wW])*$')
re_extract = re.compile('^(\\d+)(?:u(\\d... | the_stack_v2_python_sparse | cutoff.py | zeFresk/deep-position-analysis | train | 22 | |
51471a242c9778609113ef6ff9775962dcd5ab44 | [
"if not s or len(s.strip(' ')) == 0:\n return ''\nres = s.split(' ')\nstr = ''\nfor i in range(len(res) - 1, -1, -1):\n str = str.strip(' ') + ' ' + res[i]\nreturn str.strip(' ')",
"if not s or len(s.strip(' ')) == 0:\n return ''\nslist = s.split()\nslist = slist[::-1]\nreturn ' '.join(slist)"
] | <|body_start_0|>
if not s or len(s.strip(' ')) == 0:
return ''
res = s.split(' ')
str = ''
for i in range(len(res) - 1, -1, -1):
str = str.strip(' ') + ' ' + res[i]
return str.strip(' ')
<|end_body_0|>
<|body_start_1|>
if not s or len(s.strip(' ')... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWordsSol(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s or len(s.strip(' ')) == 0:
return ''
... | stack_v2_sparse_classes_36k_train_020090 | 1,018 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWordsSol",
"signature": "def reverseWordsSol(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020890 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWordsSol(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWordsSol(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseWords(self, s):
... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWordsSol(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
if not s or len(s.strip(' ')) == 0:
return ''
res = s.split(' ')
str = ''
for i in range(len(res) - 1, -1, -1):
str = str.strip(' ') + ' ' + res[i]
return str.strip(' ')
... | the_stack_v2_python_sparse | medium/reverse_words_in_string.py | gerrycfchang/leetcode-python | train | 2 | |
4056743ea5fa42f82439e8c8c0ab8eb0d8410d83 | [
"logger.debug('Get repo: %s/%s permissions for user %s', namespace_name, repository_name, username)\nperm = model.get_repo_permission_for_user(username, namespace_name, repository_name)\nreturn perm.to_dict()",
"new_permission = request.get_json()\nlogger.debug('Setting permission to: %s for user %s', new_permiss... | <|body_start_0|>
logger.debug('Get repo: %s/%s permissions for user %s', namespace_name, repository_name, username)
perm = model.get_repo_permission_for_user(username, namespace_name, repository_name)
return perm.to_dict()
<|end_body_0|>
<|body_start_1|>
new_permission = request.get_jso... | Resource for managing individual user permissions. | RepositoryUserPermission | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryUserPermission:
"""Resource for managing individual user permissions."""
def get(self, namespace_name, repository_name, username):
"""Get the permission for the specified user."""
<|body_0|>
def put(self, namespace_name, repository_name, username):
"""U... | stack_v2_sparse_classes_36k_train_020091 | 8,862 | permissive | [
{
"docstring": "Get the permission for the specified user.",
"name": "get",
"signature": "def get(self, namespace_name, repository_name, username)"
},
{
"docstring": "Update the perimssions for an existing repository.",
"name": "put",
"signature": "def put(self, namespace_name, repositor... | 3 | stack_v2_sparse_classes_30k_train_001546 | Implement the Python class `RepositoryUserPermission` described below.
Class description:
Resource for managing individual user permissions.
Method signatures and docstrings:
- def get(self, namespace_name, repository_name, username): Get the permission for the specified user.
- def put(self, namespace_name, reposito... | Implement the Python class `RepositoryUserPermission` described below.
Class description:
Resource for managing individual user permissions.
Method signatures and docstrings:
- def get(self, namespace_name, repository_name, username): Get the permission for the specified user.
- def put(self, namespace_name, reposito... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class RepositoryUserPermission:
"""Resource for managing individual user permissions."""
def get(self, namespace_name, repository_name, username):
"""Get the permission for the specified user."""
<|body_0|>
def put(self, namespace_name, repository_name, username):
"""U... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepositoryUserPermission:
"""Resource for managing individual user permissions."""
def get(self, namespace_name, repository_name, username):
"""Get the permission for the specified user."""
logger.debug('Get repo: %s/%s permissions for user %s', namespace_name, repository_name, username)
... | the_stack_v2_python_sparse | endpoints/api/permission.py | quay/quay | train | 2,363 |
3d89ae0613d2494b70d6b527647ffee1113c9d46 | [
"querier = wt_uu.CreateGenericWebTestQuerier()\nwith self.assertRaises(RuntimeError):\n querier._StripPrefixFromTestId('foobar')",
"querier = wt_uu.CreateGenericWebTestQuerier()\ntest_ids = [prefix + 'a' for prefix in queries.KNOWN_TEST_ID_PREFIXES]\nfor t in test_ids:\n stripped = querier._StripPrefixFromT... | <|body_start_0|>
querier = wt_uu.CreateGenericWebTestQuerier()
with self.assertRaises(RuntimeError):
querier._StripPrefixFromTestId('foobar')
<|end_body_0|>
<|body_start_1|>
querier = wt_uu.CreateGenericWebTestQuerier()
test_ids = [prefix + 'a' for prefix in queries.KNOWN_TE... | StripPrefixFromTestIdUnittest | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StripPrefixFromTestIdUnittest:
def testUnknownPrefix(self):
"""Tests that an error is raised if an unknown prefix is found."""
<|body_0|>
def testKnownPrefixes(self):
"""Tests that all known prefixes are properly stripped."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_020092 | 5,666 | permissive | [
{
"docstring": "Tests that an error is raised if an unknown prefix is found.",
"name": "testUnknownPrefix",
"signature": "def testUnknownPrefix(self)"
},
{
"docstring": "Tests that all known prefixes are properly stripped.",
"name": "testKnownPrefixes",
"signature": "def testKnownPrefixe... | 2 | stack_v2_sparse_classes_30k_test_000460 | Implement the Python class `StripPrefixFromTestIdUnittest` described below.
Class description:
Implement the StripPrefixFromTestIdUnittest class.
Method signatures and docstrings:
- def testUnknownPrefix(self): Tests that an error is raised if an unknown prefix is found.
- def testKnownPrefixes(self): Tests that all ... | Implement the Python class `StripPrefixFromTestIdUnittest` described below.
Class description:
Implement the StripPrefixFromTestIdUnittest class.
Method signatures and docstrings:
- def testUnknownPrefix(self): Tests that an error is raised if an unknown prefix is found.
- def testKnownPrefixes(self): Tests that all ... | fd8a8914ca0183f0add65ae55f04e287543c7d4a | <|skeleton|>
class StripPrefixFromTestIdUnittest:
def testUnknownPrefix(self):
"""Tests that an error is raised if an unknown prefix is found."""
<|body_0|>
def testKnownPrefixes(self):
"""Tests that all known prefixes are properly stripped."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StripPrefixFromTestIdUnittest:
def testUnknownPrefix(self):
"""Tests that an error is raised if an unknown prefix is found."""
querier = wt_uu.CreateGenericWebTestQuerier()
with self.assertRaises(RuntimeError):
querier._StripPrefixFromTestId('foobar')
def testKnownPref... | the_stack_v2_python_sparse | third_party/blink/tools/blinkpy/web_tests/stale_expectation_removal/queries_unittest.py | SREERAGI18/chromium | train | 1 | |
3a1452883c57e383f150dce7c4b9cce3fbb6f716 | [
"super().initialize_options()\nself.no_capture = None\nself.match_name = None\nself._pytest_public = None\nself._pytest_private = None",
"super().initialize_options()\nself.test_args = []\nself.test_suite = True",
"self._init_pytest()\nself._patch_pytest()\nself._run_pytest()",
"from betse.util.py.module impo... | <|body_start_0|>
super().initialize_options()
self.no_capture = None
self.match_name = None
self._pytest_public = None
self._pytest_private = None
<|end_body_0|>
<|body_start_1|>
super().initialize_options()
self.test_args = []
self.test_suite = True
<|en... | Command class exercising (i.e., testing) the current application with :mod:`pytest`. Attributes ---------- match_name : str Python-evaluatable expression (e.g., ``'test_method or test other'``) conditionally matching a substring of the name of each test function or class to be run if any *or* `None` if all tests are to... | test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test:
"""Command class exercising (i.e., testing) the current application with :mod:`pytest`. Attributes ---------- match_name : str Python-evaluatable expression (e.g., ``'test_method or test other'``) conditionally matching a substring of the name of each test function or class to be run if any... | stack_v2_sparse_classes_36k_train_020093 | 20,690 | no_license | [
{
"docstring": "Declare option-specific attributes subsequently initialized by :meth:`finalize_options`. If this function is *not* defined, the default implementation of this method raises an inscrutable :mod:`distutils` exception. If these attributes are *not* declared, the subsequent call to :meth:`self.set_u... | 6 | null | Implement the Python class `test` described below.
Class description:
Command class exercising (i.e., testing) the current application with :mod:`pytest`. Attributes ---------- match_name : str Python-evaluatable expression (e.g., ``'test_method or test other'``) conditionally matching a substring of the name of each ... | Implement the Python class `test` described below.
Class description:
Command class exercising (i.e., testing) the current application with :mod:`pytest`. Attributes ---------- match_name : str Python-evaluatable expression (e.g., ``'test_method or test other'``) conditionally matching a substring of the name of each ... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class test:
"""Command class exercising (i.e., testing) the current application with :mod:`pytest`. Attributes ---------- match_name : str Python-evaluatable expression (e.g., ``'test_method or test other'``) conditionally matching a substring of the name of each test function or class to be run if any... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test:
"""Command class exercising (i.e., testing) the current application with :mod:`pytest`. Attributes ---------- match_name : str Python-evaluatable expression (e.g., ``'test_method or test other'``) conditionally matching a substring of the name of each test function or class to be run if any *or* `None` ... | the_stack_v2_python_sparse | betse/lib/setuptools/command/supcmdtest.py | R-Stefano/betse-ml | train | 0 |
585acef6122cc812c107951480f03b1c2071625f | [
"response = self.client.get(url, HTTP_ACCEPT='application/json', **kwargs)\nself.assertEqual(response.status_code, code)\nreturn response",
"self.check_path(reverse('api-inventree-info'))\nself.client.logout()\nself.check_path(reverse('account_login'))\nself.check_path(reverse('account_logout'))\nresponse = self.... | <|body_start_0|>
response = self.client.get(url, HTTP_ACCEPT='application/json', **kwargs)
self.assertEqual(response.status_code, code)
return response
<|end_body_0|>
<|body_start_1|>
self.check_path(reverse('api-inventree-info'))
self.client.logout()
self.check_path(rev... | Test for middleware functions. | MiddlewareTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MiddlewareTests:
"""Test for middleware functions."""
def check_path(self, url, code=200, **kwargs):
"""Helper function to run a request."""
<|body_0|>
def test_AuthRequiredMiddleware(self):
"""Test the auth middleware."""
<|body_1|>
def test_token_a... | stack_v2_sparse_classes_36k_train_020094 | 3,114 | permissive | [
{
"docstring": "Helper function to run a request.",
"name": "check_path",
"signature": "def check_path(self, url, code=200, **kwargs)"
},
{
"docstring": "Test the auth middleware.",
"name": "test_AuthRequiredMiddleware",
"signature": "def test_AuthRequiredMiddleware(self)"
},
{
"... | 4 | null | Implement the Python class `MiddlewareTests` described below.
Class description:
Test for middleware functions.
Method signatures and docstrings:
- def check_path(self, url, code=200, **kwargs): Helper function to run a request.
- def test_AuthRequiredMiddleware(self): Test the auth middleware.
- def test_token_auth(... | Implement the Python class `MiddlewareTests` described below.
Class description:
Test for middleware functions.
Method signatures and docstrings:
- def check_path(self, url, code=200, **kwargs): Helper function to run a request.
- def test_AuthRequiredMiddleware(self): Test the auth middleware.
- def test_token_auth(... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class MiddlewareTests:
"""Test for middleware functions."""
def check_path(self, url, code=200, **kwargs):
"""Helper function to run a request."""
<|body_0|>
def test_AuthRequiredMiddleware(self):
"""Test the auth middleware."""
<|body_1|>
def test_token_a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MiddlewareTests:
"""Test for middleware functions."""
def check_path(self, url, code=200, **kwargs):
"""Helper function to run a request."""
response = self.client.get(url, HTTP_ACCEPT='application/json', **kwargs)
self.assertEqual(response.status_code, code)
return respon... | the_stack_v2_python_sparse | InvenTree/InvenTree/test_middleware.py | inventree/InvenTree | train | 3,077 |
c9c95956ff37fc86256e98c082e86644463a6eb2 | [
"if i == self.n:\n if value == self.target:\n self.ans.append(prefix)\n return None\ncurr += self.num[i]\nif i + 1 < self.n and (not curr == '0'):\n self.backtrack(i + 1, prefix, prev, curr, value)\nif prefix == '':\n self.backtrack(i + 1, curr, curr, '', value + int(curr))\nelse:\n self.backt... | <|body_start_0|>
if i == self.n:
if value == self.target:
self.ans.append(prefix)
return None
curr += self.num[i]
if i + 1 < self.n and (not curr == '0'):
self.backtrack(i + 1, prefix, prev, curr, value)
if prefix == '':
sel... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def backtrack(self, i, prefix, prev, curr, value):
"""Keep track the last operation only, reverse back previous '+' and '-' for '*' appending."""
<|body_0|>
def addOperators(self, num: str, target: int) -> List[str]:
"""backtrack, pay attention to 0."""
... | stack_v2_sparse_classes_36k_train_020095 | 3,521 | no_license | [
{
"docstring": "Keep track the last operation only, reverse back previous '+' and '-' for '*' appending.",
"name": "backtrack",
"signature": "def backtrack(self, i, prefix, prev, curr, value)"
},
{
"docstring": "backtrack, pay attention to 0.",
"name": "addOperators",
"signature": "def a... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backtrack(self, i, prefix, prev, curr, value): Keep track the last operation only, reverse back previous '+' and '-' for '*' appending.
- def addOperators(self, num: str, tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backtrack(self, i, prefix, prev, curr, value): Keep track the last operation only, reverse back previous '+' and '-' for '*' appending.
- def addOperators(self, num: str, tar... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Solution:
def backtrack(self, i, prefix, prev, curr, value):
"""Keep track the last operation only, reverse back previous '+' and '-' for '*' appending."""
<|body_0|>
def addOperators(self, num: str, target: int) -> List[str]:
"""backtrack, pay attention to 0."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def backtrack(self, i, prefix, prev, curr, value):
"""Keep track the last operation only, reverse back previous '+' and '-' for '*' appending."""
if i == self.n:
if value == self.target:
self.ans.append(prefix)
return None
curr += self.... | the_stack_v2_python_sparse | src/0200-0299/0282.expression.operator.py | gyang274/leetcode | train | 1 | |
656b627bc2bd4c4907f3516754e41407e4094459 | [
"super().__init__(**kwargs)\nself.water_price = water_price\nself.assert_valid()",
"tgi = 0\nfor individual in self.individuals:\n tgi += individual.gross_income\nself.total_gross_income = tgi",
"th = 0\nfor individual in self.individuals:\n th += individual.harvest\nself.total_harvest = th",
"\"\"\"Get... | <|body_start_0|>
super().__init__(**kwargs)
self.water_price = water_price
self.assert_valid()
<|end_body_0|>
<|body_start_1|>
tgi = 0
for individual in self.individuals:
tgi += individual.gross_income
self.total_gross_income = tgi
<|end_body_1|>
<|body_star... | World entity type mixin implementation class. | World | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class World:
"""World entity type mixin implementation class."""
def __init__(self, *, water_price, **kwargs):
"""Initialize an instance of World."""
<|body_0|>
def calc_total_gross_income(self, unused_t):
"""Calculate total gross income explicitly."""
<|body_1... | stack_v2_sparse_classes_36k_train_020096 | 3,453 | permissive | [
{
"docstring": "Initialize an instance of World.",
"name": "__init__",
"signature": "def __init__(self, *, water_price, **kwargs)"
},
{
"docstring": "Calculate total gross income explicitly.",
"name": "calc_total_gross_income",
"signature": "def calc_total_gross_income(self, unused_t)"
... | 6 | stack_v2_sparse_classes_30k_train_005680 | Implement the Python class `World` described below.
Class description:
World entity type mixin implementation class.
Method signatures and docstrings:
- def __init__(self, *, water_price, **kwargs): Initialize an instance of World.
- def calc_total_gross_income(self, unused_t): Calculate total gross income explicitly... | Implement the Python class `World` described below.
Class description:
World entity type mixin implementation class.
Method signatures and docstrings:
- def __init__(self, *, water_price, **kwargs): Initialize an instance of World.
- def calc_total_gross_income(self, unused_t): Calculate total gross income explicitly... | c5741080db35713ff469d19698519499c46583ca | <|skeleton|>
class World:
"""World entity type mixin implementation class."""
def __init__(self, *, water_price, **kwargs):
"""Initialize an instance of World."""
<|body_0|>
def calc_total_gross_income(self, unused_t):
"""Calculate total gross income explicitly."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class World:
"""World entity type mixin implementation class."""
def __init__(self, *, water_price, **kwargs):
"""Initialize an instance of World."""
super().__init__(**kwargs)
self.water_price = water_price
self.assert_valid()
def calc_total_gross_income(self, unused_t):
... | the_stack_v2_python_sparse | pycopancore/model_components/exodus/implementation/world.py | vishalbelsare/pycopancore | train | 0 |
6825a01d33499bd8f71bf9296a5086f39889ac34 | [
"super(CNN, self).__init__()\nself.resnet = models.resnet18(pretrained=True, progress=False)\nself.dense1 = nn.Linear(1000, 500)\nself.dense2 = nn.Linear(500, 100)\nself.dense3 = nn.Linear(100, 12)\nself.dense4 = nn.Linear(12, 1)",
"x = self.resnet(x)\nx = self.dense1(x)\nx = relu(x)\nx = self.dense2(x)\nx = relu... | <|body_start_0|>
super(CNN, self).__init__()
self.resnet = models.resnet18(pretrained=True, progress=False)
self.dense1 = nn.Linear(1000, 500)
self.dense2 = nn.Linear(500, 100)
self.dense3 = nn.Linear(100, 12)
self.dense4 = nn.Linear(12, 1)
<|end_body_0|>
<|body_start_1|... | CNN | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
def __init__(self):
"""Initialize the model by setting up the layers"""
<|body_0|>
def forward(self, x):
"""Perform a forward pass of our model on some input and hidden state"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CNN, self).__in... | stack_v2_sparse_classes_36k_train_020097 | 1,108 | no_license | [
{
"docstring": "Initialize the model by setting up the layers",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform a forward pass of our model on some input and hidden state",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000039 | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self): Initialize the model by setting up the layers
- def forward(self, x): Perform a forward pass of our model on some input and hidden state | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self): Initialize the model by setting up the layers
- def forward(self, x): Perform a forward pass of our model on some input and hidden state
<|skeleton|>
class CNN:
d... | 2fc9990c26224d9f34a21e69c4f57f28c1b1f648 | <|skeleton|>
class CNN:
def __init__(self):
"""Initialize the model by setting up the layers"""
<|body_0|>
def forward(self, x):
"""Perform a forward pass of our model on some input and hidden state"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNN:
def __init__(self):
"""Initialize the model by setting up the layers"""
super(CNN, self).__init__()
self.resnet = models.resnet18(pretrained=True, progress=False)
self.dense1 = nn.Linear(1000, 500)
self.dense2 = nn.Linear(500, 100)
self.dense3 = nn.Linear(1... | the_stack_v2_python_sparse | models/CNN/CNN.py | knutbugg/FALKOR | train | 1 | |
22e1094ff2cde37348cc83e93ddff97450098c14 | [
"self.folder = folder\nself.filter_fn = lambda x: True if filter_fn is None else filter_fn\nself.header = header\nself.reader = [] if header is None else [[header]]",
"self.reader.extend([[filename] for filename in os.listdir(self.folder) if self.filter_fn(filename)])\nfor filename in self.reader:\n yield file... | <|body_start_0|>
self.folder = folder
self.filter_fn = lambda x: True if filter_fn is None else filter_fn
self.header = header
self.reader = [] if header is None else [[header]]
<|end_body_0|>
<|body_start_1|>
self.reader.extend([[filename] for filename in os.listdir(self.folder... | Adapter to read files in a folder | FolderReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FolderReader:
"""Adapter to read files in a folder"""
def __init__(self, folder, filter_fn=None, header=None):
"""Constructor method for the reader"""
<|body_0|>
def open_reader(self):
"""exploring the folder"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_020098 | 1,329 | permissive | [
{
"docstring": "Constructor method for the reader",
"name": "__init__",
"signature": "def __init__(self, folder, filter_fn=None, header=None)"
},
{
"docstring": "exploring the folder",
"name": "open_reader",
"signature": "def open_reader(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018719 | Implement the Python class `FolderReader` described below.
Class description:
Adapter to read files in a folder
Method signatures and docstrings:
- def __init__(self, folder, filter_fn=None, header=None): Constructor method for the reader
- def open_reader(self): exploring the folder | Implement the Python class `FolderReader` described below.
Class description:
Adapter to read files in a folder
Method signatures and docstrings:
- def __init__(self, folder, filter_fn=None, header=None): Constructor method for the reader
- def open_reader(self): exploring the folder
<|skeleton|>
class FolderReader:... | bbf221e41ef04e8d37a511a35a63216b64689449 | <|skeleton|>
class FolderReader:
"""Adapter to read files in a folder"""
def __init__(self, folder, filter_fn=None, header=None):
"""Constructor method for the reader"""
<|body_0|>
def open_reader(self):
"""exploring the folder"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FolderReader:
"""Adapter to read files in a folder"""
def __init__(self, folder, filter_fn=None, header=None):
"""Constructor method for the reader"""
self.folder = folder
self.filter_fn = lambda x: True if filter_fn is None else filter_fn
self.header = header
self... | the_stack_v2_python_sparse | bigmler/folderreader.py | jaor/bigmler | train | 0 |
4eb02f91069b768394a66c36b64411d69619b3b8 | [
"if not root:\n return ''\nqueue = collections.deque([root])\nres = []\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('None')\nreturn '[' + ','.join(res) + ']'",
"if not... | <|body_start_0|>
if not root:
return ''
queue = collections.deque([root])
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_020099 | 3,217 | 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:... | 79d4e3946309f6e37e18c1958243d63faf99861c | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
queue = collections.deque([root])
res = []
while queue:
node = queue.popleft()
if node:
... | the_stack_v2_python_sparse | 201-300/297_二叉树的序列化与反序列化.py | ZhiyuSun/leetcode-practice | train | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.