blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1491a6ffffb229756e3b21af6431ba042fa5fd4 | [
"fake_cfg = mock.MagicMock()\nfake_cfg.ssh_public_key_path = self.SSH_PUBLIC_KEY_PATH\nfake_cfg.machine_type = self.MACHINE_TYPE\nfake_cfg.network = self.NETWORK\nfake_cfg.zone = self.ZONE\nfake_cfg.resolution = '{x}x{y}x32x{dpi}'.format(x=self.X_RES, y=self.Y_RES, dpi=self.DPI)\nfake_cfg.metadata_variable = self.M... | <|body_start_0|>
fake_cfg = mock.MagicMock()
fake_cfg.ssh_public_key_path = self.SSH_PUBLIC_KEY_PATH
fake_cfg.machine_type = self.MACHINE_TYPE
fake_cfg.network = self.NETWORK
fake_cfg.zone = self.ZONE
fake_cfg.resolution = '{x}x{y}x32x{dpi}'.format(x=self.X_RES, y=self.Y_... | Test GoldfishComputeClient. | GoldfishComputeClientTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoldfishComputeClientTest:
"""Test GoldfishComputeClient."""
def _GetFakeConfig(self):
"""Create a fake configuration object. Returns: A fake configuration mock object."""
<|body_0|>
def setUp(self):
"""Set up the test."""
<|body_1|>
def testCreateIn... | stack_v2_sparse_classes_10k_train_002200 | 5,985 | permissive | [
{
"docstring": "Create a fake configuration object. Returns: A fake configuration mock object.",
"name": "_GetFakeConfig",
"signature": "def _GetFakeConfig(self)"
},
{
"docstring": "Set up the test.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test CreateI... | 3 | stack_v2_sparse_classes_30k_train_001145 | Implement the Python class `GoldfishComputeClientTest` described below.
Class description:
Test GoldfishComputeClient.
Method signatures and docstrings:
- def _GetFakeConfig(self): Create a fake configuration object. Returns: A fake configuration mock object.
- def setUp(self): Set up the test.
- def testCreateInstan... | Implement the Python class `GoldfishComputeClientTest` described below.
Class description:
Test GoldfishComputeClient.
Method signatures and docstrings:
- def _GetFakeConfig(self): Create a fake configuration object. Returns: A fake configuration mock object.
- def setUp(self): Set up the test.
- def testCreateInstan... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class GoldfishComputeClientTest:
"""Test GoldfishComputeClient."""
def _GetFakeConfig(self):
"""Create a fake configuration object. Returns: A fake configuration mock object."""
<|body_0|>
def setUp(self):
"""Set up the test."""
<|body_1|>
def testCreateIn... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GoldfishComputeClientTest:
"""Test GoldfishComputeClient."""
def _GetFakeConfig(self):
"""Create a fake configuration object. Returns: A fake configuration mock object."""
fake_cfg = mock.MagicMock()
fake_cfg.ssh_public_key_path = self.SSH_PUBLIC_KEY_PATH
fake_cfg.machine_... | the_stack_v2_python_sparse | tools/acloud/internal/lib/goldfish_compute_client_test.py | ZYHGOD-1/Aosp11 | train | 0 |
b70fd454475f252208e3cb6036f04f88f42e30b5 | [
"logger.warning('Wiping the whole database')\nself.client.drop_database(self.db_name)\nlogger.debug('Database wiped')",
"indexes = []\nfor collection_name in self.db.list_collection_names():\n if collection and collection != collection_name:\n continue\n for index_name in self.db[collection_name].ind... | <|body_start_0|>
logger.warning('Wiping the whole database')
self.client.drop_database(self.db_name)
logger.debug('Database wiped')
<|end_body_0|>
<|body_start_1|>
indexes = []
for collection_name in self.db.list_collection_names():
if collection and collection != co... | docstring for MongoAdapter | MongoAdapter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoAdapter:
"""docstring for MongoAdapter"""
def wipe_db(self):
"""Wipe the whole database"""
<|body_0|>
def indexes(self, collection=None):
"""Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)""... | stack_v2_sparse_classes_10k_train_002201 | 2,593 | permissive | [
{
"docstring": "Wipe the whole database",
"name": "wipe_db",
"signature": "def wipe_db(self)"
},
{
"docstring": "Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)",
"name": "indexes",
"signature": "def indexes(self, collec... | 4 | stack_v2_sparse_classes_30k_train_002366 | Implement the Python class `MongoAdapter` described below.
Class description:
docstring for MongoAdapter
Method signatures and docstrings:
- def wipe_db(self): Wipe the whole database
- def indexes(self, collection=None): Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Ret... | Implement the Python class `MongoAdapter` described below.
Class description:
docstring for MongoAdapter
Method signatures and docstrings:
- def wipe_db(self): Wipe the whole database
- def indexes(self, collection=None): Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Ret... | a2be3c8215df7acfab13c9a1588a17154b04c000 | <|skeleton|>
class MongoAdapter:
"""docstring for MongoAdapter"""
def wipe_db(self):
"""Wipe the whole database"""
<|body_0|>
def indexes(self, collection=None):
"""Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MongoAdapter:
"""docstring for MongoAdapter"""
def wipe_db(self):
"""Wipe the whole database"""
logger.warning('Wiping the whole database')
self.client.drop_database(self.db_name)
logger.debug('Database wiped')
def indexes(self, collection=None):
"""Return a l... | the_stack_v2_python_sparse | loqusdb/plugins/mongo/adapter.py | Clinical-Genomics/loqusdb | train | 5 |
e757b08074273917b4577bf2ac8836a4f5dd14fd | [
"self.resultfile = Utils.config_Utils.resultfile\nself.datafile = Utils.config_Utils.datafile\nself.logsdir = Utils.config_Utils.logsdir\nself.filename = Utils.config_Utils.filename\nself.logfile = Utils.config_Utils.logfile\nself.map_function = {'INFO': print_info, 'DEBUG': print_debug, 'WARN': print_warning, 'ERR... | <|body_start_0|>
self.resultfile = Utils.config_Utils.resultfile
self.datafile = Utils.config_Utils.datafile
self.logsdir = Utils.config_Utils.logsdir
self.filename = Utils.config_Utils.filename
self.logfile = Utils.config_Utils.logfile
self.map_function = {'INFO': print_... | class LogActions having keywords that are used for logging within test | LogActions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogActions:
"""class LogActions having keywords that are used for logging within test"""
def __init__(self):
"""Constructor"""
<|body_0|>
def log_message(self, message=None, type='INFO', list_message=None, dict_message=None):
"""Keyword to print the given message... | stack_v2_sparse_classes_10k_train_002202 | 3,290 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Keyword to print the given message. :Arguments: 1. type = message severity level INFO,WARN,DEBUG,ERROR are supported values 2. message = message to be printed, 3. list_message = list of message... | 2 | stack_v2_sparse_classes_30k_train_001409 | Implement the Python class `LogActions` described below.
Class description:
class LogActions having keywords that are used for logging within test
Method signatures and docstrings:
- def __init__(self): Constructor
- def log_message(self, message=None, type='INFO', list_message=None, dict_message=None): Keyword to pr... | Implement the Python class `LogActions` described below.
Class description:
class LogActions having keywords that are used for logging within test
Method signatures and docstrings:
- def __init__(self): Constructor
- def log_message(self, message=None, type='INFO', list_message=None, dict_message=None): Keyword to pr... | 685761cf044182ec88ce86a942d4be1e150a1256 | <|skeleton|>
class LogActions:
"""class LogActions having keywords that are used for logging within test"""
def __init__(self):
"""Constructor"""
<|body_0|>
def log_message(self, message=None, type='INFO', list_message=None, dict_message=None):
"""Keyword to print the given message... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LogActions:
"""class LogActions having keywords that are used for logging within test"""
def __init__(self):
"""Constructor"""
self.resultfile = Utils.config_Utils.resultfile
self.datafile = Utils.config_Utils.datafile
self.logsdir = Utils.config_Utils.logsdir
self... | the_stack_v2_python_sparse | warrior/Actions/LogActions/log_actions.py | warriorframework/warriorframework | train | 25 |
3bedee9173cfd4b6163910c548982ab086ddefec | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LoginPageLayoutConfiguration()",
"from .layout_template_type import LayoutTemplateType\nfrom .layout_template_type import LayoutTemplateType\nfields: Dict[str, Callable[[Any], None]] = {'isFooterShown': lambda n: setattr(self, 'is_foot... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LoginPageLayoutConfiguration()
<|end_body_0|>
<|body_start_1|>
from .layout_template_type import LayoutTemplateType
from .layout_template_type import LayoutTemplateType
fields: D... | LoginPageLayoutConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginPageLayoutConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LoginPageLayoutConfiguration:
"""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... | stack_v2_sparse_classes_10k_train_002203 | 3,646 | 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: LoginPageLayoutConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_disc... | 3 | null | Implement the Python class `LoginPageLayoutConfiguration` described below.
Class description:
Implement the LoginPageLayoutConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LoginPageLayoutConfiguration: Creates a new instance of the a... | Implement the Python class `LoginPageLayoutConfiguration` described below.
Class description:
Implement the LoginPageLayoutConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LoginPageLayoutConfiguration: Creates a new instance of the a... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LoginPageLayoutConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LoginPageLayoutConfiguration:
"""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... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoginPageLayoutConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LoginPageLayoutConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | the_stack_v2_python_sparse | msgraph/generated/models/login_page_layout_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
99c3c1b966c4f3037e7b35909ea5c5a885bf9c03 | [
"session = DBSession()\nsession.merge(trans)\nsession.commit()\nsession.close()",
"session = DBSession()\nfilterList = []\nif 'trans_id' in kwargs:\n _trans_id = kwargs['trans_id']\n filterList.append(Trans.contract_type == _trans_id)\nif 'ex_trans_ids' in kwargs:\n _ex_trans_ids = f\"({kwargs['ex_trans_... | <|body_start_0|>
session = DBSession()
session.merge(trans)
session.commit()
session.close()
<|end_body_0|>
<|body_start_1|>
session = DBSession()
filterList = []
if 'trans_id' in kwargs:
_trans_id = kwargs['trans_id']
filterList.append(Tr... | 交易model类 | Trans | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trans:
"""交易model类"""
def save(trans):
"""新加/修改交易表 :param trans: :return:"""
<|body_0|>
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
session = DBSession()
session.merge(tr... | stack_v2_sparse_classes_10k_train_002204 | 8,115 | no_license | [
{
"docstring": "新加/修改交易表 :param trans: :return:",
"name": "save",
"signature": "def save(trans)"
},
{
"docstring": "新加/修改交易表 :param trans: :return:",
"name": "select",
"signature": "def select(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005570 | Implement the Python class `Trans` described below.
Class description:
交易model类
Method signatures and docstrings:
- def save(trans): 新加/修改交易表 :param trans: :return:
- def select(self, **kwargs): 新加/修改交易表 :param trans: :return: | Implement the Python class `Trans` described below.
Class description:
交易model类
Method signatures and docstrings:
- def save(trans): 新加/修改交易表 :param trans: :return:
- def select(self, **kwargs): 新加/修改交易表 :param trans: :return:
<|skeleton|>
class Trans:
"""交易model类"""
def save(trans):
"""新加/修改交易表 :pa... | 1bc744a6d331b4b733f6b6658b8310eb0c30524e | <|skeleton|>
class Trans:
"""交易model类"""
def save(trans):
"""新加/修改交易表 :param trans: :return:"""
<|body_0|>
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Trans:
"""交易model类"""
def save(trans):
"""新加/修改交易表 :param trans: :return:"""
session = DBSession()
session.merge(trans)
session.commit()
session.close()
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
session = DBSession()
... | the_stack_v2_python_sparse | investment/transaction/models.py | cliicy/vtrade | train | 0 |
7a02d49108d79b2075ab25f1edbb3626dee48182 | [
"super().__init__(parent)\nself.hold = hold\nself.color = color\nself.items = items\nself.initUi()",
"layout = QGridLayout()\nwidth = 100\nheight = 40\nroundness = 20\nstyle = '\\n QLabel {\\n color: white;\\n font-weight: bold;\\n font-size: 15pt;\\n ... | <|body_start_0|>
super().__init__(parent)
self.hold = hold
self.color = color
self.items = items
self.initUi()
<|end_body_0|>
<|body_start_1|>
layout = QGridLayout()
width = 100
height = 40
roundness = 20
style = '\n QLabel {\n ... | Food Menu widget. | Menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Food Menu widget."""
def __init__(self, items, color, parent, hold=None):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(parent)
self.hold = hold
se... | stack_v2_sparse_classes_10k_train_002205 | 2,585 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, items, color, parent, hold=None)"
},
{
"docstring": "Ui Setup.",
"name": "initUi",
"signature": "def initUi(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003646 | Implement the Python class `Menu` described below.
Class description:
Food Menu widget.
Method signatures and docstrings:
- def __init__(self, items, color, parent, hold=None): Init.
- def initUi(self): Ui Setup. | Implement the Python class `Menu` described below.
Class description:
Food Menu widget.
Method signatures and docstrings:
- def __init__(self, items, color, parent, hold=None): Init.
- def initUi(self): Ui Setup.
<|skeleton|>
class Menu:
"""Food Menu widget."""
def __init__(self, items, color, parent, hold=... | a5d18593e689123cac34af552628ed2818ca5d59 | <|skeleton|>
class Menu:
"""Food Menu widget."""
def __init__(self, items, color, parent, hold=None):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Menu:
"""Food Menu widget."""
def __init__(self, items, color, parent, hold=None):
"""Init."""
super().__init__(parent)
self.hold = hold
self.color = color
self.items = items
self.initUi()
def initUi(self):
"""Ui Setup."""
layout = QGri... | the_stack_v2_python_sparse | Menu.py | edgary777/lonchepos | train | 0 |
14ab87d8c52996b15862b001650183b42ab08eea | [
"if num // 10 == 0:\n return num\nr = 0\nwhile num // 10 != 0:\n r += num % 10\n num = num // 10\nreturn self.addDigits(r + num)",
"while num // 10 != 0:\n r = 0\n while num // 10 != 0:\n r += num % 10\n num = num // 10\n num = r + num\nreturn num"
] | <|body_start_0|>
if num // 10 == 0:
return num
r = 0
while num // 10 != 0:
r += num % 10
num = num // 10
return self.addDigits(r + num)
<|end_body_0|>
<|body_start_1|>
while num // 10 != 0:
r = 0
while num // 10 != 0:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addDigits(self, num: int) -> int:
"""DFS : 36 ms"""
<|body_0|>
def addDigits(self, num):
"""recursion: 32 ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num // 10 == 0:
return num
r = 0
while num // 1... | stack_v2_sparse_classes_10k_train_002206 | 1,369 | permissive | [
{
"docstring": "DFS : 36 ms",
"name": "addDigits",
"signature": "def addDigits(self, num: int) -> int"
},
{
"docstring": "recursion: 32 ms",
"name": "addDigits",
"signature": "def addDigits(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addDigits(self, num: int) -> int: DFS : 36 ms
- def addDigits(self, num): recursion: 32 ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addDigits(self, num: int) -> int: DFS : 36 ms
- def addDigits(self, num): recursion: 32 ms
<|skeleton|>
class Solution:
def addDigits(self, num: int) -> int:
""... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class Solution:
def addDigits(self, num: int) -> int:
"""DFS : 36 ms"""
<|body_0|>
def addDigits(self, num):
"""recursion: 32 ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def addDigits(self, num: int) -> int:
"""DFS : 36 ms"""
if num // 10 == 0:
return num
r = 0
while num // 10 != 0:
r += num % 10
num = num // 10
return self.addDigits(r + num)
def addDigits(self, num):
"""recursi... | the_stack_v2_python_sparse | src/258.add-digits.py | wisesky/LeetCode-Practice | train | 0 | |
8c543d33c6500bdd96f6404b8fd23c2a8caf78dc | [
"self.lowest_new_price = lowest_new_price\nself.lowest_used_price = lowest_used_price\nself.lowest_collectible_price = lowest_collectible_price\nself.lowest_refurbished_price = lowest_refurbished_price\nself.total_new = total_new\nself.total_used = total_used\nself.total_collectible = total_collectible\nself.total_... | <|body_start_0|>
self.lowest_new_price = lowest_new_price
self.lowest_used_price = lowest_used_price
self.lowest_collectible_price = lowest_collectible_price
self.lowest_refurbished_price = lowest_refurbished_price
self.total_new = total_new
self.total_used = total_used
... | Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbished_price (Price): TODO: type descriptio... | OfferSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfferSummary:
"""Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbis... | stack_v2_sparse_classes_10k_train_002207 | 4,010 | permissive | [
{
"docstring": "Constructor for the OfferSummary class",
"name": "__init__",
"signature": "def __init__(self, lowest_new_price=None, lowest_used_price=None, lowest_collectible_price=None, lowest_refurbished_price=None, total_new=None, total_used=None, total_collectible=None, total_refurbished=None)"
}... | 2 | stack_v2_sparse_classes_30k_train_006769 | Implement the Python class `OfferSummary` described below.
Class description:
Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO:... | Implement the Python class `OfferSummary` described below.
Class description:
Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO:... | 26ea1019115a1de3b1b37a4b830525e164ac55ce | <|skeleton|>
class OfferSummary:
"""Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OfferSummary:
"""Implementation of the 'OfferSummary' model. TODO: type model description here. Attributes: lowest_new_price (Price): TODO: type description here. lowest_used_price (Price): TODO: type description here. lowest_collectible_price (Price): TODO: type description here. lowest_refurbished_price (Pr... | the_stack_v2_python_sparse | awsecommerceservice/models/offer_summary.py | nidaizamir/Test-PY | train | 0 |
b2530147f2e24cfc0f6131f19773a863275754e5 | [
"super(Encoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, self.dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for m in range(self.N)]\nself.dropout = tf.keras.layers.Dropout(dr... | <|body_start_0|>
super(Encoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, self.dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for m in ra... | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class Constructor param:: :N: number of blocks in the encoder param:: dm: dimensionality of the model param:: h: number of heads param:: hidden: number of hidden units in the fully connected layer ... | stack_v2_sparse_classes_10k_train_002208 | 2,487 | no_license | [
{
"docstring": "Class Constructor param:: :N: number of blocks in the encoder param:: dm: dimensionality of the model param:: h: number of heads param:: hidden: number of hidden units in the fully connected layer param:: input_vocab: size of the input vocabulary param:: max_seq_len: maximum sequence length poss... | 2 | stack_v2_sparse_classes_30k_train_003177 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class Constructor param:: :N: number of blocks in the encoder param:: dm: dimensionality of the model... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class Constructor param:: :N: number of blocks in the encoder param:: dm: dimensionality of the model... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class Encoder:
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class Constructor param:: :N: number of blocks in the encoder param:: dm: dimensionality of the model param:: h: number of heads param:: hidden: number of hidden units in the fully connected layer ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class Constructor param:: :N: number of blocks in the encoder param:: dm: dimensionality of the model param:: h: number of heads param:: hidden: number of hidden units in the fully connected layer param:: input_... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/9-transformer_encoder.py | DracoMindz/holbertonschool-machine_learning | train | 2 | |
ae5cbd882c78ebb5413b5c645474fa006abb3c63 | [
"model = MEGNet(n_node_features=n_node_features, n_edge_features=n_edge_features, n_global_features=n_global_features, n_blocks=n_blocks, is_undirected=is_undirected, residual_connection=residual_connection, mode=mode, n_classes=n_classes, n_tasks=n_tasks)\nif mode == 'regression':\n loss: Loss = L2Loss()\n o... | <|body_start_0|>
model = MEGNet(n_node_features=n_node_features, n_edge_features=n_edge_features, n_global_features=n_global_features, n_blocks=n_blocks, is_undirected=is_undirected, residual_connection=residual_connection, mode=mode, n_classes=n_classes, n_tasks=n_tasks)
if mode == 'regression':
... | MatErials Graph Network for Molecules and Crystals MatErials Graph Network [1]_ are Graph Networks [2]_ which are used for property prediction in molecules and crystals. The model implements multiple layers of Graph Network as MEGNetBlocks and then combines the node properties and edge properties of all nodes and edges... | MEGNetModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MEGNetModel:
"""MatErials Graph Network for Molecules and Crystals MatErials Graph Network [1]_ are Graph Networks [2]_ which are used for property prediction in molecules and crystals. The model implements multiple layers of Graph Network as MEGNetBlocks and then combines the node properties and... | stack_v2_sparse_classes_10k_train_002209 | 11,170 | permissive | [
{
"docstring": "Parameters ---------- n_node_features: int Number of features in a node n_edge_features: int Number of features in a edge n_global_features: int Number of global features n_blocks: int Number of GraphNetworks block to use in update is_undirected: bool, optional (default True) True when the model... | 2 | null | Implement the Python class `MEGNetModel` described below.
Class description:
MatErials Graph Network for Molecules and Crystals MatErials Graph Network [1]_ are Graph Networks [2]_ which are used for property prediction in molecules and crystals. The model implements multiple layers of Graph Network as MEGNetBlocks an... | Implement the Python class `MEGNetModel` described below.
Class description:
MatErials Graph Network for Molecules and Crystals MatErials Graph Network [1]_ are Graph Networks [2]_ which are used for property prediction in molecules and crystals. The model implements multiple layers of Graph Network as MEGNetBlocks an... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class MEGNetModel:
"""MatErials Graph Network for Molecules and Crystals MatErials Graph Network [1]_ are Graph Networks [2]_ which are used for property prediction in molecules and crystals. The model implements multiple layers of Graph Network as MEGNetBlocks and then combines the node properties and... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MEGNetModel:
"""MatErials Graph Network for Molecules and Crystals MatErials Graph Network [1]_ are Graph Networks [2]_ which are used for property prediction in molecules and crystals. The model implements multiple layers of Graph Network as MEGNetBlocks and then combines the node properties and edge propert... | the_stack_v2_python_sparse | deepchem/models/torch_models/megnet.py | deepchem/deepchem | train | 4,876 |
6f9cfaca5979ec78138348407f71106617c4e796 | [
"kwargs = super().get_form_kwargs()\nkwargs.update({'camp': self.camp})\nreturn kwargs",
"speaker = form.save()\nsave_speaker_availability(form, obj=speaker)\nmessages.success(self.request, 'Speaker has been updated')\nreturn redirect(reverse('backoffice:speaker_detail', kwargs={'camp_slug': self.camp.slug, 'slug... | <|body_start_0|>
kwargs = super().get_form_kwargs()
kwargs.update({'camp': self.camp})
return kwargs
<|end_body_0|>
<|body_start_1|>
speaker = form.save()
save_speaker_availability(form, obj=speaker)
messages.success(self.request, 'Speaker has been updated')
retu... | This view is used by the Content Team to update Speaker objects | SpeakerUpdateView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeakerUpdateView:
"""This view is used by the Content Team to update Speaker objects"""
def get_form_kwargs(self):
"""Set camp for the form"""
<|body_0|>
def form_valid(self, form):
"""Save object and availability"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_002210 | 33,145 | permissive | [
{
"docstring": "Set camp for the form",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Save object and availability",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | null | Implement the Python class `SpeakerUpdateView` described below.
Class description:
This view is used by the Content Team to update Speaker objects
Method signatures and docstrings:
- def get_form_kwargs(self): Set camp for the form
- def form_valid(self, form): Save object and availability | Implement the Python class `SpeakerUpdateView` described below.
Class description:
This view is used by the Content Team to update Speaker objects
Method signatures and docstrings:
- def get_form_kwargs(self): Set camp for the form
- def form_valid(self, form): Save object and availability
<|skeleton|>
class Speaker... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class SpeakerUpdateView:
"""This view is used by the Content Team to update Speaker objects"""
def get_form_kwargs(self):
"""Set camp for the form"""
<|body_0|>
def form_valid(self, form):
"""Save object and availability"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpeakerUpdateView:
"""This view is used by the Content Team to update Speaker objects"""
def get_form_kwargs(self):
"""Set camp for the form"""
kwargs = super().get_form_kwargs()
kwargs.update({'camp': self.camp})
return kwargs
def form_valid(self, form):
"""S... | the_stack_v2_python_sparse | src/backoffice/views/program.py | bornhack/bornhack-website | train | 9 |
c7343e36430c63026d8a3c6cd5fe11726cb84ca3 | [
"pm_operations = ('suspend', 'hibernate', 'poweroff', 'reboot')\ndescription = 'Run power management operation as many times as needed'\nepilog = 'Unknown arguments will be passed to the underlying command: pm-suspend, pm-hibernate, poweroff or reboot.'\nparser = ArgumentParser(description=description, epilog=epilo... | <|body_start_0|>
pm_operations = ('suspend', 'hibernate', 'poweroff', 'reboot')
description = 'Run power management operation as many times as needed'
epilog = 'Unknown arguments will be passed to the underlying command: pm-suspend, pm-hibernate, poweroff or reboot.'
parser = ArgumentPar... | Command-line argument parser | MyArgumentParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyArgumentParser:
"""Command-line argument parser"""
def __init__(self):
"""Create parser object"""
<|body_0|>
def parse(self):
"""Parse command-line arguments"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pm_operations = ('suspend', 'hibernat... | stack_v2_sparse_classes_10k_train_002211 | 33,067 | permissive | [
{
"docstring": "Create parser object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parse command-line arguments",
"name": "parse",
"signature": "def parse(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002359 | Implement the Python class `MyArgumentParser` described below.
Class description:
Command-line argument parser
Method signatures and docstrings:
- def __init__(self): Create parser object
- def parse(self): Parse command-line arguments | Implement the Python class `MyArgumentParser` described below.
Class description:
Command-line argument parser
Method signatures and docstrings:
- def __init__(self): Create parser object
- def parse(self): Parse command-line arguments
<|skeleton|>
class MyArgumentParser:
"""Command-line argument parser"""
... | 40ceac081f5181d01e188a5a1c40463d891203e6 | <|skeleton|>
class MyArgumentParser:
"""Command-line argument parser"""
def __init__(self):
"""Create parser object"""
<|body_0|>
def parse(self):
"""Parse command-line arguments"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyArgumentParser:
"""Command-line argument parser"""
def __init__(self):
"""Create parser object"""
pm_operations = ('suspend', 'hibernate', 'poweroff', 'reboot')
description = 'Run power management operation as many times as needed'
epilog = 'Unknown arguments will be pas... | the_stack_v2_python_sparse | work/pm.py | sebastian-code/ideas_sueltas | train | 0 |
1684678b68165a0fd8dd055be58b2f53e1faa4ad | [
"fit_params = {}\nmodel_params = {}\nfor k, v in params.items():\n if k in self.independent_vars or k in ['weights', 'method', 'scale_covar', 'iter_cb']:\n fit_params[k] = v\n else:\n model_params[k] = v\np = self.make_params(**model_params)\nfit = lmfit.Model.fit(self, data, params=p, **fit_par... | <|body_start_0|>
fit_params = {}
model_params = {}
for k, v in params.items():
if k in self.independent_vars or k in ['weights', 'method', 'scale_covar', 'iter_cb']:
fit_params[k] = v
else:
model_params[k] = v
p = self.make_params(*... | Simple extension of lmfit.Model that allows one-line fitting. Example uses: # single exponential fit:: fit = expfitting.Exp1.fit(data, x=time_vals, xoffset=(0, 'fixed'), yoffset=(yoff_guess, -120, 0), amp=(amp_guess, 0, 50), tau=(tau_guess, 0.1, 50)) # plot the fit:: fit_curve = fit.eval() plot(time_vals, fit_curve) # ... | FitModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitModel:
"""Simple extension of lmfit.Model that allows one-line fitting. Example uses: # single exponential fit:: fit = expfitting.Exp1.fit(data, x=time_vals, xoffset=(0, 'fixed'), yoffset=(yoff_guess, -120, 0), amp=(amp_guess, 0, 50), tau=(tau_guess, 0.1, 50)) # plot the fit:: fit_curve = fit.... | stack_v2_sparse_classes_10k_train_002212 | 6,827 | permissive | [
{
"docstring": "Return a fit of data to this model. Parameters ---------- data : array dependent data to fit interactive : bool If True, show a GUI used for interactively exploring fit parameters Extra keyword arguments are passed to make_params() if they are model parameter names, or passed directly to Model.f... | 3 | stack_v2_sparse_classes_30k_train_001610 | Implement the Python class `FitModel` described below.
Class description:
Simple extension of lmfit.Model that allows one-line fitting. Example uses: # single exponential fit:: fit = expfitting.Exp1.fit(data, x=time_vals, xoffset=(0, 'fixed'), yoffset=(yoff_guess, -120, 0), amp=(amp_guess, 0, 50), tau=(tau_guess, 0.1,... | Implement the Python class `FitModel` described below.
Class description:
Simple extension of lmfit.Model that allows one-line fitting. Example uses: # single exponential fit:: fit = expfitting.Exp1.fit(data, x=time_vals, xoffset=(0, 'fixed'), yoffset=(yoff_guess, -120, 0), amp=(amp_guess, 0, 50), tau=(tau_guess, 0.1,... | ff705f650e765142775f4ae0e3c3159e30af8944 | <|skeleton|>
class FitModel:
"""Simple extension of lmfit.Model that allows one-line fitting. Example uses: # single exponential fit:: fit = expfitting.Exp1.fit(data, x=time_vals, xoffset=(0, 'fixed'), yoffset=(yoff_guess, -120, 0), amp=(amp_guess, 0, 50), tau=(tau_guess, 0.1, 50)) # plot the fit:: fit_curve = fit.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FitModel:
"""Simple extension of lmfit.Model that allows one-line fitting. Example uses: # single exponential fit:: fit = expfitting.Exp1.fit(data, x=time_vals, xoffset=(0, 'fixed'), yoffset=(yoff_guess, -120, 0), amp=(amp_guess, 0, 50), tau=(tau_guess, 0.1, 50)) # plot the fit:: fit_curve = fit.eval() plot(t... | the_stack_v2_python_sparse | cnmodel/util/fitting.py | cnmodel/cnmodel | train | 10 |
ece8ece4f75df2572e803e9bffc890bb4a9f6073 | [
"val = round_decimal(val=3.4, places=5, roundfactor=0.5, normalize=True)\nself.assertEqual(val, Decimal('3.5'))\nval = round_decimal(val=3.4, places=5, roundfactor=-0.5, normalize=True)\nself.assertEqual(val, Decimal('3'))\nval = round_decimal(val=0, places=5, roundfactor=-0.5, normalize=False)\nself.assertEqual(va... | <|body_start_0|>
val = round_decimal(val=3.4, places=5, roundfactor=0.5, normalize=True)
self.assertEqual(val, Decimal('3.5'))
val = round_decimal(val=3.4, places=5, roundfactor=-0.5, normalize=True)
self.assertEqual(val, Decimal('3'))
val = round_decimal(val=0, places=5, roundfa... | TestRoundedDecimals | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRoundedDecimals:
def testRoundingDecimals(self):
"""Test Partial Unit Rounding Decimal Conversion behavior"""
<|body_0|>
def testTruncDecimal(self):
"""Test trunc_decimal's rounding behavior."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
val =... | stack_v2_sparse_classes_10k_train_002213 | 3,005 | permissive | [
{
"docstring": "Test Partial Unit Rounding Decimal Conversion behavior",
"name": "testRoundingDecimals",
"signature": "def testRoundingDecimals(self)"
},
{
"docstring": "Test trunc_decimal's rounding behavior.",
"name": "testTruncDecimal",
"signature": "def testTruncDecimal(self)"
}
] | 2 | null | Implement the Python class `TestRoundedDecimals` described below.
Class description:
Implement the TestRoundedDecimals class.
Method signatures and docstrings:
- def testRoundingDecimals(self): Test Partial Unit Rounding Decimal Conversion behavior
- def testTruncDecimal(self): Test trunc_decimal's rounding behavior. | Implement the Python class `TestRoundedDecimals` described below.
Class description:
Implement the TestRoundedDecimals class.
Method signatures and docstrings:
- def testRoundingDecimals(self): Test Partial Unit Rounding Decimal Conversion behavior
- def testTruncDecimal(self): Test trunc_decimal's rounding behavior.... | cd8ce63fdb94f1a7cf095a79edfb8350d0ea2938 | <|skeleton|>
class TestRoundedDecimals:
def testRoundingDecimals(self):
"""Test Partial Unit Rounding Decimal Conversion behavior"""
<|body_0|>
def testTruncDecimal(self):
"""Test trunc_decimal's rounding behavior."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestRoundedDecimals:
def testRoundingDecimals(self):
"""Test Partial Unit Rounding Decimal Conversion behavior"""
val = round_decimal(val=3.4, places=5, roundfactor=0.5, normalize=True)
self.assertEqual(val, Decimal('3.5'))
val = round_decimal(val=3.4, places=5, roundfactor=-0.... | the_stack_v2_python_sparse | satchmo/apps/satchmo_utils/tests.py | twidi/satchmo | train | 2 | |
ebe80767ea33ac0f78a5127e9a7a4a799da4957c | [
"self.data = list()\nself.data_len = 0\nself.start_idx = -1\nself.size = size\nself.average = None",
"self.data.append(val)\nself.data_len += 1\nprint(self.data_len, val, self.start_idx, self.size)\nif self.data_len <= self.size:\n if self.data_len == 1:\n self.average = self.data[0]\n else:\n ... | <|body_start_0|>
self.data = list()
self.data_len = 0
self.start_idx = -1
self.size = size
self.average = None
<|end_body_0|>
<|body_start_1|>
self.data.append(val)
self.data_len += 1
print(self.data_len, val, self.start_idx, self.size)
if self.da... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.data = list()
self.data_... | stack_v2_sparse_classes_10k_train_002214 | 1,298 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001777 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 5e48a72a20456d5c6ecbefe776a1c5e08d2c7e46 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.data = list()
self.data_len = 0
self.start_idx = -1
self.size = size
self.average = None
def next(self, val):
""":type val: int :rtype: float"""... | the_stack_v2_python_sparse | code_bases/python_coding_practice/moving_average.py | sgarg87/sahilgarg.github.io | train | 0 | |
3ed8ac44356e6851334db0d09f2395d2ed4f7d1c | [
"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... | ClaraServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClaraServicer:
def Stop(self, request, context):
"""Requests the termination of Clara Platform Server and associated resource cleanup."""
<|body_0|>
def Utilization(self, request, context):
"""Requests utilization data for all Clara Platform managed GPUs."""
... | stack_v2_sparse_classes_10k_train_002215 | 4,175 | permissive | [
{
"docstring": "Requests the termination of Clara Platform Server and associated resource cleanup.",
"name": "Stop",
"signature": "def Stop(self, request, context)"
},
{
"docstring": "Requests utilization data for all Clara Platform managed GPUs.",
"name": "Utilization",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_000673 | Implement the Python class `ClaraServicer` described below.
Class description:
Implement the ClaraServicer class.
Method signatures and docstrings:
- def Stop(self, request, context): Requests the termination of Clara Platform Server and associated resource cleanup.
- def Utilization(self, request, context): Requests... | Implement the Python class `ClaraServicer` described below.
Class description:
Implement the ClaraServicer class.
Method signatures and docstrings:
- def Stop(self, request, context): Requests the termination of Clara Platform Server and associated resource cleanup.
- def Utilization(self, request, context): Requests... | 0d2e328f238bbbe127023bc834e12811df6f4a27 | <|skeleton|>
class ClaraServicer:
def Stop(self, request, context):
"""Requests the termination of Clara Platform Server and associated resource cleanup."""
<|body_0|>
def Utilization(self, request, context):
"""Requests utilization data for all Clara Platform managed GPUs."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClaraServicer:
def Stop(self, request, context):
"""Requests the termination of Clara Platform Server and associated resource cleanup."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not impleme... | the_stack_v2_python_sparse | nvidia_clara/grpc/clara_pb2_grpc.py | DeepHiveMind/clara-platform-python-client | train | 2 | |
00aebdf3dfd86c7ea7580ca6118a1db55fb135ab | [
"self.a, self.b, self.c = 3 * [-1.0]\nself._func = lambda t, a, b, c: a * np.exp(b * t) + c\nself._fit_func = lambda t: self.a * np.exp(self.b * t) + self.c\nself._fitted = False",
"b_0 = y[-1] / y[-2]\na_0 = 0.1\nc_0 = 0\nguess = np.asarray([a_0, b_0, c_0], dtype=float)\ntry:\n popt = scipy.optimize.curve_fit... | <|body_start_0|>
self.a, self.b, self.c = 3 * [-1.0]
self._func = lambda t, a, b, c: a * np.exp(b * t) + c
self._fit_func = lambda t: self.a * np.exp(self.b * t) + self.c
self._fitted = False
<|end_body_0|>
<|body_start_1|>
b_0 = y[-1] / y[-2]
a_0 = 0.1
c_0 = 0
... | Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data. | TSExp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSExp:
"""Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data."""
def __init__(self):
"""Init an exponential forecasting model."""
<|body_0|>
def fit... | stack_v2_sparse_classes_10k_train_002216 | 12,299 | permissive | [
{
"docstring": "Init an exponential forecasting model.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Fit the exponential forecasting model.",
"name": "fit",
"signature": "def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSExp'"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_003869 | Implement the Python class `TSExp` described below.
Class description:
Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data.
Method signatures and docstrings:
- def __init__(self): Init an exponent... | Implement the Python class `TSExp` described below.
Class description:
Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data.
Method signatures and docstrings:
- def __init__(self): Init an exponent... | 61cc1f63fa055c7466151cfefa7baff8df1702b7 | <|skeleton|>
class TSExp:
"""Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data."""
def __init__(self):
"""Init an exponential forecasting model."""
<|body_0|>
def fit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TSExp:
"""Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data."""
def __init__(self):
"""Init an exponential forecasting model."""
self.a, self.b, self.c = 3 * [-1.0]
... | the_stack_v2_python_sparse | tspymfe/_models.py | FelSiq/ts-pymfe | train | 9 |
4d0d5dc246acb98ec8ff66aab128b93e51689209 | [
"super(SaliencyMapMethod, self).__init__(model, sess, dtypestr, **kwargs)\nself.feedable_kwargs = ('y_target',)\nself.structural_kwargs = ['theta', 'gamma', 'clip_max', 'clip_min', 'symbolic_impl']",
"assert self.parse_params(**kwargs)\nif self.symbolic_impl:\n if self.y_target is None:\n from random im... | <|body_start_0|>
super(SaliencyMapMethod, self).__init__(model, sess, dtypestr, **kwargs)
self.feedable_kwargs = ('y_target',)
self.structural_kwargs = ['theta', 'gamma', 'clip_max', 'clip_min', 'symbolic_impl']
<|end_body_0|>
<|body_start_1|>
assert self.parse_params(**kwargs)
... | The Jacobian-based Saliency Map Method (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf :param model: cleverhans.model.Model :param sess: optional tf.Session :param dtypestr: dtype of the data :param kwargs: passed through to super constructor :note: When not using symbolic implementation in `ge... | SaliencyMapMethod | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaliencyMapMethod:
"""The Jacobian-based Saliency Map Method (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf :param model: cleverhans.model.Model :param sess: optional tf.Session :param dtypestr: dtype of the data :param kwargs: passed through to super constructor :note: ... | stack_v2_sparse_classes_10k_train_002217 | 10,071 | permissive | [
{
"docstring": "Create a SaliencyMapMethod instance. Note: the model parameter should be an instance of the cleverhans.model.Model abstraction provided by CleverHans.",
"name": "__init__",
"signature": "def __init__(self, model, sess=None, dtypestr='float32', **kwargs)"
},
{
"docstring": "Genera... | 3 | stack_v2_sparse_classes_30k_train_005991 | Implement the Python class `SaliencyMapMethod` described below.
Class description:
The Jacobian-based Saliency Map Method (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf :param model: cleverhans.model.Model :param sess: optional tf.Session :param dtypestr: dtype of the data :param kwargs: pass... | Implement the Python class `SaliencyMapMethod` described below.
Class description:
The Jacobian-based Saliency Map Method (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf :param model: cleverhans.model.Model :param sess: optional tf.Session :param dtypestr: dtype of the data :param kwargs: pass... | bbe96757fa7daded0090b1d9a26b9c90d7d87c61 | <|skeleton|>
class SaliencyMapMethod:
"""The Jacobian-based Saliency Map Method (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf :param model: cleverhans.model.Model :param sess: optional tf.Session :param dtypestr: dtype of the data :param kwargs: passed through to super constructor :note: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SaliencyMapMethod:
"""The Jacobian-based Saliency Map Method (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf :param model: cleverhans.model.Model :param sess: optional tf.Session :param dtypestr: dtype of the data :param kwargs: passed through to super constructor :note: When not usin... | the_stack_v2_python_sparse | cleverhans/attacks/saliency_map_method.py | yogeshbalaji/InvGAN | train | 17 |
33aeb53524132e3e81b43fd854f442af1cf8ce2b | [
"super().__init__(*args, **kwargs)\nself._callback_fn = callback_fn\nself._current_task_info = None",
"task_name = task['name']\nif task_name == 'resource':\n return self._callback_fn['deal_with_resource']()\nelif task_name == 'collector_start_task':\n self._current_task_info = task['task_info']\n self._... | <|body_start_0|>
super().__init__(*args, **kwargs)
self._callback_fn = callback_fn
self._current_task_info = None
<|end_body_0|>
<|body_start_1|>
task_name = task['name']
if task_name == 'resource':
return self._callback_fn['deal_with_resource']()
elif task_n... | Overview: A slave, whose master is coordinator. Used to pass message between comm collector and coordinator. Interfaces: __init__, _process_task | CollectorSlave | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectorSlave:
"""Overview: A slave, whose master is coordinator. Used to pass message between comm collector and coordinator. Interfaces: __init__, _process_task"""
def __init__(self, *args, callback_fn: Dict[str, Callable], **kwargs) -> None:
"""Overview: Init callback functions a... | stack_v2_sparse_classes_10k_train_002218 | 8,845 | permissive | [
{
"docstring": "Overview: Init callback functions additionally. Callback functions are methods in comm collector.",
"name": "__init__",
"signature": "def __init__(self, *args, callback_fn: Dict[str, Callable], **kwargs) -> None"
},
{
"docstring": "Overview: Process a task according to input task... | 2 | null | Implement the Python class `CollectorSlave` described below.
Class description:
Overview: A slave, whose master is coordinator. Used to pass message between comm collector and coordinator. Interfaces: __init__, _process_task
Method signatures and docstrings:
- def __init__(self, *args, callback_fn: Dict[str, Callable... | Implement the Python class `CollectorSlave` described below.
Class description:
Overview: A slave, whose master is coordinator. Used to pass message between comm collector and coordinator. Interfaces: __init__, _process_task
Method signatures and docstrings:
- def __init__(self, *args, callback_fn: Dict[str, Callable... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class CollectorSlave:
"""Overview: A slave, whose master is coordinator. Used to pass message between comm collector and coordinator. Interfaces: __init__, _process_task"""
def __init__(self, *args, callback_fn: Dict[str, Callable], **kwargs) -> None:
"""Overview: Init callback functions a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CollectorSlave:
"""Overview: A slave, whose master is coordinator. Used to pass message between comm collector and coordinator. Interfaces: __init__, _process_task"""
def __init__(self, *args, callback_fn: Dict[str, Callable], **kwargs) -> None:
"""Overview: Init callback functions additionally. ... | the_stack_v2_python_sparse | ding/worker/collector/comm/flask_fs_collector.py | shengxuesun/DI-engine | train | 1 |
09d37a4f8d77fdada6b0df5e52594a0c66d6ac12 | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"σ2 = self.sigma_f ** 2\nl2 = self.l ** 2\nsqr_sumx1 = np.sum(X1 ** 2, 1).reshape(-1, 1)\nsqr_sumx2 = np.sum(X2 ** 2, 1)\nsqr_dist = sqr_sumx1 - 2 * np.dot(X1, X2.T) + sqr_sumx2\nkernel = σ2 * np.exp(-0.5... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
σ2 = self.sigma_f ** 2
l2 = self.l ** 2
sqr_sumx1 = np.sum(X1 ** 2, 1).reshape(-1, 1)
sqr_sumx2... | Represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray ... | stack_v2_sparse_classes_10k_train_002219 | 1,540 | no_license | [
{
"docstring": "Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input in X_init l is the length parameter for the kernel ... | 2 | stack_v2_sparse_classes_30k_train_007065 | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampl... | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampl... | bb980395b146c9f4e0d4e9766c4a36f67de70d2e | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray of shape (t, ... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | AndrewKalil/holbertonschool-machine_learning | train | 0 |
bae9d598f6eef893e3b2a64a75527ff65c8217eb | [
"if self.request.params.get('all', ''):\n collection_data = [i.serialize('view') for i in self.context.documents]\nelse:\n collection_data = sorted(dict([(i.id, i.serialize('view')) for i in self.context.documents]).values(), key=lambda i: i['dateModified'])\nreturn {'data': collection_data}",
"document = u... | <|body_start_0|>
if self.request.params.get('all', ''):
collection_data = [i.serialize('view') for i in self.context.documents]
else:
collection_data = sorted(dict([(i.id, i.serialize('view')) for i in self.context.documents]).values(), key=lambda i: i['dateModified'])
re... | TenderQualificationDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenderQualificationDocumentResource:
def collection_get(self):
"""Tender Qualification Documents List"""
<|body_0|>
def collection_post(self):
"""Tender Qualification Document Upload"""
<|body_1|>
def get(self):
"""Tender Qualification Document R... | stack_v2_sparse_classes_10k_train_002220 | 5,238 | permissive | [
{
"docstring": "Tender Qualification Documents List",
"name": "collection_get",
"signature": "def collection_get(self)"
},
{
"docstring": "Tender Qualification Document Upload",
"name": "collection_post",
"signature": "def collection_post(self)"
},
{
"docstring": "Tender Qualific... | 5 | stack_v2_sparse_classes_30k_train_003731 | Implement the Python class `TenderQualificationDocumentResource` described below.
Class description:
Implement the TenderQualificationDocumentResource class.
Method signatures and docstrings:
- def collection_get(self): Tender Qualification Documents List
- def collection_post(self): Tender Qualification Document Upl... | Implement the Python class `TenderQualificationDocumentResource` described below.
Class description:
Implement the TenderQualificationDocumentResource class.
Method signatures and docstrings:
- def collection_get(self): Tender Qualification Documents List
- def collection_post(self): Tender Qualification Document Upl... | 5afdd3a62a8e562cf77e2d963d88f1a26613d16a | <|skeleton|>
class TenderQualificationDocumentResource:
def collection_get(self):
"""Tender Qualification Documents List"""
<|body_0|>
def collection_post(self):
"""Tender Qualification Document Upload"""
<|body_1|>
def get(self):
"""Tender Qualification Document R... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TenderQualificationDocumentResource:
def collection_get(self):
"""Tender Qualification Documents List"""
if self.request.params.get('all', ''):
collection_data = [i.serialize('view') for i in self.context.documents]
else:
collection_data = sorted(dict([(i.id, i.... | the_stack_v2_python_sparse | src/openprocurement/tender/openeu/views/qualification_document.py | pontostroy/api | train | 0 | |
608bb69fed018b3543f702428b642d34a23c2328 | [
"if not os.path.isdir(path + 'birdvox_dcase_20k'):\n print('Creating birdvox_dcase_20k Directory')\n os.mkdir(path + 'birdvox_dcase_20k')\nbase = 'https://zenodo.org/record/1208080/files/'\nfilename = 'BirdVox-DCASE-20k.zip'\nif not os.path.exists(path + 'birdvox_dcase_20k/' + filename):\n url = base + fil... | <|body_start_0|>
if not os.path.isdir(path + 'birdvox_dcase_20k'):
print('Creating birdvox_dcase_20k Directory')
os.mkdir(path + 'birdvox_dcase_20k')
base = 'https://zenodo.org/record/1208080/files/'
filename = 'BirdVox-DCASE-20k.zip'
if not os.path.exists(path + ... | Binary bird detection classification Dataset is 16.5Go compressed. BirdVox-DCASE-20k: a dataset for bird audio detection in 10-second clips Version 2.0, March 2018. Created By Vincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew Farnsworth (1), Steve Kelling (1), and Juan Pablo Bello (2, 3). (1): Cornell Lab of O... | birdvox_dcase_20k | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class birdvox_dcase_20k:
"""Binary bird detection classification Dataset is 16.5Go compressed. BirdVox-DCASE-20k: a dataset for bird audio detection in 10-second clips Version 2.0, March 2018. Created By Vincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew Farnsworth (1), Steve Kelling (1), and J... | stack_v2_sparse_classes_10k_train_002221 | 6,924 | permissive | [
{
"docstring": "Download the Birdvox dataset and store the result into the given path Parameters ---------- path: str the path where the downloaded files will be stored. If the directory does not exist, it is created.",
"name": "download",
"signature": "def download(path)"
},
{
"docstring": "Par... | 2 | stack_v2_sparse_classes_30k_train_002119 | Implement the Python class `birdvox_dcase_20k` described below.
Class description:
Binary bird detection classification Dataset is 16.5Go compressed. BirdVox-DCASE-20k: a dataset for bird audio detection in 10-second clips Version 2.0, March 2018. Created By Vincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew F... | Implement the Python class `birdvox_dcase_20k` described below.
Class description:
Binary bird detection classification Dataset is 16.5Go compressed. BirdVox-DCASE-20k: a dataset for bird audio detection in 10-second clips Version 2.0, March 2018. Created By Vincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew F... | d8778c2eb3254b478cef4f45d934bf921e695619 | <|skeleton|>
class birdvox_dcase_20k:
"""Binary bird detection classification Dataset is 16.5Go compressed. BirdVox-DCASE-20k: a dataset for bird audio detection in 10-second clips Version 2.0, March 2018. Created By Vincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew Farnsworth (1), Steve Kelling (1), and J... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class birdvox_dcase_20k:
"""Binary bird detection classification Dataset is 16.5Go compressed. BirdVox-DCASE-20k: a dataset for bird audio detection in 10-second clips Version 2.0, March 2018. Created By Vincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew Farnsworth (1), Steve Kelling (1), and Juan Pablo Bel... | the_stack_v2_python_sparse | symjax/data/birdvox_dcase_20k.py | SymJAX/SymJAX | train | 52 |
7a88f24954bb02389d332885ac483236a1f6a796 | [
"if user not in self._user_enrollments:\n self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)\nreturn self._user_enrollments[user]",
"field_dictionary = super().field_dictionary(**kwargs)\nif not kwargs.get('user'):\n field_dictionary['course'] = []\nelif not kwargs.get('course_id'):\... | <|body_start_0|>
if user not in self._user_enrollments:
self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)
return self._user_enrollments[user]
<|end_body_0|>
<|body_start_1|>
field_dictionary = super().field_dictionary(**kwargs)
if not kwargs.get('use... | SearchFilterGenerator for LMS Search | LmsSearchFilterGenerator | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
<|body_0|>
def field_dictionary(self, **kwargs):
"""add course if provided otherwise add courses in wh... | stack_v2_sparse_classes_10k_train_002222 | 2,467 | permissive | [
{
"docstring": "Return the specified user's course enrollments",
"name": "_enrollments_for_user",
"signature": "def _enrollments_for_user(self, user)"
},
{
"docstring": "add course if provided otherwise add courses in which the user is enrolled in",
"name": "field_dictionary",
"signature... | 3 | null | Implement the Python class `LmsSearchFilterGenerator` described below.
Class description:
SearchFilterGenerator for LMS Search
Method signatures and docstrings:
- def _enrollments_for_user(self, user): Return the specified user's course enrollments
- def field_dictionary(self, **kwargs): add course if provided otherw... | Implement the Python class `LmsSearchFilterGenerator` described below.
Class description:
SearchFilterGenerator for LMS Search
Method signatures and docstrings:
- def _enrollments_for_user(self, user): Return the specified user's course enrollments
- def field_dictionary(self, **kwargs): add course if provided otherw... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
<|body_0|>
def field_dictionary(self, **kwargs):
"""add course if provided otherwise add courses in wh... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
if user not in self._user_enrollments:
self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)
... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/lib/courseware_search/lms_filter_generator.py | luque/better-ways-of-thinking-about-software | train | 3 |
e082dafc4eb0fad89a239f1636e6556668d91463 | [
"n, m = (len(A), len(B))\ndp = [[0] * (m + 1) for _ in range(n + 1)]\nans = 0\nfor i in range(n - 1, -1, -1):\n for j in range(m - 1, -1, -1):\n dp[i][j] = dp[i + 1][j + 1] + 1 if A[i] == B[j] else 0\n ans = max(dp[i][j], ans)\nreturn ans",
"n, m = (len(A), len(B))\nans = 0\nfor i in range(n):\n ... | <|body_start_0|>
n, m = (len(A), len(B))
dp = [[0] * (m + 1) for _ in range(n + 1)]
ans = 0
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
dp[i][j] = dp[i + 1][j + 1] + 1 if A[i] == B[j] else 0
ans = max(dp[i][j], ans)
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
"""dp解法:状态转移方程 dp[i][j] = dp[i+1][j+1] + 1 因为dp[i][j]是由dp[i+1][j+1]+1得来的 所以我们从后往前遍历 :param A: :param B: :return:"""
<|body_0|>
def findLength2(self, A: List[int], B: List[int]) -> int:
"""暴力法 三重循环 严重超... | stack_v2_sparse_classes_10k_train_002223 | 1,445 | no_license | [
{
"docstring": "dp解法:状态转移方程 dp[i][j] = dp[i+1][j+1] + 1 因为dp[i][j]是由dp[i+1][j+1]+1得来的 所以我们从后往前遍历 :param A: :param B: :return:",
"name": "findLength",
"signature": "def findLength(self, A: List[int], B: List[int]) -> int"
},
{
"docstring": "暴力法 三重循环 严重超时 :param A: :param B: :return:",
"name":... | 2 | stack_v2_sparse_classes_30k_train_007036 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, A: List[int], B: List[int]) -> int: dp解法:状态转移方程 dp[i][j] = dp[i+1][j+1] + 1 因为dp[i][j]是由dp[i+1][j+1]+1得来的 所以我们从后往前遍历 :param A: :param B: :return:
- def findL... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, A: List[int], B: List[int]) -> int: dp解法:状态转移方程 dp[i][j] = dp[i+1][j+1] + 1 因为dp[i][j]是由dp[i+1][j+1]+1得来的 所以我们从后往前遍历 :param A: :param B: :return:
- def findL... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
"""dp解法:状态转移方程 dp[i][j] = dp[i+1][j+1] + 1 因为dp[i][j]是由dp[i+1][j+1]+1得来的 所以我们从后往前遍历 :param A: :param B: :return:"""
<|body_0|>
def findLength2(self, A: List[int], B: List[int]) -> int:
"""暴力法 三重循环 严重超... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
"""dp解法:状态转移方程 dp[i][j] = dp[i+1][j+1] + 1 因为dp[i][j]是由dp[i+1][j+1]+1得来的 所以我们从后往前遍历 :param A: :param B: :return:"""
n, m = (len(A), len(B))
dp = [[0] * (m + 1) for _ in range(n + 1)]
ans = 0
for i in ran... | the_stack_v2_python_sparse | 最长重复子数组.py | cjrzs/MyLeetCode | train | 8 | |
c5f3d11c65c9685c935289e92a611558280d29bd | [
"if not s1 and (not s2):\n return True\nif not s1 or not s2:\n return False\nif len(s1) != len(s2):\n return False\nn = len(s1)\nf = [[[False for _ in range(n)] for _ in range(n)] for _ in range(n + 1)]\nfor i in range(n):\n for j in range(n):\n f[1][i][j] = s1[i] == s2[j]\nfor l in range(1, n + ... | <|body_start_0|>
if not s1 and (not s2):
return True
if not s1 or not s2:
return False
if len(s1) != len(s2):
return False
n = len(s1)
f = [[[False for _ in range(n)] for _ in range(n)] for _ in range(n + 1)]
for i in range(n):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isScramble_DP(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_0|>
def isScramble_TLE(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s1 and (not s2)... | stack_v2_sparse_classes_10k_train_002224 | 1,922 | no_license | [
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "isScramble_DP",
"signature": "def isScramble_DP(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "isScramble_TLE",
"signature": "def isScramble_TLE(self, s1, s2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005824 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isScramble_DP(self, s1, s2): :type s1: str :type s2: str :rtype: bool
- def isScramble_TLE(self, s1, s2): :type s1: str :type s2: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isScramble_DP(self, s1, s2): :type s1: str :type s2: str :rtype: bool
- def isScramble_TLE(self, s1, s2): :type s1: str :type s2: str :rtype: bool
<|skeleton|>
class Solutio... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def isScramble_DP(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_0|>
def isScramble_TLE(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isScramble_DP(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
if not s1 and (not s2):
return True
if not s1 or not s2:
return False
if len(s1) != len(s2):
return False
n = len(s1)
f = [[[False for _... | the_stack_v2_python_sparse | Algorithm/087_Scramble_String.py | Gi1ia/TechNoteBook | train | 7 | |
cc8c544a641c5f9b93e06de114d2b92c0884d917 | [
"self._sub_input_topic = None\nself._sub_output_topic = None\nself._publisher = None\nself._time_received_input = 0\nself.node = node\nself.callback_lock = threading.RLock()",
"try:\n self._publisher = self.node.create_publisher(Int64, publish_topic, qos_profile=QoSProfile(depth=1))\n input_topic_type = get... | <|body_start_0|>
self._sub_input_topic = None
self._sub_output_topic = None
self._publisher = None
self._time_received_input = 0
self.node = node
self.callback_lock = threading.RLock()
<|end_body_0|>
<|body_start_1|>
try:
self._publisher = self.node.c... | The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic. | TimeEstimatorTopic | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeEstimatorTopic:
"""The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic."""
def __init__(self, node):
"""Create a TimeEstimatorTopic ... | stack_v2_sparse_classes_10k_train_002225 | 5,018 | permissive | [
{
"docstring": "Create a TimeEstimatorTopic object. @param node: ROS2 node @type node: rclpy.node.Node",
"name": "__init__",
"signature": "def __init__(self, node)"
},
{
"docstring": "Start the time measurement. @param input_topic: Topic to be listened to start the time measurement @type input_t... | 4 | stack_v2_sparse_classes_30k_train_003167 | Implement the Python class `TimeEstimatorTopic` described below.
Class description:
The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic.
Method signatures and docstrings:... | Implement the Python class `TimeEstimatorTopic` described below.
Class description:
The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic.
Method signatures and docstrings:... | ff8950abbb72366ed3072de790c405de8875ecc3 | <|skeleton|>
class TimeEstimatorTopic:
"""The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic."""
def __init__(self, node):
"""Create a TimeEstimatorTopic ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TimeEstimatorTopic:
"""The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic."""
def __init__(self, node):
"""Create a TimeEstimatorTopic object. @para... | the_stack_v2_python_sparse | src/tools/benchmark_tool/benchmark_tool/time_estimator/time_estimator_topic.py | bytetok/vde | train | 0 |
ce6ea196bc0450ee5d284cee0046a395c36214d6 | [
"self.player = player\nself.team = team\ntry:\n self.page = wikipedia.page(player)\n self.soup = BeautifulSoup(self.page.html())\nexcept wikipedia.exceptions.DisambiguationError as e:\n self._get_correct_page(e.options, team)\nself._gen_table()",
"best_candidate = None\nbest_yob = None\nfor option in opt... | <|body_start_0|>
self.player = player
self.team = team
try:
self.page = wikipedia.page(player)
self.soup = BeautifulSoup(self.page.html())
except wikipedia.exceptions.DisambiguationError as e:
self._get_correct_page(e.options, team)
self._gen_t... | WikipediaPlayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikipediaPlayer:
def __init__(self, player, team):
"""initializes self.page to the correct wikipedia resource"""
<|body_0|>
def _get_correct_page(self, options, team):
"""gets appropiate wikipedia among options considering wether team is in html and age"""
<|... | stack_v2_sparse_classes_10k_train_002226 | 12,481 | permissive | [
{
"docstring": "initializes self.page to the correct wikipedia resource",
"name": "__init__",
"signature": "def __init__(self, player, team)"
},
{
"docstring": "gets appropiate wikipedia among options considering wether team is in html and age",
"name": "_get_correct_page",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_004001 | Implement the Python class `WikipediaPlayer` described below.
Class description:
Implement the WikipediaPlayer class.
Method signatures and docstrings:
- def __init__(self, player, team): initializes self.page to the correct wikipedia resource
- def _get_correct_page(self, options, team): gets appropiate wikipedia am... | Implement the Python class `WikipediaPlayer` described below.
Class description:
Implement the WikipediaPlayer class.
Method signatures and docstrings:
- def __init__(self, player, team): initializes self.page to the correct wikipedia resource
- def _get_correct_page(self, options, team): gets appropiate wikipedia am... | e3951450713f7cfaead070998e1b84d392114283 | <|skeleton|>
class WikipediaPlayer:
def __init__(self, player, team):
"""initializes self.page to the correct wikipedia resource"""
<|body_0|>
def _get_correct_page(self, options, team):
"""gets appropiate wikipedia among options considering wether team is in html and age"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WikipediaPlayer:
def __init__(self, player, team):
"""initializes self.page to the correct wikipedia resource"""
self.player = player
self.team = team
try:
self.page = wikipedia.page(player)
self.soup = BeautifulSoup(self.page.html())
except wiki... | the_stack_v2_python_sparse | basketball_reference/utils.py | nbaprediction/nba_prediction | train | 3 | |
1551cf21b02340673adabca151988a906dc0f1ae | [
"highest_index = len(array) - 1\nHeap.heapify(array, highest_index)\nfor end in range(highest_index, 0, -1):\n array[end], array[0] = (array[0], array[end])\n Heap.sift_down(array, 0, end - 1)",
"first = (highest_index - 1) // 2\nfor start in range(first, -1, -1):\n Heap.sift_down(array, start, highest_i... | <|body_start_0|>
highest_index = len(array) - 1
Heap.heapify(array, highest_index)
for end in range(highest_index, 0, -1):
array[end], array[0] = (array[0], array[end])
Heap.sift_down(array, 0, end - 1)
<|end_body_0|>
<|body_start_1|>
first = (highest_index - 1) ... | Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort | Heap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Heap:
"""Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort"""
def heap_sort(array):
"""A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and ... | stack_v2_sparse_classes_10k_train_002227 | 14,101 | no_license | [
{
"docstring": "A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and sift_down() Inplace: Yes Time complexity: all O(nlogn)",
"name": "heap_sort",
"signature": "def heap_sort(array)"
},
{
... | 3 | stack_v2_sparse_classes_30k_val_000074 | Implement the Python class `Heap` described below.
Class description:
Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort
Method signatures and docstrings:
- def heap_sort(array): A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort... | Implement the Python class `Heap` described below.
Class description:
Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort
Method signatures and docstrings:
- def heap_sort(array): A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort... | c88059dc66297af577ad2b8afa4e0ac0ad622915 | <|skeleton|>
class Heap:
"""Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort"""
def heap_sort(array):
"""A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Heap:
"""Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort"""
def heap_sort(array):
"""A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and sift_down() I... | the_stack_v2_python_sparse | codes/BuildLinks1.02/test_input/sort_codes/pysort.py | DaHuO/Supergraph | train | 2 |
607e7f6af826bb5e869c207cdd888f72a8a1d34d | [
"id = request.GET.get('id', '')\nshare_page_desc = ''\ntry:\n scanlottery = app_models.Scanlottery.objects.get(id=id)\n share_page_desc = scanlottery.name\nexcept:\n pass\nmember = request.member\nis_pc = False if member else True\nthumbnails_url = '/static_v2/img/thumbnails_lottery.png'\nc = RequestContex... | <|body_start_0|>
id = request.GET.get('id', '')
share_page_desc = ''
try:
scanlottery = app_models.Scanlottery.objects.get(id=id)
share_page_desc = scanlottery.name
except:
pass
member = request.member
is_pc = False if member else True
... | Mexlottery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mexlottery:
def get(request):
"""响应GET"""
<|body_0|>
def api_get(request):
"""响应GET"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
id = request.GET.get('id', '')
share_page_desc = ''
try:
scanlottery = app_models.Scanlot... | stack_v2_sparse_classes_10k_train_002228 | 4,367 | no_license | [
{
"docstring": "响应GET",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "响应GET",
"name": "api_get",
"signature": "def api_get(request)"
}
] | 2 | null | Implement the Python class `Mexlottery` described below.
Class description:
Implement the Mexlottery class.
Method signatures and docstrings:
- def get(request): 响应GET
- def api_get(request): 响应GET | Implement the Python class `Mexlottery` described below.
Class description:
Implement the Mexlottery class.
Method signatures and docstrings:
- def get(request): 响应GET
- def api_get(request): 响应GET
<|skeleton|>
class Mexlottery:
def get(request):
"""响应GET"""
<|body_0|>
def api_get(request):... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class Mexlottery:
def get(request):
"""响应GET"""
<|body_0|>
def api_get(request):
"""响应GET"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Mexlottery:
def get(request):
"""响应GET"""
id = request.GET.get('id', '')
share_page_desc = ''
try:
scanlottery = app_models.Scanlottery.objects.get(id=id)
share_page_desc = scanlottery.name
except:
pass
member = request.member... | the_stack_v2_python_sparse | weapp/apps/customerized_apps/scanlottery/m_scanlottery_page.py | chengdg/weizoom | train | 1 | |
2f86dc0783c7165661c461a1fea1fb2376e9e55f | [
"Parametre.__init__(self, 'trouver', 'find')\nself.schema = '<ident_salle>'\nself.aide_courte = 'cherche une route'\nself.aide_longue = \"Cette commande demande au système de chercher le chemin le plus court entre deux salles : la salle d'origine est celle où vous vous trouvez actuellement. La salle de destination ... | <|body_start_0|>
Parametre.__init__(self, 'trouver', 'find')
self.schema = '<ident_salle>'
self.aide_courte = 'cherche une route'
self.aide_longue = "Cette commande demande au système de chercher le chemin le plus court entre deux salles : la salle d'origine est celle où vous vous trouve... | Commande 'route trouver' | PrmTrouver | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmTrouver:
"""Commande 'route trouver'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
P... | stack_v2_sparse_classes_10k_train_002229 | 3,108 | permissive | [
{
"docstring": "Constructeur du paramètre.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande.",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001676 | Implement the Python class `PrmTrouver` described below.
Class description:
Commande 'route trouver'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande. | Implement the Python class `PrmTrouver` described below.
Class description:
Commande 'route trouver'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande.
<|skeleton|>
class PrmTrouver:
"""Command... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmTrouver:
"""Commande 'route trouver'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmTrouver:
"""Commande 'route trouver'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, 'trouver', 'find')
self.schema = '<ident_salle>'
self.aide_courte = 'cherche une route'
self.aide_longue = "Cette commande demande au système de... | the_stack_v2_python_sparse | src/secondaires/route/commandes/route/trouver.py | vincent-lg/tsunami | train | 5 |
0c9925080ff4ff3e11acb75f3631c5e77d82e794 | [
"try:\n jd = jc.load_obj_json('{}')\n jd.dir = baseid\n jd.table = table\n jd.nn_id = nnid\n jd.datadesc = 'Y'\n jd.preprocess = '2'\n netconf.save_format(nnid, str(request.body, 'utf-8'))\n result = netconf.update_network(jd)\n return_data = {'status': '200', 'result': result}\n retur... | <|body_start_0|>
try:
jd = jc.load_obj_json('{}')
jd.dir = baseid
jd.table = table
jd.nn_id = nnid
jd.datadesc = 'Y'
jd.preprocess = '2'
netconf.save_format(nnid, str(request.body, 'utf-8'))
result = netconf.update_n... | 1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/label/{label}/ - post /a... | ImageFileFormat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageFileFormat:
"""1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{... | stack_v2_sparse_classes_10k_train_002230 | 4,138 | no_license | [
{
"docstring": "- desc : create a format data - desc : update data format information <textfield> <font size = 1> { \"x_size\": 100 , \"y_size\": 100 } </font> </textfield> --- parameters: - name: body paramType: body pytype: json",
"name": "post",
"signature": "def post(self, request, baseid, table, nn... | 4 | stack_v2_sparse_classes_30k_train_006727 | Implement the Python class `ImageFileFormat` described below.
Class description:
1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb... | Implement the Python class `ImageFileFormat` described below.
Class description:
1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class ImageFileFormat:
"""1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageFileFormat:
"""1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{baseid}/table... | the_stack_v2_python_sparse | tfmsarest/views/imagefile_format.py | TensorMSA/tensormsa_old | train | 6 |
b3131f38564bfb6dde59c315d852decff05f695d | [
"if not root:\n return 0\nfrom queue import Queue\nq = Queue()\nq.put(root)\nmin_depth = 1\nwhile not q.empty():\n q_size = q.qsize()\n for _ in range(q_size):\n cur = q.get()\n if not cur.right and (not cur.left):\n return min_depth\n for n in [cur.left, cur.right]:\n ... | <|body_start_0|>
if not root:
return 0
from queue import Queue
q = Queue()
q.put(root)
min_depth = 1
while not q.empty():
q_size = q.qsize()
for _ in range(q_size):
cur = q.get()
if not cur.right and (not... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""层次遍历,遇到叶子节点即结束返回当前深度"""
<|body_0|>
def minDepth_dfs(self, root: TreeNode) -> int:
"""DFS解法,遍历整棵树,存储最短路径"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
... | stack_v2_sparse_classes_10k_train_002231 | 2,112 | no_license | [
{
"docstring": "层次遍历,遇到叶子节点即结束返回当前深度",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
},
{
"docstring": "DFS解法,遍历整棵树,存储最短路径",
"name": "minDepth_dfs",
"signature": "def minDepth_dfs(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_004908 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: 层次遍历,遇到叶子节点即结束返回当前深度
- def minDepth_dfs(self, root: TreeNode) -> int: DFS解法,遍历整棵树,存储最短路径 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: 层次遍历,遇到叶子节点即结束返回当前深度
- def minDepth_dfs(self, root: TreeNode) -> int: DFS解法,遍历整棵树,存储最短路径
<|skeleton|>
class Solution:
def minDept... | c9eed637887753eb28d78cf252ea3763231e23a2 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""层次遍历,遇到叶子节点即结束返回当前深度"""
<|body_0|>
def minDepth_dfs(self, root: TreeNode) -> int:
"""DFS解法,遍历整棵树,存储最短路径"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root: TreeNode) -> int:
"""层次遍历,遇到叶子节点即结束返回当前深度"""
if not root:
return 0
from queue import Queue
q = Queue()
q.put(root)
min_depth = 1
while not q.empty():
q_size = q.qsize()
for _ in range... | the_stack_v2_python_sparse | CODE/111. 二叉树的最小深度.py | moshlwx/leetcode | train | 5 | |
7edbd5ec43c9ac6da2d579907204f6252653f8c1 | [
"with open(filename) as runfile:\n data = runfile.read()\ndecoded = json.loads(data)\nreturn cls(**decoded)",
"filename = os.path.join(directory, self.station_id)\nwith open(filename, 'w') as runfile:\n runfile.write(self.AsJSON())\nreturn filename",
"data = self._asdict()\ndata['http_host'] = self.http_h... | <|body_start_0|>
with open(filename) as runfile:
data = runfile.read()
decoded = json.loads(data)
return cls(**decoded)
<|end_body_0|>
<|body_start_1|>
filename = os.path.join(directory, self.station_id)
with open(filename, 'w') as runfile:
runfile.write(... | Encapsulates the run data stored in an openhtf file. | RunData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunData:
"""Encapsulates the run data stored in an openhtf file."""
def FromFile(cls, filename):
"""Creates RunData from a run file."""
<|body_0|>
def SaveToFile(self, directory):
"""Saves this run data to a file, typically in /var/run/openhtf. Args: directory: T... | stack_v2_sparse_classes_10k_train_002232 | 3,099 | permissive | [
{
"docstring": "Creates RunData from a run file.",
"name": "FromFile",
"signature": "def FromFile(cls, filename)"
},
{
"docstring": "Saves this run data to a file, typically in /var/run/openhtf. Args: directory: The directory in which to save this file. Return: The filename of this rundata.",
... | 4 | stack_v2_sparse_classes_30k_train_000565 | Implement the Python class `RunData` described below.
Class description:
Encapsulates the run data stored in an openhtf file.
Method signatures and docstrings:
- def FromFile(cls, filename): Creates RunData from a run file.
- def SaveToFile(self, directory): Saves this run data to a file, typically in /var/run/openht... | Implement the Python class `RunData` described below.
Class description:
Encapsulates the run data stored in an openhtf file.
Method signatures and docstrings:
- def FromFile(cls, filename): Creates RunData from a run file.
- def SaveToFile(self, directory): Saves this run data to a file, typically in /var/run/openht... | bc41fcf0b804530c36cbeccacba5d5b98c5df243 | <|skeleton|>
class RunData:
"""Encapsulates the run data stored in an openhtf file."""
def FromFile(cls, filename):
"""Creates RunData from a run file."""
<|body_0|>
def SaveToFile(self, directory):
"""Saves this run data to a file, typically in /var/run/openhtf. Args: directory: T... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RunData:
"""Encapsulates the run data stored in an openhtf file."""
def FromFile(cls, filename):
"""Creates RunData from a run file."""
with open(filename) as runfile:
data = runfile.read()
decoded = json.loads(data)
return cls(**decoded)
def SaveToFile(se... | the_stack_v2_python_sparse | openhtf/io/rundata.py | googlerhuili/openhtf | train | 1 |
927cfb4caa0cb5d264566bb912be25e92c0a168a | [
"parser.add_argument('metric_name', help='The name of the log-based metric to update.')\nconfig_group = parser.add_argument_group(help='Data about the metric to update.', mutex=True, required=True)\nlegacy_mode_group = config_group.add_argument_group(help='Arguments to specify information about simple counter logs-... | <|body_start_0|>
parser.add_argument('metric_name', help='The name of the log-based metric to update.')
config_group = parser.add_argument_group(help='Data about the metric to update.', mutex=True, required=True)
legacy_mode_group = config_group.add_argument_group(help='Arguments to specify info... | Updates the definition of a logs-based metric. | UpdateBeta | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateBeta:
"""Updates the definition of a logs-based metric."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the argum... | stack_v2_sparse_classes_10k_train_002233 | 7,286 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The updated... | 2 | null | Implement the Python class `UpdateBeta` described below.
Class description:
Updates the definition of a logs-based metric.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse nam... | Implement the Python class `UpdateBeta` described below.
Class description:
Updates the definition of a logs-based metric.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse nam... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class UpdateBeta:
"""Updates the definition of a logs-based metric."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the argum... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateBeta:
"""Updates the definition of a logs-based metric."""
def Args(parser):
"""Register flags for this command."""
parser.add_argument('metric_name', help='The name of the log-based metric to update.')
config_group = parser.add_argument_group(help='Data about the metric to ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/logging/metrics/update.py | bopopescu/socialliteapp | train | 0 |
7d11ffbca1b56700327d9bf296d078a445458f85 | [
"data = get_fetch_result_row_by_id(pk)\nif not data:\n raise NotFound\nresult = marshal(data, fields_item_fetch_result, envelope=structure_key_item)\nreturn jsonify(result)",
"result = delete_fetch_result(pk)\nif result:\n success_msg = SUCCESS_MSG.copy()\n return make_response(jsonify(success_msg), 204)... | <|body_start_0|>
data = get_fetch_result_row_by_id(pk)
if not data:
raise NotFound
result = marshal(data, fields_item_fetch_result, envelope=structure_key_item)
return jsonify(result)
<|end_body_0|>
<|body_start_1|>
result = delete_fetch_result(pk)
if result:... | FetchResultResource | FetchResultResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchResultResource:
"""FetchResultResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:5000/news/fetch_result/1 :param pk: :return:"""
<|body_0|>
def delete(self, pk):
"""Example: curl http://0.0.0.0:5000/news/fetch_result/1 -X DELETE :param pk: :retur... | stack_v2_sparse_classes_10k_train_002234 | 11,580 | permissive | [
{
"docstring": "Example: curl http://0.0.0.0:5000/news/fetch_result/1 :param pk: :return:",
"name": "get",
"signature": "def get(self, pk)"
},
{
"docstring": "Example: curl http://0.0.0.0:5000/news/fetch_result/1 -X DELETE :param pk: :return:",
"name": "delete",
"signature": "def delete(... | 3 | stack_v2_sparse_classes_30k_train_004378 | Implement the Python class `FetchResultResource` described below.
Class description:
FetchResultResource
Method signatures and docstrings:
- def get(self, pk): Example: curl http://0.0.0.0:5000/news/fetch_result/1 :param pk: :return:
- def delete(self, pk): Example: curl http://0.0.0.0:5000/news/fetch_result/1 -X DEL... | Implement the Python class `FetchResultResource` described below.
Class description:
FetchResultResource
Method signatures and docstrings:
- def get(self, pk): Example: curl http://0.0.0.0:5000/news/fetch_result/1 :param pk: :return:
- def delete(self, pk): Example: curl http://0.0.0.0:5000/news/fetch_result/1 -X DEL... | 6ef54f3f7efbbaff6169e963dcf45ab25e11e593 | <|skeleton|>
class FetchResultResource:
"""FetchResultResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:5000/news/fetch_result/1 :param pk: :return:"""
<|body_0|>
def delete(self, pk):
"""Example: curl http://0.0.0.0:5000/news/fetch_result/1 -X DELETE :param pk: :retur... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FetchResultResource:
"""FetchResultResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:5000/news/fetch_result/1 :param pk: :return:"""
data = get_fetch_result_row_by_id(pk)
if not data:
raise NotFound
result = marshal(data, fields_item_fetch_result, ... | the_stack_v2_python_sparse | web_api/news/resources/fetch_result.py | zhanghe06/flask_restful | train | 2 |
e08c8f6be26f584a8d3174e4862ed7a88d85b385 | [
"try:\n logger.info('服务器地址为空的rsever注册测试')\n self.login()\n self.register_rserver('', readconfig.name, readconfig.pwd, readconfig.machineName)\n sleep(3)\n self.assertEqual(self.error_hint(), u'服务器地址不能为空!')\n WebDriverWait(self.driver, 5, 0.5).until(ES.alert_is_present())\n sleep(2)\n self.ac... | <|body_start_0|>
try:
logger.info('服务器地址为空的rsever注册测试')
self.login()
self.register_rserver('', readconfig.name, readconfig.pwd, readconfig.machineName)
sleep(3)
self.assertEqual(self.error_hint(), u'服务器地址不能为空!')
WebDriverWait(self.driver, 5... | 快速配置,rserver注册相关测试 | ConfigureRegisterTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigureRegisterTest:
"""快速配置,rserver注册相关测试"""
def test_register1(self):
"""服务器地址为空的rsever注册测试"""
<|body_0|>
def test_register2(self):
"""服务账号为空的rsever注册测试"""
<|body_1|>
def test_register3(self):
"""服务昵称为空的rsever注册测试"""
<|body_2|>
... | stack_v2_sparse_classes_10k_train_002235 | 4,945 | no_license | [
{
"docstring": "服务器地址为空的rsever注册测试",
"name": "test_register1",
"signature": "def test_register1(self)"
},
{
"docstring": "服务账号为空的rsever注册测试",
"name": "test_register2",
"signature": "def test_register2(self)"
},
{
"docstring": "服务昵称为空的rsever注册测试",
"name": "test_register3",
... | 6 | stack_v2_sparse_classes_30k_test_000211 | Implement the Python class `ConfigureRegisterTest` described below.
Class description:
快速配置,rserver注册相关测试
Method signatures and docstrings:
- def test_register1(self): 服务器地址为空的rsever注册测试
- def test_register2(self): 服务账号为空的rsever注册测试
- def test_register3(self): 服务昵称为空的rsever注册测试
- def test_register4(self): 非白名单的用户注册
-... | Implement the Python class `ConfigureRegisterTest` described below.
Class description:
快速配置,rserver注册相关测试
Method signatures and docstrings:
- def test_register1(self): 服务器地址为空的rsever注册测试
- def test_register2(self): 服务账号为空的rsever注册测试
- def test_register3(self): 服务昵称为空的rsever注册测试
- def test_register4(self): 非白名单的用户注册
-... | fd552eeb47fd4838c2c5caef4deea7480ab75ce9 | <|skeleton|>
class ConfigureRegisterTest:
"""快速配置,rserver注册相关测试"""
def test_register1(self):
"""服务器地址为空的rsever注册测试"""
<|body_0|>
def test_register2(self):
"""服务账号为空的rsever注册测试"""
<|body_1|>
def test_register3(self):
"""服务昵称为空的rsever注册测试"""
<|body_2|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfigureRegisterTest:
"""快速配置,rserver注册相关测试"""
def test_register1(self):
"""服务器地址为空的rsever注册测试"""
try:
logger.info('服务器地址为空的rsever注册测试')
self.login()
self.register_rserver('', readconfig.name, readconfig.pwd, readconfig.machineName)
sleep(3... | the_stack_v2_python_sparse | test_case/A003_configure_register_test.py | luhuifnag/AVA_UIauto_test | train | 0 |
77bbc498738c8174c74f106afa9b877bffd16016 | [
"self.key = aKey\nself.crc = 0\nfor x in self.key:\n intX = ord(x)\n self.crc = self.crc ^ intX",
"kIdx = 0\ncryptStr = ''\nfor x in range(len(aString)):\n cryptStr = cryptStr + chr(ord(aString[x]) ^ ord(self.key[kIdx]))\n kIdx = (kIdx + 1) % len(self.key)\nreturn cryptStr"
] | <|body_start_0|>
self.key = aKey
self.crc = 0
for x in self.key:
intX = ord(x)
self.crc = self.crc ^ intX
<|end_body_0|>
<|body_start_1|>
kIdx = 0
cryptStr = ''
for x in range(len(aString)):
cryptStr = cryptStr + chr(ord(aString[x]) ^ ... | PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string. | PEcrypt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PEcrypt:
"""PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string."""
... | stack_v2_sparse_classes_10k_train_002236 | 3,796 | no_license | [
{
"docstring": "Initialise the class with the key that is used to encrypt/decrypt strings",
"name": "__init__",
"signature": "def __init__(self, aKey)"
},
{
"docstring": "Encrypt/Decrypt the passed string object and return the encrypted string",
"name": "Crypt",
"signature": "def Crypt(s... | 2 | stack_v2_sparse_classes_30k_train_004303 | Implement the Python class `PEcrypt` described below.
Class description:
PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if... | Implement the Python class `PEcrypt` described below.
Class description:
PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if... | b4c81010a1476721cabc2621b17d92fead9314b4 | <|skeleton|>
class PEcrypt:
"""PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PEcrypt:
"""PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string."""
def __init_... | the_stack_v2_python_sparse | BASE SCRIPTS/XOR decryption.py | btrif/Python_dev_repo | train | 0 |
712b7de089d6ba04f6d241b1ea0ea3c5328c401a | [
"gAEAttrPresetCurrentTarget = mel.eval('$tmpVar=$gAEAttrPresetCurrentTarget;')\ngAEAttrPresetBlend = mel.eval('$tmpVar=$gAEAttrPresetBlend;')\nntype = cmds.nodeType(node)\nppath = cmds.internalVar(userPrefDir=True)\nif presetName[-4:] == '.mel':\n ppath = presetName\nelse:\n ppath = ppath.replace('prefs', 'pr... | <|body_start_0|>
gAEAttrPresetCurrentTarget = mel.eval('$tmpVar=$gAEAttrPresetCurrentTarget;')
gAEAttrPresetBlend = mel.eval('$tmpVar=$gAEAttrPresetBlend;')
ntype = cmds.nodeType(node)
ppath = cmds.internalVar(userPrefDir=True)
if presetName[-4:] == '.mel':
ppath = pr... | Helper class for finding attribute presets and reading them | fn_attr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fn_attr:
"""Helper class for finding attribute presets and reading them"""
def applyAttrPreset(node, presetName, blend):
"""Apply the named preset to the given node."""
<|body_0|>
def findAttrPresets(node):
"""Build a list of attribute presets for the given node ... | stack_v2_sparse_classes_10k_train_002237 | 2,296 | no_license | [
{
"docstring": "Apply the named preset to the given node.",
"name": "applyAttrPreset",
"signature": "def applyAttrPreset(node, presetName, blend)"
},
{
"docstring": "Build a list of attribute presets for the given node (the node's type is determined first)",
"name": "findAttrPresets",
"s... | 2 | stack_v2_sparse_classes_30k_train_005472 | Implement the Python class `fn_attr` described below.
Class description:
Helper class for finding attribute presets and reading them
Method signatures and docstrings:
- def applyAttrPreset(node, presetName, blend): Apply the named preset to the given node.
- def findAttrPresets(node): Build a list of attribute preset... | Implement the Python class `fn_attr` described below.
Class description:
Helper class for finding attribute presets and reading them
Method signatures and docstrings:
- def applyAttrPreset(node, presetName, blend): Apply the named preset to the given node.
- def findAttrPresets(node): Build a list of attribute preset... | 3891e40c3c4c3a054e5ff1ff16d051d4e690cc4a | <|skeleton|>
class fn_attr:
"""Helper class for finding attribute presets and reading them"""
def applyAttrPreset(node, presetName, blend):
"""Apply the named preset to the given node."""
<|body_0|>
def findAttrPresets(node):
"""Build a list of attribute presets for the given node ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class fn_attr:
"""Helper class for finding attribute presets and reading them"""
def applyAttrPreset(node, presetName, blend):
"""Apply the named preset to the given node."""
gAEAttrPresetCurrentTarget = mel.eval('$tmpVar=$gAEAttrPresetCurrentTarget;')
gAEAttrPresetBlend = mel.eval('$tm... | the_stack_v2_python_sparse | luxPlugin/Lux/LuxMiscModules/fn_attr.py | LuxRender/LuxMaya | train | 0 |
d32b149b58bc137d39cc258af4797b60d981d8c7 | [
"if format:\n self._format = format\nelse:\n self._format = '{percent:> 4.0f}% [{index}/{total}] {name}'\nself._name = name",
"format = self._format\nname = self._name\nvalues = collections.deque(flow)\ntotal = len(values)\nfor index in range(1, total + 1):\n yield values.popleft()\n percent = 100.0 *... | <|body_start_0|>
if format:
self._format = format
else:
self._format = '{percent:> 4.0f}% [{index}/{total}] {name}'
self._name = name
<|end_body_0|>
<|body_start_1|>
format = self._format
name = self._name
values = collections.deque(flow)
... | Print progress (how much data was processed and remains). | Progress | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Progress:
"""Print progress (how much data was processed and remains)."""
def __init__(self, name='', format=''):
"""*name*, if set, customizes the output with the collective name of values being processed (for example, "events"). *format* is a formatting string for the output. It wi... | stack_v2_sparse_classes_10k_train_002238 | 2,598 | permissive | [
{
"docstring": "*name*, if set, customizes the output with the collective name of values being processed (for example, \"events\"). *format* is a formatting string for the output. It will be passed keyword arguments *percent*, *index*, *total* and *name*. Use :class:`Progress` before a large processing. For exa... | 2 | stack_v2_sparse_classes_30k_train_002407 | Implement the Python class `Progress` described below.
Class description:
Print progress (how much data was processed and remains).
Method signatures and docstrings:
- def __init__(self, name='', format=''): *name*, if set, customizes the output with the collective name of values being processed (for example, "events... | Implement the Python class `Progress` described below.
Class description:
Print progress (how much data was processed and remains).
Method signatures and docstrings:
- def __init__(self, name='', format=''): *name*, if set, customizes the output with the collective name of values being processed (for example, "events... | 8b85a93e3c15a69d58521332aac3202a077aa7ba | <|skeleton|>
class Progress:
"""Print progress (how much data was processed and remains)."""
def __init__(self, name='', format=''):
"""*name*, if set, customizes the output with the collective name of values being processed (for example, "events"). *format* is a formatting string for the output. It wi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Progress:
"""Print progress (how much data was processed and remains)."""
def __init__(self, name='', format=''):
"""*name*, if set, customizes the output with the collective name of values being processed (for example, "events"). *format* is a formatting string for the output. It will be passed ... | the_stack_v2_python_sparse | lena/flow/progress.py | ynikitenko/lena | train | 4 |
599471fca4ccb4ca24191a09dc5ffa6db27b94f2 | [
"if self._validate:\n if len(data.shape) <= 1:\n raise DataProcessorError('The data should be an array with at least two dimensions.')\nreturn data",
"all_counts = []\nfor datum in data:\n counts = {}\n for bit_string in set(datum):\n counts[bit_string] = sum(datum == bit_string)\n all_c... | <|body_start_0|>
if self._validate:
if len(data.shape) <= 1:
raise DataProcessorError('The data should be an array with at least two dimensions.')
return data
<|end_body_0|>
<|body_start_1|>
all_counts = []
for datum in data:
counts = {}
... | A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array. | MemoryToCounts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemoryToCounts:
"""A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array."""
def _format_d... | stack_v2_sparse_classes_10k_train_002239 | 42,185 | permissive | [
{
"docstring": "Validate the input data.",
"name": "_format_data",
"signature": "def _format_data(self, data: np.ndarray) -> np.ndarray"
},
{
"docstring": "Args: data: The classified data to format into a counts dictionary. The first dimension is assumed to correspond to the different circuit ex... | 2 | stack_v2_sparse_classes_30k_train_001699 | Implement the Python class `MemoryToCounts` described below.
Class description:
A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped ... | Implement the Python class `MemoryToCounts` described below.
Class description:
A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped ... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class MemoryToCounts:
"""A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array."""
def _format_d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MemoryToCounts:
"""A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array."""
def _format_data(self, dat... | the_stack_v2_python_sparse | qiskit_experiments/data_processing/nodes.py | oliverdial/qiskit-experiments | train | 0 |
8fd103c2892d529f5fd66ed603ad285900c9f5c9 | [
"nbm = self.notebook_manager\ncheckpoints = nbm.list_checkpoints(notebook_id)\ndata = jsonapi.dumps(checkpoints, default=date_default)\nself.finish(data)",
"nbm = self.notebook_manager\ncheckpoint = nbm.create_checkpoint(notebook_id)\ndata = jsonapi.dumps(checkpoint, default=date_default)\nself.set_header('Locati... | <|body_start_0|>
nbm = self.notebook_manager
checkpoints = nbm.list_checkpoints(notebook_id)
data = jsonapi.dumps(checkpoints, default=date_default)
self.finish(data)
<|end_body_0|>
<|body_start_1|>
nbm = self.notebook_manager
checkpoint = nbm.create_checkpoint(notebook_... | NotebookCheckpointsHandler | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotebookCheckpointsHandler:
def get(self, notebook_id):
"""get lists checkpoints for a notebook"""
<|body_0|>
def post(self, notebook_id):
"""post creates a new checkpoint"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nbm = self.notebook_manager
... | stack_v2_sparse_classes_10k_train_002240 | 5,267 | permissive | [
{
"docstring": "get lists checkpoints for a notebook",
"name": "get",
"signature": "def get(self, notebook_id)"
},
{
"docstring": "post creates a new checkpoint",
"name": "post",
"signature": "def post(self, notebook_id)"
}
] | 2 | null | Implement the Python class `NotebookCheckpointsHandler` described below.
Class description:
Implement the NotebookCheckpointsHandler class.
Method signatures and docstrings:
- def get(self, notebook_id): get lists checkpoints for a notebook
- def post(self, notebook_id): post creates a new checkpoint | Implement the Python class `NotebookCheckpointsHandler` described below.
Class description:
Implement the NotebookCheckpointsHandler class.
Method signatures and docstrings:
- def get(self, notebook_id): get lists checkpoints for a notebook
- def post(self, notebook_id): post creates a new checkpoint
<|skeleton|>
cl... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class NotebookCheckpointsHandler:
def get(self, notebook_id):
"""get lists checkpoints for a notebook"""
<|body_0|>
def post(self, notebook_id):
"""post creates a new checkpoint"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NotebookCheckpointsHandler:
def get(self, notebook_id):
"""get lists checkpoints for a notebook"""
nbm = self.notebook_manager
checkpoints = nbm.list_checkpoints(notebook_id)
data = jsonapi.dumps(checkpoints, default=date_default)
self.finish(data)
def post(self, n... | the_stack_v2_python_sparse | pkgs/ipython-1.2.1-py27_0/lib/python2.7/site-packages/IPython/html/services/notebooks/handlers.py | wangyum/Anaconda | train | 11 | |
fdf29d115289758c0fc2b00344f357292e489ce7 | [
"test = '5 6\\n1 2\\n1 3\\n2 3\\n2 4\\n3 4\\n4 5'\nd = Musk(test)\nself.assertEqual(d.n, 5)\nself.assertEqual(d.m, 6)\nself.assertEqual(d.numa, [0, 0, 1, 1, 2, 3])\nself.assertEqual(d.numb, [1, 2, 2, 3, 3, 4])\nself.assertEqual(d.sets[0], {1, 2})\nself.assertEqual(d.sets[3], {1, 2, 4})\nself.assertEqual(Musk(test).... | <|body_start_0|>
test = '5 6\n1 2\n1 3\n2 3\n2 4\n3 4\n4 5'
d = Musk(test)
self.assertEqual(d.n, 5)
self.assertEqual(d.m, 6)
self.assertEqual(d.numa, [0, 0, 1, 1, 2, 3])
self.assertEqual(d.numb, [1, 2, 2, 3, 3, 4])
self.assertEqual(d.sets[0], {1, 2})
self.... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Musk class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '5 6\n1 2\n1 3\n2 3\n2 4\n3 4\n4 5'
d = Musk(test)
... | stack_v2_sparse_classes_10k_train_002241 | 3,953 | permissive | [
{
"docstring": "Musk class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001089 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Musk class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Musk class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""M... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Musk class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Musk class testing"""
test = '5 6\n1 2\n1 3\n2 3\n2 4\n3 4\n4 5'
d = Musk(test)
self.assertEqual(d.n, 5)
self.assertEqual(d.m, 6)
self.assertEqual(d.numa, [0, 0, 1, 1, 2, 3])
self.assertEqual(d.numb, [1, 2, 2, 3,... | the_stack_v2_python_sparse | codeforces/574B_musk.py | snsokolov/contests | train | 1 | |
8840aa3d67146a62f9c2733d84e461954c440811 | [
"if isinstance(key, int):\n return Certificate(key)\nif key not in Certificate._member_map_:\n extend_enum(Certificate, key, default)\nreturn Certificate[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 9 <= value <= 255... | <|body_start_0|>
if isinstance(key, int):
return Certificate(key)
if key not in Certificate._member_map_:
extend_enum(Certificate, key, default)
return Certificate[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
... | [Certificate] HIP Certificate Types | Certificate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Certificate:
"""[Certificate] HIP Certificate Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_10k_train_002242 | 1,540 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000323 | Implement the Python class `Certificate` described below.
Class description:
[Certificate] HIP Certificate Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Certificate` described below.
Class description:
[Certificate] HIP Certificate Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Certificate... | 90cd07d67df28d5c5ab0585bc60f467a78d9db33 | <|skeleton|>
class Certificate:
"""[Certificate] HIP Certificate Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Certificate:
"""[Certificate] HIP Certificate Types"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Certificate(key)
if key not in Certificate._member_map_:
extend_enum(Certificate, key, default)
... | the_stack_v2_python_sparse | pcapkit/const/hip/certificate.py | stjordanis/PyPCAPKit | train | 0 |
aeb7faa37bcf6f39d899933445f5c230f972a6b1 | [
"self = object.__new__(cls)\nself.name = cls.DEFAULT_NAME\nself.metadata_type = None\nself.INSTANCES[value] = self\nreturn self",
"self.name = name\nself.value = value\nself.metadata_type = metadata_type\nself.INSTANCES[value] = self"
] | <|body_start_0|>
self = object.__new__(cls)
self.name = cls.DEFAULT_NAME
self.metadata_type = None
self.INSTANCES[value] = self
return self
<|end_body_0|>
<|body_start_1|>
self.name = name
self.value = value
self.metadata_type = metadata_type
self... | Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass The scheduled event's metadata's applicable type. Clas... | ScheduledEventEntityType | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduledEventEntityType:
"""Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass Th... | stack_v2_sparse_classes_10k_train_002243 | 7,142 | permissive | [
{
"docstring": "Creates a scheduled event entity type from the given id and stores it at class's `.INSTANCES`. Called by `.get` when no scheduled event entity type was found with the given id. Parameters ---------- value : `int` The identifier of the scheduled event entity type. Returns ------- self : `instance... | 2 | null | Implement the Python class `ScheduledEventEntityType` described below.
Class description:
Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``Sch... | Implement the Python class `ScheduledEventEntityType` described below.
Class description:
Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``Sch... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class ScheduledEventEntityType:
"""Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScheduledEventEntityType:
"""Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass The scheduled e... | the_stack_v2_python_sparse | hata/discord/scheduled_event/scheduled_event/preinstanced.py | HuyaneMatsu/hata | train | 3 |
793e9053b218a4c4ece4d609e02a50cd685bfa1b | [
"super(LabelSmoothingLoss, self).__init__()\nself.criterion = criterion\nself.padding_idx = padding_idx\nassert 0.0 < smoothing <= 1.0\nself.confidence = 1.0 - smoothing\nself.smoothing = smoothing\nself.size = size\nself.true_dist = None\nself.normalize_length = normalize_length",
"assert x.size(2) == self.size\... | <|body_start_0|>
super(LabelSmoothingLoss, self).__init__()
self.criterion = criterion
self.padding_idx = padding_idx
assert 0.0 < smoothing <= 1.0
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.size = size
self.true_dist = None
... | Label-smoothing loss. KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/label_smoothing_loss.py Args: size: the number of class padding_idx: padding_idx: ignored cla... | LabelSmoothingLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothingLoss:
"""Label-smoothing loss. KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/label_smoothing_loss.py Args: size: the number ... | stack_v2_sparse_classes_10k_train_002244 | 33,189 | permissive | [
{
"docstring": "Construct an LabelSmoothingLoss object.",
"name": "__init__",
"signature": "def __init__(self, size: int, padding_idx: int=-1, smoothing: float=0.1, normalize_length: bool=False, criterion: nn.Module=nn.KLDivLoss(reduction='none')) -> None"
},
{
"docstring": "Compute loss between... | 2 | stack_v2_sparse_classes_30k_train_006623 | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Label-smoothing loss. KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/label_sm... | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Label-smoothing loss. KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/label_sm... | 2dda31e14039a79b77c89bcd3bb96d52cbf60c8a | <|skeleton|>
class LabelSmoothingLoss:
"""Label-smoothing loss. KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/label_smoothing_loss.py Args: size: the number ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LabelSmoothingLoss:
"""Label-smoothing loss. KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/label_smoothing_loss.py Args: size: the number of class padd... | the_stack_v2_python_sparse | snowfall/models/transformer.py | csukuangfj/snowfall | train | 0 |
3cc4f180878e97fe9a9e379189e688bdf950b0e6 | [
"self.best_clf = best_clf\nself.min_max_scaler = min_max_scaler\nself.clustering = False\nself.polynomial = False\nif clustering_obj is not None:\n self.clustering_obj = clustering_obj\n self.clustering = True\nif best_features is not None:\n self.best_features = best_features\nif best_features_poly is not... | <|body_start_0|>
self.best_clf = best_clf
self.min_max_scaler = min_max_scaler
self.clustering = False
self.polynomial = False
if clustering_obj is not None:
self.clustering_obj = clustering_obj
self.clustering = True
if best_features is not None:
... | Class to use best model output from AML_MS .Use this class to deploy trainied classifiers. | Predictor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
"""Class to use best model output from AML_MS .Use this class to deploy trainied classifiers."""
def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):
"""Use Pickle files from CoreML to deploy the classifier. P... | stack_v2_sparse_classes_10k_train_002245 | 3,923 | permissive | [
{
"docstring": "Use Pickle files from CoreML to deploy the classifier. Parameters: best_clf (object): classifier from CoreML min_max_scaler (object) clustering_obj (object) best_features (list) best_features_poly (list) poly_obj (object)",
"name": "__init__",
"signature": "def __init__(self, best_clf, m... | 3 | stack_v2_sparse_classes_30k_train_001174 | Implement the Python class `Predictor` described below.
Class description:
Class to use best model output from AML_MS .Use this class to deploy trainied classifiers.
Method signatures and docstrings:
- def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):... | Implement the Python class `Predictor` described below.
Class description:
Class to use best model output from AML_MS .Use this class to deploy trainied classifiers.
Method signatures and docstrings:
- def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):... | 22806f3ed2e102363d44e4e78a35c39381c846a9 | <|skeleton|>
class Predictor:
"""Class to use best model output from AML_MS .Use this class to deploy trainied classifiers."""
def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):
"""Use Pickle files from CoreML to deploy the classifier. P... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Predictor:
"""Class to use best model output from AML_MS .Use this class to deploy trainied classifiers."""
def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):
"""Use Pickle files from CoreML to deploy the classifier. Parameters: be... | the_stack_v2_python_sparse | Classes/Predictor.py | gariciodaro/MLDiagnosisTool | train | 1 |
dc1bb1cec63d46f9e53281a8bdc2708d847f2f3e | [
"is_admin = False\nif api.user.is_logged_in():\n is_admin = api.user.get_user().get('admin', False)\nsettings = api.config.get_settings()\nif not is_admin:\n return jsonify({'enable_captcha': settings['captcha']['enable_captcha'], 'reCAPTCHA_public_key': settings['captcha']['reCAPTCHA_public_key'], 'email_ver... | <|body_start_0|>
is_admin = False
if api.user.is_logged_in():
is_admin = api.user.get_user().get('admin', False)
settings = api.config.get_settings()
if not is_admin:
return jsonify({'enable_captcha': settings['captcha']['enable_captcha'], 'reCAPTCHA_public_key': ... | Get or modify the current settings. | Settings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Get or modify the current settings."""
def get(self):
"""Get the current settings. Admins get everything, non-admins only get registration/login related params."""
<|body_0|>
def patch(self):
"""Update settings."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k_train_002246 | 1,854 | permissive | [
{
"docstring": "Get the current settings. Admins get everything, non-admins only get registration/login related params.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Update settings.",
"name": "patch",
"signature": "def patch(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004624 | Implement the Python class `Settings` described below.
Class description:
Get or modify the current settings.
Method signatures and docstrings:
- def get(self): Get the current settings. Admins get everything, non-admins only get registration/login related params.
- def patch(self): Update settings. | Implement the Python class `Settings` described below.
Class description:
Get or modify the current settings.
Method signatures and docstrings:
- def get(self): Get the current settings. Admins get everything, non-admins only get registration/login related params.
- def patch(self): Update settings.
<|skeleton|>
cla... | 468035038afe00c6e7842b7e68ec45355ee1a224 | <|skeleton|>
class Settings:
"""Get or modify the current settings."""
def get(self):
"""Get the current settings. Admins get everything, non-admins only get registration/login related params."""
<|body_0|>
def patch(self):
"""Update settings."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Settings:
"""Get or modify the current settings."""
def get(self):
"""Get the current settings. Admins get everything, non-admins only get registration/login related params."""
is_admin = False
if api.user.is_logged_in():
is_admin = api.user.get_user().get('admin', Fal... | the_stack_v2_python_sparse | picoCTF-web/api/apps/v1/settings.py | zxc135781/picoCTF | train | 1 |
ac7aad9c932a78cfb7b2fc409e661f20564106c7 | [
"squares = [i ** 2 for i in range(1, int(n ** 0.5) + 1)]\ndp = [float('inf') for _ in range(n + 1)]\ndp[0] = 0\nfor i in range(1, n + 1):\n for square in squares:\n if square > i:\n break\n dp[i] = min(dp[i], dp[i - square] + 1)\nreturn dp[n]",
"from collections import deque\nqueue, de... | <|body_start_0|>
squares = [i ** 2 for i in range(1, int(n ** 0.5) + 1)]
dp = [float('inf') for _ in range(n + 1)]
dp[0] = 0
for i in range(1, n + 1):
for square in squares:
if square > i:
break
dp[i] = min(dp[i], dp[i - squ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
<|body_0|>
def numSquares_1(self, n: int) -> int:
"""BFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
squares = [i ** 2 for i in range(1, int(n ** 0.5) + 1)]
dp = [float('inf') for _... | stack_v2_sparse_classes_10k_train_002247 | 1,233 | no_license | [
{
"docstring": "dp",
"name": "numSquares",
"signature": "def numSquares(self, n: int) -> int"
},
{
"docstring": "BFS",
"name": "numSquares_1",
"signature": "def numSquares_1(self, n: int) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: dp
- def numSquares_1(self, n: int) -> int: BFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: dp
- def numSquares_1(self, n: int) -> int: BFS
<|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
<|body_0|>
def numSquares_1(self, n: int) -> int:
"""BFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
squares = [i ** 2 for i in range(1, int(n ** 0.5) + 1)]
dp = [float('inf') for _ in range(n + 1)]
dp[0] = 0
for i in range(1, n + 1):
for square in squares:
if square > i:
... | the_stack_v2_python_sparse | algorithm/leetcode/bfs/11-完全平方数.py | lxconfig/UbuntuCode_bak | train | 0 | |
c8c975b5de40c3c6b78dbebe52dea33b098d6e43 | [
"def maxLengthBeforeI(num):\n lstBeforeI = [dp[j] for j in range(num) if nums[j] < nums[i]]\n return max(lstBeforeI) if lstBeforeI else 0\nn = len(nums)\ndp = [0] * n\ndp[0] = 1\nfor i in range(1, n):\n dp[i] = 1 + maxLengthBeforeI(i)\nreturn max(dp)",
"if not nums:\n return 0\ndp = []\nfor i in range... | <|body_start_0|>
def maxLengthBeforeI(num):
lstBeforeI = [dp[j] for j in range(num) if nums[j] < nums[i]]
return max(lstBeforeI) if lstBeforeI else 0
n = len(nums)
dp = [0] * n
dp[0] = 1
for i in range(1, n):
dp[i] = 1 + maxLengthBeforeI(i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_10k_train_002248 | 2,098 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] ... | 4 | stack_v2_sparse_classes_30k_train_001004 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): :type nums: List[in... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
def maxLengthBeforeI(num):
lstBeforeI = [dp[j] for j in range(num) if nums[j] < nums[i]]
return max(lstBeforeI) if lstBeforeI else 0
n = len(nums)
dp = [0] * n
dp[0] =... | the_stack_v2_python_sparse | 0300_Longest_Increasing_Subsequence.py | bingli8802/leetcode | train | 0 | |
7557204b340501465e6cd6bd1ff513a21b1091df | [
"if self.validate_data():\n try:\n open(self.name, 'wb').write(lxml.etree.tostring(self.xdata, pretty_print=True))\n return True\n except IOError:\n err = sys.exc_info()[1]\n logger.error('Failed to write %s: %s' % (self.name, err))\n return False\nelse:\n return False",
... | <|body_start_0|>
if self.validate_data():
try:
open(self.name, 'wb').write(lxml.etree.tostring(self.xdata, pretty_print=True))
return True
except IOError:
err = sys.exc_info()[1]
logger.error('Failed to write %s: %s' % (self... | Class for properties files. | PropertyFile | [
"mpich2",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyFile:
"""Class for properties files."""
def write(self):
"""Write the data in this data structure back to the property file"""
<|body_0|>
def validate_data(self):
"""ensure that the data in this object validates against the XML schema for this property fi... | stack_v2_sparse_classes_10k_train_002249 | 2,503 | permissive | [
{
"docstring": "Write the data in this data structure back to the property file",
"name": "write",
"signature": "def write(self)"
},
{
"docstring": "ensure that the data in this object validates against the XML schema for this property file (if a schema exists)",
"name": "validate_data",
... | 2 | stack_v2_sparse_classes_30k_train_000026 | Implement the Python class `PropertyFile` described below.
Class description:
Class for properties files.
Method signatures and docstrings:
- def write(self): Write the data in this data structure back to the property file
- def validate_data(self): ensure that the data in this object validates against the XML schema... | Implement the Python class `PropertyFile` described below.
Class description:
Class for properties files.
Method signatures and docstrings:
- def write(self): Write the data in this data structure back to the property file
- def validate_data(self): ensure that the data in this object validates against the XML schema... | 826f385767ccf9f608fcfbe35e381a9dbc59db4b | <|skeleton|>
class PropertyFile:
"""Class for properties files."""
def write(self):
"""Write the data in this data structure back to the property file"""
<|body_0|>
def validate_data(self):
"""ensure that the data in this object validates against the XML schema for this property fi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PropertyFile:
"""Class for properties files."""
def write(self):
"""Write the data in this data structure back to the property file"""
if self.validate_data():
try:
open(self.name, 'wb').write(lxml.etree.tostring(self.xdata, pretty_print=True))
... | the_stack_v2_python_sparse | src/lib/Server/Plugins/Properties.py | mikemccllstr/bcfg2 | train | 1 |
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_10k_train_002250 | 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 | null | 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_10k | 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 |
22e4d9702a840cce0e1551289c50561225b4f268 | [
"if (image_folder is None) == (image_files is None):\n raise ValueError('One of image_folder and image_files should be provided')\ndataset, preproc_transform = _load_dataset(image_folder, image_files)\nsuper().__init__(dataset, batchsize_per_replica, shuffle, transform, num_samples)\nif preproc_transform is not ... | <|body_start_0|>
if (image_folder is None) == (image_files is None):
raise ValueError('One of image_folder and image_files should be provided')
dataset, preproc_transform = _load_dataset(image_folder, image_files)
super().__init__(dataset, batchsize_per_replica, shuffle, transform, n... | Dataset which reads images from a local filesystem. Implements ClassyDataset. | ImagePathDataset | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePathDataset:
"""Dataset which reads images from a local filesystem. Implements ClassyDataset."""
def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, num_samples: Optional[int]=None, image_folder: Optional[str]=None, i... | stack_v2_sparse_classes_10k_train_002251 | 4,706 | permissive | [
{
"docstring": "Constructor for ImagePathDataset. Only one of image_folder or image_files should be passed to specify the images. Args: batchsize_per_replica: Positive integer indicating batch size for each replica shuffle: Whether we should shuffle between epochs transform: Transform to be applied to each samp... | 2 | stack_v2_sparse_classes_30k_train_001798 | Implement the Python class `ImagePathDataset` described below.
Class description:
Dataset which reads images from a local filesystem. Implements ClassyDataset.
Method signatures and docstrings:
- def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, ... | Implement the Python class `ImagePathDataset` described below.
Class description:
Dataset which reads images from a local filesystem. Implements ClassyDataset.
Method signatures and docstrings:
- def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, ... | 08a82e88fcfa143933832994ace2424c03dd43b8 | <|skeleton|>
class ImagePathDataset:
"""Dataset which reads images from a local filesystem. Implements ClassyDataset."""
def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, num_samples: Optional[int]=None, image_folder: Optional[str]=None, i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImagePathDataset:
"""Dataset which reads images from a local filesystem. Implements ClassyDataset."""
def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, num_samples: Optional[int]=None, image_folder: Optional[str]=None, image_files: O... | the_stack_v2_python_sparse | classy_vision/dataset/image_path_dataset.py | facebookresearch/ClassyVision | train | 1,673 |
ef6b73ad4022308c6072298ae6577084698cba77 | [
"Component.__init__(self, bot)\nself.bot = bot\nself.logger = logging.getLogger('components.topic')\nself.persistence = self.bot.get_subsystem('local-persistence')",
"added_at = date.today()\naddition = TopicAddition(date=added_at, text=text, user=user)\nsession = self.persistence.get_session()\nsession.add(addit... | <|body_start_0|>
Component.__init__(self, bot)
self.bot = bot
self.logger = logging.getLogger('components.topic')
self.persistence = self.bot.get_subsystem('local-persistence')
<|end_body_0|>
<|body_start_1|>
added_at = date.today()
addition = TopicAddition(date=added_at... | TopicComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicComponent:
def __init__(self, bot):
"""Initialize all required variables."""
<|body_0|>
def insert_addition(self, text, user):
"""Insert a new addition to database. @param text: the real addition text @param user: the person who likes to add the addition @return... | stack_v2_sparse_classes_10k_train_002252 | 4,482 | permissive | [
{
"docstring": "Initialize all required variables.",
"name": "__init__",
"signature": "def __init__(self, bot)"
},
{
"docstring": "Insert a new addition to database. @param text: the real addition text @param user: the person who likes to add the addition @return: None",
"name": "insert_addi... | 6 | stack_v2_sparse_classes_30k_train_006957 | Implement the Python class `TopicComponent` described below.
Class description:
Implement the TopicComponent class.
Method signatures and docstrings:
- def __init__(self, bot): Initialize all required variables.
- def insert_addition(self, text, user): Insert a new addition to database. @param text: the real addition... | Implement the Python class `TopicComponent` described below.
Class description:
Implement the TopicComponent class.
Method signatures and docstrings:
- def __init__(self, bot): Initialize all required variables.
- def insert_addition(self, text, user): Insert a new addition to database. @param text: the real addition... | 064164dcd3baa867f276a5791eaf8050d568fc3f | <|skeleton|>
class TopicComponent:
def __init__(self, bot):
"""Initialize all required variables."""
<|body_0|>
def insert_addition(self, text, user):
"""Insert a new addition to database. @param text: the real addition text @param user: the person who likes to add the addition @return... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TopicComponent:
def __init__(self, bot):
"""Initialize all required variables."""
Component.__init__(self, bot)
self.bot = bot
self.logger = logging.getLogger('components.topic')
self.persistence = self.bot.get_subsystem('local-persistence')
def insert_addition(sel... | the_stack_v2_python_sparse | src/python/components/topic.py | msteinhoff/foption-bot | train | 0 | |
8091dc981667607b8d8c9e273ffd291be1ff3e87 | [
"if not headA or not headB:\n return None\ncur = headA\npassed_nodes = {cur}\nwhile cur:\n passed_nodes.add(cur)\n cur = cur.next\ncur = headB\nwhile cur:\n if cur in passed_nodes:\n return cur\n cur = cur.next\nelse:\n return None",
"pA = headA\npB = headB\nwhile pA != pB:\n pA = pA.n... | <|body_start_0|>
if not headA or not headB:
return None
cur = headA
passed_nodes = {cur}
while cur:
passed_nodes.add(cur)
cur = cur.next
cur = headB
while cur:
if cur in passed_nodes:
return cur
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
"""使用 set 保存走过路径的笨办法, 不满足`程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存`要求 O(n+m) 时间复杂度, O(n) 内存h :type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode(self, headA, headB):
"""神奇的解法, 代码还漂亮"""
... | stack_v2_sparse_classes_10k_train_002253 | 1,502 | no_license | [
{
"docstring": "使用 set 保存走过路径的笨办法, 不满足`程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存`要求 O(n+m) 时间复杂度, O(n) 内存h :type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA, headB)"
},
{
"docstring": "神奇的解法, 代码还漂亮",
"name": "getIntersectionN... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): 使用 set 保存走过路径的笨办法, 不满足`程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存`要求 O(n+m) 时间复杂度, O(n) 内存h :type head1, head1: ListNode :rtype: ListNode
- def ge... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): 使用 set 保存走过路径的笨办法, 不满足`程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存`要求 O(n+m) 时间复杂度, O(n) 内存h :type head1, head1: ListNode :rtype: ListNode
- def ge... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
"""使用 set 保存走过路径的笨办法, 不满足`程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存`要求 O(n+m) 时间复杂度, O(n) 内存h :type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode(self, headA, headB):
"""神奇的解法, 代码还漂亮"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def getIntersectionNode(self, headA, headB):
"""使用 set 保存走过路径的笨办法, 不满足`程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存`要求 O(n+m) 时间复杂度, O(n) 内存h :type head1, head1: ListNode :rtype: ListNode"""
if not headA or not headB:
return None
cur = headA
passed_nodes = {cur}
... | the_stack_v2_python_sparse | 2018年力扣高频算法面试题汇总/相交链表.py | iamkissg/leetcode | train | 0 | |
81da836e0eaa2bd70607388b820d6a22a3effb09 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LicenseDetails()",
"from .entity import Entity\nfrom .service_plan_info import ServicePlanInfo\nfrom .entity import Entity\nfrom .service_plan_info import ServicePlanInfo\nfields: Dict[str, Callable[[Any], None]] = {'servicePlans': lam... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LicenseDetails()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .service_plan_info import ServicePlanInfo
from .entity import Entity
from .service_plan_i... | LicenseDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LicenseDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_10k_train_002254 | 2,913 | 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: LicenseDetails",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | null | Implement the Python class `LicenseDetails` described below.
Class description:
Implement the LicenseDetails class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `LicenseDetails` described below.
Class description:
Implement the LicenseDetails class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LicenseDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LicenseDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails:
"""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: LicenseDet... | the_stack_v2_python_sparse | msgraph/generated/models/license_details.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3fc43052b05e733fc669cfd053336b2825dc65f9 | [
"version_url = self._get_base_version_url()\nresp, body = self.raw_request(version_url, 'GET')\nself._error_checker(resp, body)\nself.expected_success(300, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)",
"version = 'v%s' % version\nsupported = ['SUPPORTED', 'CURRENT']\nversion... | <|body_start_0|>
version_url = self._get_base_version_url()
resp, body = self.raw_request(version_url, 'GET')
self._error_checker(resp, body)
self.expected_success(300, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
<|end_body_0|>
<|body... | VersionsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionsClient:
def list_versions(self):
"""List API versions"""
<|body_0|>
def has_version(self, version):
"""Return True if a version is supported."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
version_url = self._get_base_version_url()
... | stack_v2_sparse_classes_10k_train_002255 | 1,531 | permissive | [
{
"docstring": "List API versions",
"name": "list_versions",
"signature": "def list_versions(self)"
},
{
"docstring": "Return True if a version is supported.",
"name": "has_version",
"signature": "def has_version(self, version)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000005 | Implement the Python class `VersionsClient` described below.
Class description:
Implement the VersionsClient class.
Method signatures and docstrings:
- def list_versions(self): List API versions
- def has_version(self, version): Return True if a version is supported. | Implement the Python class `VersionsClient` described below.
Class description:
Implement the VersionsClient class.
Method signatures and docstrings:
- def list_versions(self): List API versions
- def has_version(self, version): Return True if a version is supported.
<|skeleton|>
class VersionsClient:
def list_... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class VersionsClient:
def list_versions(self):
"""List API versions"""
<|body_0|>
def has_version(self, version):
"""Return True if a version is supported."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VersionsClient:
def list_versions(self):
"""List API versions"""
version_url = self._get_base_version_url()
resp, body = self.raw_request(version_url, 'GET')
self._error_checker(resp, body)
self.expected_success(300, resp.status)
body = json.loads(body)
... | the_stack_v2_python_sparse | tempest/lib/services/image/v2/versions_client.py | openstack/tempest | train | 270 | |
47510d7029e8af23795e38e0ae5da4674fff0773 | [
"data = self.request.get('data', {})\nself_id = data['self_id']\nuser = self.request.app['models']['user']\ncompany = self.request.app['models']['company']\nuser_id = self.request.rel_url.query.get('id')\nif user_id:\n account = await user.get_user(user_id)\n access = user_id == self_id\n users_company = a... | <|body_start_0|>
data = self.request.get('data', {})
self_id = data['self_id']
user = self.request.app['models']['user']
company = self.request.app['models']['company']
user_id = self.request.rel_url.query.get('id')
if user_id:
account = await user.get_user(us... | AccountDetails | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountDetails:
async def get(self):
"""Страница проосмотра данных о пользователе"""
<|body_0|>
async def post(self):
"""Обновление данных пользователя"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = self.request.get('data', {})
self_... | stack_v2_sparse_classes_10k_train_002256 | 3,877 | no_license | [
{
"docstring": "Страница проосмотра данных о пользователе",
"name": "get",
"signature": "async def get(self)"
},
{
"docstring": "Обновление данных пользователя",
"name": "post",
"signature": "async def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000158 | Implement the Python class `AccountDetails` described below.
Class description:
Implement the AccountDetails class.
Method signatures and docstrings:
- async def get(self): Страница проосмотра данных о пользователе
- async def post(self): Обновление данных пользователя | Implement the Python class `AccountDetails` described below.
Class description:
Implement the AccountDetails class.
Method signatures and docstrings:
- async def get(self): Страница проосмотра данных о пользователе
- async def post(self): Обновление данных пользователя
<|skeleton|>
class AccountDetails:
async d... | c8726ad77079b981453c11d5c7fc39bc838eec67 | <|skeleton|>
class AccountDetails:
async def get(self):
"""Страница проосмотра данных о пользователе"""
<|body_0|>
async def post(self):
"""Обновление данных пользователя"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountDetails:
async def get(self):
"""Страница проосмотра данных о пользователе"""
data = self.request.get('data', {})
self_id = data['self_id']
user = self.request.app['models']['user']
company = self.request.app['models']['company']
user_id = self.request.re... | the_stack_v2_python_sparse | auth/views.py | ArtemZaitsev1994/chat | train | 0 | |
0e975715b084adf731f8297c9aaa09f501edd7ea | [
"data_dir = get_data_dir()\nif platform.system() == 'Linux':\n url = 'https://github.com/gnina/gnina/releases/download/v1.0/gnina'\n filename = 'gnina'\n self.gnina_dir = data_dir\n self.gnina_cmd = os.path.join(self.gnina_dir, filename)\nelse:\n raise ValueError('GNINA currently only runs on Linux. ... | <|body_start_0|>
data_dir = get_data_dir()
if platform.system() == 'Linux':
url = 'https://github.com/gnina/gnina/releases/download/v1.0/gnina'
filename = 'gnina'
self.gnina_dir = data_dir
self.gnina_cmd = os.path.join(self.gnina_dir, filename)
els... | Use GNINA to generate binding poses. This class uses GNINA (a deep learning framework for molecular docking) to generate binding poses. It downloads the GNINA executable to DEEPCHEM_DATA_DIR (an environment variable you set) and invokes the executable to perform pose generation. GNINA uses pre-trained convolutional neu... | GninaPoseGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GninaPoseGenerator:
"""Use GNINA to generate binding poses. This class uses GNINA (a deep learning framework for molecular docking) to generate binding poses. It downloads the GNINA executable to DEEPCHEM_DATA_DIR (an environment variable you set) and invokes the executable to perform pose genera... | stack_v2_sparse_classes_10k_train_002257 | 19,576 | permissive | [
{
"docstring": "Initialize GNINA pose generator.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Generates the docked complex and outputs files for docked complex. Parameters ---------- molecular_complexes: Tuple[str, str] A representation of a molecular complex. This ... | 2 | null | Implement the Python class `GninaPoseGenerator` described below.
Class description:
Use GNINA to generate binding poses. This class uses GNINA (a deep learning framework for molecular docking) to generate binding poses. It downloads the GNINA executable to DEEPCHEM_DATA_DIR (an environment variable you set) and invoke... | Implement the Python class `GninaPoseGenerator` described below.
Class description:
Use GNINA to generate binding poses. This class uses GNINA (a deep learning framework for molecular docking) to generate binding poses. It downloads the GNINA executable to DEEPCHEM_DATA_DIR (an environment variable you set) and invoke... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class GninaPoseGenerator:
"""Use GNINA to generate binding poses. This class uses GNINA (a deep learning framework for molecular docking) to generate binding poses. It downloads the GNINA executable to DEEPCHEM_DATA_DIR (an environment variable you set) and invokes the executable to perform pose genera... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GninaPoseGenerator:
"""Use GNINA to generate binding poses. This class uses GNINA (a deep learning framework for molecular docking) to generate binding poses. It downloads the GNINA executable to DEEPCHEM_DATA_DIR (an environment variable you set) and invokes the executable to perform pose generation. GNINA u... | the_stack_v2_python_sparse | deepchem/dock/pose_generation.py | deepchem/deepchem | train | 4,876 |
2a4c63f2e0c71e2f1f553ccef9f23123a0578e61 | [
"if not hasattr(self, 'nextFrame'):\n raise RuntimeError('SimpleTour instance has no specified nextFrame method.')\nif not hasattr(self, 'X'):\n raise RuntimeError('SimpleTour instance has no specified X property.')\nself.pauseSteps = pause\nself.moveFlag = True\nself.Fz, self.moveSteps = self.nextFrame(None)... | <|body_start_0|>
if not hasattr(self, 'nextFrame'):
raise RuntimeError('SimpleTour instance has no specified nextFrame method.')
if not hasattr(self, 'X'):
raise RuntimeError('SimpleTour instance has no specified X property.')
self.pauseSteps = pause
self.moveFlag... | A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils. | SimpleTour | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleTour:
"""A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils."""
def __init__(self, pause=0):
"""Constructs a SimpleTour object given a generator function that specifie... | stack_v2_sparse_classes_10k_train_002258 | 3,652 | permissive | [
{
"docstring": "Constructs a SimpleTour object given a generator function that specifies the next frame to travel to and the number of steps to take. Should not be called explicitly.",
"name": "__init__",
"signature": "def __init__(self, pause=0)"
},
{
"docstring": "Checks to make sure that the ... | 6 | stack_v2_sparse_classes_30k_train_005569 | Implement the Python class `SimpleTour` described below.
Class description:
A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils.
Method signatures and docstrings:
- def __init__(self, pause=0): Constructs a S... | Implement the Python class `SimpleTour` described below.
Class description:
A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils.
Method signatures and docstrings:
- def __init__(self, pause=0): Constructs a S... | 435676abe6a1ad07aa9227325c7a35d3c6e146d7 | <|skeleton|>
class SimpleTour:
"""A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils."""
def __init__(self, pause=0):
"""Constructs a SimpleTour object given a generator function that specifie... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleTour:
"""A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils."""
def __init__(self, pause=0):
"""Constructs a SimpleTour object given a generator function that specifies the next fr... | the_stack_v2_python_sparse | pytour/simpleTour/simpleTour.py | crhoyt/pytour | train | 0 |
81f5a8c856b9334baaa0a7a44c56fe5de989ec38 | [
"errors = []\nif not HAS_TTP:\n errors.append(missing_required_lib('ttp'))\nreturn {'errors': errors}",
"cli_output = self._task_args.get('text')\nres = self._check_reqs()\nif res.get('errors'):\n return {'errors': res.get('errors')}\ntry:\n parser = ttp(data=cli_output, template=self._task_args.get('par... | <|body_start_0|>
errors = []
if not HAS_TTP:
errors.append(missing_required_lib('ttp'))
return {'errors': errors}
<|end_body_0|>
<|body_start_1|>
cli_output = self._task_args.get('text')
res = self._check_reqs()
if res.get('errors'):
return {'erro... | The ttp parser class Convert raw text to structured data using ttp | CliParser | [
"GPL-3.0-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliParser:
"""The ttp parser class Convert raw text to structured data using ttp"""
def _check_reqs():
"""Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
"""Std entry... | stack_v2_sparse_classes_10k_train_002259 | 2,378 | permissive | [
{
"docstring": "Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path",
"name": "_check_reqs",
"signature": "def _check_reqs()"
},
{
"docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype: di... | 2 | stack_v2_sparse_classes_30k_test_000342 | Implement the Python class `CliParser` described below.
Class description:
The ttp parser class Convert raw text to structured data using ttp
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path
- def parse(self, *_args, ... | Implement the Python class `CliParser` described below.
Class description:
The ttp parser class Convert raw text to structured data using ttp
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path
- def parse(self, *_args, ... | 2ea7d4f00212f502bc684ac257371ada73da1ca9 | <|skeleton|>
class CliParser:
"""The ttp parser class Convert raw text to structured data using ttp"""
def _check_reqs():
"""Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
"""Std entry... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CliParser:
"""The ttp parser class Convert raw text to structured data using ttp"""
def _check_reqs():
"""Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path"""
errors = []
if not HAS_TTP:
errors.append(missing_required_lib('t... | the_stack_v2_python_sparse | intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/netcommon/plugins/cli_parsers/ttp_parser.py | SimonFangCisco/dne-dna-code | train | 0 |
5de33d881a2d9e16ab686acc6ebc63b78969eaa9 | [
"acl.enforce('code_sources:create', context.ctx())\ncontent = pecan.request.text\nLOG.debug('Creating code source [names=%s, scope=%s, namespace=%s]', name, scope, namespace)\ndb_model = rest_utils.rest_retry_on_db_error(db_api.create_code_source)({'name': name, 'content': content, 'namespace': namespace, 'scope': ... | <|body_start_0|>
acl.enforce('code_sources:create', context.ctx())
content = pecan.request.text
LOG.debug('Creating code source [names=%s, scope=%s, namespace=%s]', name, scope, namespace)
db_model = rest_utils.rest_retry_on_db_error(db_api.create_code_source)({'name': name, 'content': c... | CodeSourcesController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeSourcesController:
def post(self, name, scope='private', namespace=''):
"""Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in... | stack_v2_sparse_classes_10k_train_002260 | 8,557 | permissive | [
{
"docstring": "Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in.",
"name": "post",
"signature": "def post(self, name, scope='private', namespa... | 5 | stack_v2_sparse_classes_30k_train_002072 | Implement the Python class `CodeSourcesController` described below.
Class description:
Implement the CodeSourcesController class.
Method signatures and docstrings:
- def post(self, name, scope='private', namespace=''): Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope... | Implement the Python class `CodeSourcesController` described below.
Class description:
Implement the CodeSourcesController class.
Method signatures and docstrings:
- def post(self, name, scope='private', namespace=''): Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope... | 7baff017d0cf01d19c44055ad201ca59131b9f94 | <|skeleton|>
class CodeSourcesController:
def post(self, name, scope='private', namespace=''):
"""Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CodeSourcesController:
def post(self, name, scope='private', namespace=''):
"""Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in."""
a... | the_stack_v2_python_sparse | mistral/api/controllers/v2/code_source.py | openstack/mistral | train | 214 | |
1d83103e7ca98b2c2cab1e66dbf098a4dc62c3f0 | [
"if self.measure == self.MeasureType.PROGRESS:\n if self.threshold > 1.0:\n raise TrainerConfigError('Threshold for next lesson cannot be greater than 1 when the measure is progress.')\n if self.threshold < 0.0:\n raise TrainerConfigError('Threshold for next lesson cannot be negative when the me... | <|body_start_0|>
if self.measure == self.MeasureType.PROGRESS:
if self.threshold > 1.0:
raise TrainerConfigError('Threshold for next lesson cannot be greater than 1 when the measure is progress.')
if self.threshold < 0.0:
raise TrainerConfigError('Threshol... | CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start. | CompletionCriteriaSettings | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompletionCriteriaSettings:
"""CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start."""
def _check_threshold_value(self, attribute, value):
"""Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS"""
... | stack_v2_sparse_classes_10k_train_002261 | 33,986 | permissive | [
{
"docstring": "Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS",
"name": "_check_threshold_value",
"signature": "def _check_threshold_value(self, attribute, value)"
},
{
"docstring": "Given measures, this method returns a boolean indicating if the lesson needs... | 2 | stack_v2_sparse_classes_30k_train_004036 | Implement the Python class `CompletionCriteriaSettings` described below.
Class description:
CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start.
Method signatures and docstrings:
- def _check_threshold_value(self, attribute, value): Verify that the threshold has a va... | Implement the Python class `CompletionCriteriaSettings` described below.
Class description:
CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start.
Method signatures and docstrings:
- def _check_threshold_value(self, attribute, value): Verify that the threshold has a va... | 768405d0f80d30acb29e1f7c201a98ce67a668b3 | <|skeleton|>
class CompletionCriteriaSettings:
"""CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start."""
def _check_threshold_value(self, attribute, value):
"""Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CompletionCriteriaSettings:
"""CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start."""
def _check_threshold_value(self, attribute, value):
"""Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS"""
if self.me... | the_stack_v2_python_sparse | ml-agents/mlagents/trainers/settings.py | xogur6889/ml-agents | train | 2 |
25ec0cf7049a3a19f55c79eb486332345a751ca7 | [
"page = self.client.get('/search/')\nself.assertEqual(page.status_code, 302)\nself.client.post(reverse('index'))",
"test_user = User.objects.create(username='TestUser', password='TestPassword')\nmembership = Membership.objects.create(user_id='1')\nself.client.force_login(test_user)\ntest_event = Event.objects.cre... | <|body_start_0|>
page = self.client.get('/search/')
self.assertEqual(page.status_code, 302)
self.client.post(reverse('index'))
<|end_body_0|>
<|body_start_1|>
test_user = User.objects.create(username='TestUser', password='TestPassword')
membership = Membership.objects.create(use... | TestSearchViews | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSearchViews:
def test_get_all_events_page_redirect(self):
"""Test search redirects to index with an empty result(or database)"""
<|body_0|>
def test_get_all_events_page(self):
"""Test search renders correct template with events in db"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k_train_002262 | 1,705 | no_license | [
{
"docstring": "Test search redirects to index with an empty result(or database)",
"name": "test_get_all_events_page_redirect",
"signature": "def test_get_all_events_page_redirect(self)"
},
{
"docstring": "Test search renders correct template with events in db",
"name": "test_get_all_events_... | 2 | stack_v2_sparse_classes_30k_train_007087 | Implement the Python class `TestSearchViews` described below.
Class description:
Implement the TestSearchViews class.
Method signatures and docstrings:
- def test_get_all_events_page_redirect(self): Test search redirects to index with an empty result(or database)
- def test_get_all_events_page(self): Test search rend... | Implement the Python class `TestSearchViews` described below.
Class description:
Implement the TestSearchViews class.
Method signatures and docstrings:
- def test_get_all_events_page_redirect(self): Test search redirects to index with an empty result(or database)
- def test_get_all_events_page(self): Test search rend... | 52795e9217d2786b457ca4f0b925c7d36c2dbfd4 | <|skeleton|>
class TestSearchViews:
def test_get_all_events_page_redirect(self):
"""Test search redirects to index with an empty result(or database)"""
<|body_0|>
def test_get_all_events_page(self):
"""Test search renders correct template with events in db"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestSearchViews:
def test_get_all_events_page_redirect(self):
"""Test search redirects to index with an empty result(or database)"""
page = self.client.get('/search/')
self.assertEqual(page.status_code, 302)
self.client.post(reverse('index'))
def test_get_all_events_page(s... | the_stack_v2_python_sparse | search/tests.py | paperclippete/FinalMilestone | train | 1 | |
68f44addfb9163bb2696f511e6bb58378f22e780 | [
"try:\n if self.id is None:\n return self.query.all()\n if self.id is not None and type(self.id) is int and (self.id >= 0):\n return self.query.get(self.id)\nexcept Exception as e:\n return e.__cause__.args[1]",
"try:\n db.session.add(self)\n return db.session.commit()\nexcept Excepti... | <|body_start_0|>
try:
if self.id is None:
return self.query.all()
if self.id is not None and type(self.id) is int and (self.id >= 0):
return self.query.get(self.id)
except Exception as e:
return e.__cause__.args[1]
<|end_body_0|>
<|bod... | Using to create a session in database [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [The id of session] user_id {[int]} -- [The user_id have this session] ip_address {[sring(17)]} -- [The ip address of person have user_id] user_agent {[text]} -- [The user agent... | Session | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Session:
"""Using to create a session in database [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [The id of session] user_id {[int]} -- [The user_id have this session] ip_address {[sring(17)]} -- [The ip address of person have user_id] use... | stack_v2_sparse_classes_10k_train_002263 | 5,599 | no_license | [
{
"docstring": "[summary] [description] Arguments: id {[type]} -- [description] Returns: [None] -- [When successed] [Message] -- [When failed]",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "[summary] [description] Returns: [None] -- [When successed] [Message] -- [When failed]",... | 4 | stack_v2_sparse_classes_30k_train_004615 | Implement the Python class `Session` described below.
Class description:
Using to create a session in database [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [The id of session] user_id {[int]} -- [The user_id have this session] ip_address {[sring(17)]} -- [The... | Implement the Python class `Session` described below.
Class description:
Using to create a session in database [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [The id of session] user_id {[int]} -- [The user_id have this session] ip_address {[sring(17)]} -- [The... | 052956e5006f7d274d19a43b061c2fe4a6456cc0 | <|skeleton|>
class Session:
"""Using to create a session in database [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [The id of session] user_id {[int]} -- [The user_id have this session] ip_address {[sring(17)]} -- [The ip address of person have user_id] use... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Session:
"""Using to create a session in database [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [The id of session] user_id {[int]} -- [The user_id have this session] ip_address {[sring(17)]} -- [The ip address of person have user_id] user_agent {[tex... | the_stack_v2_python_sparse | models/cache.py | BoTranVan/statuspage | train | 0 |
d870bc14e27f410951e7876aeb88f69f19ec363f | [
"params = base.get_params(None, locals())\nrequest = http.Request('GET', self.get_url(), params)\nreturn (request, parsers.parse_json)",
"self.require_collection()\nrequest = http.Request('POST', self.get_url(), self.wrap_object(obj))\nreturn (request, parsers.parse_json)",
"self.require_item()\nrequest = http.... | <|body_start_0|>
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
self.require_collection()
request = http.Request('POST', self.get_url(), self.wrap_object(obj))
... | UserVoiceResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserVoiceResource:
def get(self, page=None, per_page=None, sort=None):
"""For single-object resources, fetch the object's data. For collections, fetch all of the objects. :var page: For collections, where should paging start. If left as `None`, the first page is returned. :vartype page: ... | stack_v2_sparse_classes_10k_train_002264 | 2,920 | permissive | [
{
"docstring": "For single-object resources, fetch the object's data. For collections, fetch all of the objects. :var page: For collections, where should paging start. If left as `None`, the first page is returned. :vartype page: int :var per_page: For collections, how many objects sould be returned. If left as... | 3 | null | Implement the Python class `UserVoiceResource` described below.
Class description:
Implement the UserVoiceResource class.
Method signatures and docstrings:
- def get(self, page=None, per_page=None, sort=None): For single-object resources, fetch the object's data. For collections, fetch all of the objects. :var page: ... | Implement the Python class `UserVoiceResource` described below.
Class description:
Implement the UserVoiceResource class.
Method signatures and docstrings:
- def get(self, page=None, per_page=None, sort=None): For single-object resources, fetch the object's data. For collections, fetch all of the objects. :var page: ... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class UserVoiceResource:
def get(self, page=None, per_page=None, sort=None):
"""For single-object resources, fetch the object's data. For collections, fetch all of the objects. :var page: For collections, where should paging start. If left as `None`, the first page is returned. :vartype page: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserVoiceResource:
def get(self, page=None, per_page=None, sort=None):
"""For single-object resources, fetch the object's data. For collections, fetch all of the objects. :var page: For collections, where should paging start. If left as `None`, the first page is returned. :vartype page: int :var per_p... | the_stack_v2_python_sparse | libsaas/services/uservoice/resource.py | piplcom/libsaas | train | 1 | |
a89f117b870097cf0b490c843663f8c7a7cc9868 | [
"super(sppasStringFilterDialog, self).__init__(parent=parent, title='{:s} filter'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE)\nself._create_content()\nself.CreateActions([wx.ID_CANCEL, wx.ID_OK])\nself.SetSize(wx.Size(380, 320))\nself.LayoutComponents()\nself.CenterOnParent()",
"idx = self.radiobox.GetSele... | <|body_start_0|>
super(sppasStringFilterDialog, self).__init__(parent=parent, title='{:s} filter'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE)
self._create_content()
self.CreateActions([wx.ID_CANCEL, wx.ID_OK])
self.SetSize(wx.Size(380, 320))
self.LayoutComponents()
... | Dialog to get a filter on a string. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi | sppasStringFilterDialog | [
"MIT",
"GFDL-1.1-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sppasStringFilterDialog:
"""Dialog to get a filter on a string. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi"""
def __init__(self, parent):
... | stack_v2_sparse_classes_10k_train_002265 | 28,177 | permissive | [
{
"docstring": "Create a string filter dialog. :param parent: (wx.Window)",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Return the data defined by the user. Returns: (tuple) with: - function (str): one of the methods in Compare - values (list): patterns to fi... | 3 | null | Implement the Python class `sppasStringFilterDialog` described below.
Class description:
Dialog to get a filter on a string. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi
Meth... | Implement the Python class `sppasStringFilterDialog` described below.
Class description:
Dialog to get a filter on a string. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi
Meth... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class sppasStringFilterDialog:
"""Dialog to get a filter on a string. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi"""
def __init__(self, parent):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class sppasStringFilterDialog:
"""Dialog to get a filter on a string. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi"""
def __init__(self, parent):
"""Create a s... | the_stack_v2_python_sparse | sppas/sppas/src/ui/phoenix/page_files/associate.py | mirfan899/MTTS | train | 0 |
6bf00dcef6bb9cca25219a2bcd0ccad0008d24f1 | [
"super().__init__(model_config)\nself.model = model\nself.epoch = epoch\nself.pipeline_id = pipeline_id\nmodel.eval()",
"model_and_info = model_util.load_from_checkpoint_and_adjust(config, path_to_checkpoint)\nif model_and_info.model is None or model_and_info.checkpoint_epoch is None:\n logging.warning(f'Could... | <|body_start_0|>
super().__init__(model_config)
self.model = model
self.epoch = epoch
self.pipeline_id = pipeline_id
model.eval()
<|end_body_0|>
<|body_start_1|>
model_and_info = model_util.load_from_checkpoint_and_adjust(config, path_to_checkpoint)
if model_and_... | Pipeline for inference from a single model on classification tasks. | ScalarInferencePipeline | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarInferencePipeline:
"""Pipeline for inference from a single model on classification tasks."""
def __init__(self, model: BaseModelOrDataParallelModel, model_config: ScalarModelBase, epoch: int, pipeline_id: int) -> None:
""":param model: Model recovered from the checkpoint. :para... | stack_v2_sparse_classes_10k_train_002266 | 10,504 | permissive | [
{
"docstring": ":param model: Model recovered from the checkpoint. :param model_config: Model configuration information. :param epoch: Epoch of the checkpoint which was recovered. :param pipeline_id: ID for this pipeline (useful for ensembles). :return:",
"name": "__init__",
"signature": "def __init__(s... | 3 | stack_v2_sparse_classes_30k_train_000483 | Implement the Python class `ScalarInferencePipeline` described below.
Class description:
Pipeline for inference from a single model on classification tasks.
Method signatures and docstrings:
- def __init__(self, model: BaseModelOrDataParallelModel, model_config: ScalarModelBase, epoch: int, pipeline_id: int) -> None:... | Implement the Python class `ScalarInferencePipeline` described below.
Class description:
Pipeline for inference from a single model on classification tasks.
Method signatures and docstrings:
- def __init__(self, model: BaseModelOrDataParallelModel, model_config: ScalarModelBase, epoch: int, pipeline_id: int) -> None:... | 12b496093097ef48d5ac8880985c04918d7f76fe | <|skeleton|>
class ScalarInferencePipeline:
"""Pipeline for inference from a single model on classification tasks."""
def __init__(self, model: BaseModelOrDataParallelModel, model_config: ScalarModelBase, epoch: int, pipeline_id: int) -> None:
""":param model: Model recovered from the checkpoint. :para... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScalarInferencePipeline:
"""Pipeline for inference from a single model on classification tasks."""
def __init__(self, model: BaseModelOrDataParallelModel, model_config: ScalarModelBase, epoch: int, pipeline_id: int) -> None:
""":param model: Model recovered from the checkpoint. :param model_confi... | the_stack_v2_python_sparse | InnerEye/ML/pipelines/scalar_inference.py | MaxCodeXTC/InnerEye-DeepLearning | train | 1 |
98cf14d01fcfcd86ef1b11b3208fe037e9922432 | [
"self.map = dict()\nself.head = DLNode()\nself.tail = DLNode()\nself.head.next = self.tail\nself.tail.prev = self.head",
"if key in self.map:\n cur = self.map[key]\n cur.data[1].remove(key)\n val = cur.data[0] + 1\n r = cur.next\n if len(cur.data[1]) == 0:\n r.prev = cur.prev\n cur.pr... | <|body_start_0|>
self.map = dict()
self.head = DLNode()
self.tail = DLNode()
self.head.next = self.tail
self.tail.prev = self.head
<|end_body_0|>
<|body_start_1|>
if key in self.map:
cur = self.map[key]
cur.data[1].remove(key)
val = cu... | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""De... | stack_v2_sparse_classes_10k_train_002267 | 3,736 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void",
"name": "inc",
"signature": "def inc(self, key)"
},
... | 5 | stack_v2_sparse_classes_30k_train_005552 | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void
-... | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void
-... | 9190d3d178f1733aa226973757ee7e045b7bab00 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""De... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AllOne:
def __init__(self):
"""Initialize your data structure here."""
self.map = dict()
self.head = DLNode()
self.tail = DLNode()
self.head.next = self.tail
self.tail.prev = self.head
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or ... | the_stack_v2_python_sparse | AllOoneDataStructure.py | ellinx/LC-python | train | 1 | |
d3d5a702792a92c898b25c9781a7e3c7409403f5 | [
"self.x = x\nself.y = y\nself.z = z\nself.u = u\nself.v = v\nself.w = w\nself.spacing = spacing\nself.dimensions = dimensions\nself.origin = origin\nself.resolution = Vec3(len(np.unique(x)), len(np.unique(y)), len(np.unique(z)))",
"n_points = self.dimensions.x1 * self.dimensions.x2 * self.dimensions.x3\nvtk_file ... | <|body_start_0|>
self.x = x
self.y = y
self.z = z
self.u = u
self.v = v
self.w = w
self.spacing = spacing
self.dimensions = dimensions
self.origin = origin
self.resolution = Vec3(len(np.unique(x)), len(np.unique(y)), len(np.unique(z)))
<|en... | Generate a FlowData object to handle data I/O | FlowData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlowData:
"""Generate a FlowData object to handle data I/O"""
def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None):
"""Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array):... | stack_v2_sparse_classes_10k_train_002268 | 4,601 | permissive | [
{
"docstring": "Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array): Cartesian coordinate data. z (np.array): Cartesian coordinate data. u (np.array): x-component of velocity. v (np.array): y-component of velocity. w (np.array)... | 3 | stack_v2_sparse_classes_30k_train_000431 | Implement the Python class `FlowData` described below.
Class description:
Generate a FlowData object to handle data I/O
Method signatures and docstrings:
- def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None): Initialize FlowData object with coordinates, velocity fields, and meta data. Arg... | Implement the Python class `FlowData` described below.
Class description:
Generate a FlowData object to handle data I/O
Method signatures and docstrings:
- def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None): Initialize FlowData object with coordinates, velocity fields, and meta data. Arg... | 85f2a56fa0ab7c2237d308690a554c6101dbcd34 | <|skeleton|>
class FlowData:
"""Generate a FlowData object to handle data I/O"""
def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None):
"""Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array):... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FlowData:
"""Generate a FlowData object to handle data I/O"""
def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None):
"""Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array): Cartesian co... | the_stack_v2_python_sparse | floris/tools/flow_data.py | PStanfel/floris | train | 3 |
3ef2fa290d4c27dcd1517c1dbad1356382573242 | [
"super().__init__(config)\nself.collector_host = config.get('collector_host')\nself.schedds = config.get('schedds', [None])\nself.condor_config = config.get('condor_config')\nself.constraint = config.get('constraint', True)\nself.classad_attrs = config.get('classad_attrs')\nself.correction_map = config.get('correct... | <|body_start_0|>
super().__init__(config)
self.collector_host = config.get('collector_host')
self.schedds = config.get('schedds', [None])
self.condor_config = config.get('condor_config')
self.constraint = config.get('constraint', True)
self.classad_attrs = config.get('cla... | JobQ | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobQ:
def __init__(self, config):
"""In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002269 | 3,265 | permissive | [
{
"docstring": "In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs.",
"name": "__init__",
"signature": "def __init__(self, config... | 2 | stack_v2_sparse_classes_30k_train_006087 | Implement the Python class `JobQ` described below.
Class description:
Implement the JobQ class.
Method signatures and docstrings:
- def __init__(self, config): In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values... | Implement the Python class `JobQ` described below.
Class description:
Implement the JobQ class.
Method signatures and docstrings:
- def __init__(self, config): In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values... | 842fdc91a31879084906d71a7d0c317e5035a925 | <|skeleton|>
class JobQ:
def __init__(self, config):
"""In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JobQ:
def __init__(self, config):
"""In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs."""
super().__init__(config)
... | the_stack_v2_python_sparse | src/decisionengine_modules/htcondor/sources/job_q.py | HEPCloud/decisionengine_modules | train | 2 | |
2165f2b1d85c1b654466a49e1a333e98e4241e3e | [
"super(W, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\nself.options = options\nself.ret_required = False\nself._is_overwritten = False\nself.current_ret['GENERAL_INFO'] = dict()\nself.current_ret['RESULT'] = list()\nself.headers = list()",
"if self._regex_helpe... | <|body_start_0|>
super(W, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)
self.options = options
self.ret_required = False
self._is_overwritten = False
self.current_ret['GENERAL_INFO'] = dict()
self.current_ret['RESULT'] = ... | W command class. | W | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class W:
"""W command class."""
def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None):
"""W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt tha... | stack_v2_sparse_classes_10k_train_002270 | 9,989 | permissive | [
{
"docstring": "W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt that has been sent by device after command execution. :param newline_chars: Characters to split lines - list. :param runner: Runner to... | 6 | stack_v2_sparse_classes_30k_train_000171 | Implement the Python class `W` described below.
Class description:
W command class.
Method signatures and docstrings:
- def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None): W command. :param connection: Moler connection to device, terminal when command is executed. :param options:... | Implement the Python class `W` described below.
Class description:
W command class.
Method signatures and docstrings:
- def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None): W command. :param connection: Moler connection to device, terminal when command is executed. :param options:... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class W:
"""W command class."""
def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None):
"""W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt tha... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class W:
"""W command class."""
def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None):
"""W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt that has been se... | the_stack_v2_python_sparse | moler/cmd/unix/w.py | nokia/moler | train | 60 |
5c8ff6c1f9d180b00b5a459d6d5ef599d3929317 | [
"intermediate_result = word_tokenize(str_input)\nintermediate_result = BDATextProcessing.__stop_work_removal(intermediate_result)\nintermediate_result = BDATextProcessing.__word_lemmatizing(intermediate_result)\nreturn intermediate_result",
"result = []\nstop_words = set(stopwords.words('english'))\nfor word in s... | <|body_start_0|>
intermediate_result = word_tokenize(str_input)
intermediate_result = BDATextProcessing.__stop_work_removal(intermediate_result)
intermediate_result = BDATextProcessing.__word_lemmatizing(intermediate_result)
return intermediate_result
<|end_body_0|>
<|body_start_1|>
... | BDATextProcessing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BDATextProcessing:
def simplify_text(str_input):
"""Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:"""
<|body_0|>
def __stop_work_removal(str_input):
"""Removes NLTK stop words from input stream :param str_i... | stack_v2_sparse_classes_10k_train_002271 | 1,876 | no_license | [
{
"docstring": "Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:",
"name": "simplify_text",
"signature": "def simplify_text(str_input)"
},
{
"docstring": "Removes NLTK stop words from input stream :param str_input: :return: result",
... | 4 | stack_v2_sparse_classes_30k_train_000417 | Implement the Python class `BDATextProcessing` described below.
Class description:
Implement the BDATextProcessing class.
Method signatures and docstrings:
- def simplify_text(str_input): Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:
- def __stop_work_remo... | Implement the Python class `BDATextProcessing` described below.
Class description:
Implement the BDATextProcessing class.
Method signatures and docstrings:
- def simplify_text(str_input): Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:
- def __stop_work_remo... | 2177d43c75939a0c4906aa3761772365d4bf79e2 | <|skeleton|>
class BDATextProcessing:
def simplify_text(str_input):
"""Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:"""
<|body_0|>
def __stop_work_removal(str_input):
"""Removes NLTK stop words from input stream :param str_i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BDATextProcessing:
def simplify_text(str_input):
"""Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:"""
intermediate_result = word_tokenize(str_input)
intermediate_result = BDATextProcessing.__stop_work_removal(intermediate_res... | the_stack_v2_python_sparse | recording/src/coding_framework/BDATextProcessing.py | eldrad294/ICS5114_Practical_Assignment | train | 0 | |
6e21041c69338a7111dcc3d4b036d2c4ca2e2e44 | [
"if identifier.startswith('T'):\n return ({'message': babel('No information on temp registrations.')}, 200)\nbusiness = Business.find_by_identifier(identifier)\nif not business:\n return (jsonify({'message': f'{identifier} not found'}), HTTPStatus.NOT_FOUND)\nif not authorized(identifier, jwt, action=['view']... | <|body_start_0|>
if identifier.startswith('T'):
return ({'message': babel('No information on temp registrations.')}, 200)
business = Business.find_by_identifier(identifier)
if not business:
return (jsonify({'message': f'{identifier} not found'}), HTTPStatus.NOT_FOUND)
... | Meta information about the overall service. | BusinessResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessResource:
"""Meta information about the overall service."""
def get(identifier: str):
"""Return a JSON object with meta information about the Service."""
<|body_0|>
def post():
"""Create a valid filing, else error out."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k_train_002272 | 4,386 | permissive | [
{
"docstring": "Return a JSON object with meta information about the Service.",
"name": "get",
"signature": "def get(identifier: str)"
},
{
"docstring": "Create a valid filing, else error out.",
"name": "post",
"signature": "def post()"
}
] | 2 | stack_v2_sparse_classes_30k_train_000433 | Implement the Python class `BusinessResource` described below.
Class description:
Meta information about the overall service.
Method signatures and docstrings:
- def get(identifier: str): Return a JSON object with meta information about the Service.
- def post(): Create a valid filing, else error out. | Implement the Python class `BusinessResource` described below.
Class description:
Meta information about the overall service.
Method signatures and docstrings:
- def get(identifier: str): Return a JSON object with meta information about the Service.
- def post(): Create a valid filing, else error out.
<|skeleton|>
c... | d90f11a7b14411b02c07fe97d2c1fc31cd4a9b32 | <|skeleton|>
class BusinessResource:
"""Meta information about the overall service."""
def get(identifier: str):
"""Return a JSON object with meta information about the Service."""
<|body_0|>
def post():
"""Create a valid filing, else error out."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BusinessResource:
"""Meta information about the overall service."""
def get(identifier: str):
"""Return a JSON object with meta information about the Service."""
if identifier.startswith('T'):
return ({'message': babel('No information on temp registrations.')}, 200)
bu... | the_stack_v2_python_sparse | legal-api/src/legal_api/resources/v1/business/business.py | bcgov/lear | train | 13 |
c7222a8ee0733ff066067678fac38469350e9325 | [
"super().__init__(*args, **kwargs)\nself.dag_name = dag_name\nself.input_hook = hook_factory.get_input_hook(input_hook, **kwargs)\nself.output_hook = hook_factory.get_output_hook(output_hook, **kwargs)\nself.return_report = return_report\nself.enable_monitoring = enable_monitoring\nself.is_retry = is_retry\nif enab... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.dag_name = dag_name
self.input_hook = hook_factory.get_input_hook(input_hook, **kwargs)
self.output_hook = hook_factory.get_output_hook(output_hook, **kwargs)
self.return_report = return_report
self.enable_monitoring... | Custom Operator to send data from an input hook to an output hook. | DataConnectorOperator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataConnectorOperator:
"""Custom Operator to send data from an input hook to an output hook."""
def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monitoring_dataset: str='', monitoring_table: str='', monitoring_bq_conn_... | stack_v2_sparse_classes_10k_train_002273 | 5,361 | permissive | [
{
"docstring": "Initiates the DataConnectorOperator. Args: *args: arguments for the operator. input_hook: The type of the input hook. output_hook: The type of the output hook. dag_name: The ID of the current running dag. monitoring_dataset: Dataset id of the monitoring table. monitoring_table: Table name of the... | 2 | stack_v2_sparse_classes_30k_train_006341 | Implement the Python class `DataConnectorOperator` described below.
Class description:
Custom Operator to send data from an input hook to an output hook.
Method signatures and docstrings:
- def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monit... | Implement the Python class `DataConnectorOperator` described below.
Class description:
Custom Operator to send data from an input hook to an output hook.
Method signatures and docstrings:
- def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monit... | 031f21680c8646c9d2d39d589c581a9bc9796424 | <|skeleton|>
class DataConnectorOperator:
"""Custom Operator to send data from an input hook to an output hook."""
def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monitoring_dataset: str='', monitoring_table: str='', monitoring_bq_conn_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataConnectorOperator:
"""Custom Operator to send data from an input hook to an output hook."""
def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monitoring_dataset: str='', monitoring_table: str='', monitoring_bq_conn_id: str='', r... | the_stack_v2_python_sparse | src/dags/dependencies/tcrm/operators/data_connector_operator.py | Ressmann/blockbuster | train | 0 |
52b989eb48d45c51964beca7ce85a4cb7a654c78 | [
"mtz_file = mtz.object()\nmtz_file.set_title(f'From {env.dispatcher_name}')\ndate_str = time.strftime('%Y-%m-%d at %H:%M:%S %Z')\nif time.strftime('%Z') != 'GMT':\n date_str += time.strftime(' (%Y-%m-%d at %H:%M:%S %Z)', time.gmtime())\nmtz_file.add_history(f'From {dials_version()}, run on {date_str}')\nmtz_fil... | <|body_start_0|>
mtz_file = mtz.object()
mtz_file.set_title(f'From {env.dispatcher_name}')
date_str = time.strftime('%Y-%m-%d at %H:%M:%S %Z')
if time.strftime('%Z') != 'GMT':
date_str += time.strftime(' (%Y-%m-%d at %H:%M:%S %Z)', time.gmtime())
mtz_file.add_history... | Helper for adding metadata, crystals and datasets to an mtz file object. | MTZWriterBase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTZWriterBase:
"""Helper for adding metadata, crystals and datasets to an mtz file object."""
def __init__(self, space_group, unit_cell=None):
"""If a unit cell is provided, will be used as default unless specified for each crystal."""
<|body_0|>
def add_crystal(self, cr... | stack_v2_sparse_classes_10k_train_002274 | 23,243 | permissive | [
{
"docstring": "If a unit cell is provided, will be used as default unless specified for each crystal.",
"name": "__init__",
"signature": "def __init__(self, space_group, unit_cell=None)"
},
{
"docstring": "Add a crystal to the mtz file object.",
"name": "add_crystal",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_005806 | Implement the Python class `MTZWriterBase` described below.
Class description:
Helper for adding metadata, crystals and datasets to an mtz file object.
Method signatures and docstrings:
- def __init__(self, space_group, unit_cell=None): If a unit cell is provided, will be used as default unless specified for each cry... | Implement the Python class `MTZWriterBase` described below.
Class description:
Helper for adding metadata, crystals and datasets to an mtz file object.
Method signatures and docstrings:
- def __init__(self, space_group, unit_cell=None): If a unit cell is provided, will be used as default unless specified for each cry... | e611c7680a02b5766a8f476557834daf6361d124 | <|skeleton|>
class MTZWriterBase:
"""Helper for adding metadata, crystals and datasets to an mtz file object."""
def __init__(self, space_group, unit_cell=None):
"""If a unit cell is provided, will be used as default unless specified for each crystal."""
<|body_0|>
def add_crystal(self, cr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MTZWriterBase:
"""Helper for adding metadata, crystals and datasets to an mtz file object."""
def __init__(self, space_group, unit_cell=None):
"""If a unit cell is provided, will be used as default unless specified for each crystal."""
mtz_file = mtz.object()
mtz_file.set_title(f'... | the_stack_v2_python_sparse | util/export_mtz.py | dagewa/dials | train | 1 |
d3afad4242879ffdf9cbb34934755f24a0b54f99 | [
"self.open(base_url + '/logout')\nself.open(base_url + '/login')\nself.type('#password', generate_password_hash('test_password'))\nself.click('input[type=\"submit\"]')\nself.assert_element('#message')\nself.assert_text('Email format incorrect: Cannot be empty', '#message')",
"self.open(base_url + '/logout')\nself... | <|body_start_0|>
self.open(base_url + '/logout')
self.open(base_url + '/login')
self.type('#password', generate_password_hash('test_password'))
self.click('input[type="submit"]')
self.assert_element('#message')
self.assert_text('Email format incorrect: Cannot be empty', '... | FrontEndLoginR1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrontEndLoginR1:
def test_loginFormEmailEmpty(self, *_):
"""This function tests that the user form cannot be empty, if email is empty the message warns the user with an error message"""
<|body_0|>
def test_loginFormPassEmpty(self, *_):
"""This function tests that the... | stack_v2_sparse_classes_10k_train_002275 | 1,752 | permissive | [
{
"docstring": "This function tests that the user form cannot be empty, if email is empty the message warns the user with an error message",
"name": "test_loginFormEmailEmpty",
"signature": "def test_loginFormEmailEmpty(self, *_)"
},
{
"docstring": "This function tests that the user form cannot ... | 2 | stack_v2_sparse_classes_30k_train_001793 | Implement the Python class `FrontEndLoginR1` described below.
Class description:
Implement the FrontEndLoginR1 class.
Method signatures and docstrings:
- def test_loginFormEmailEmpty(self, *_): This function tests that the user form cannot be empty, if email is empty the message warns the user with an error message
-... | Implement the Python class `FrontEndLoginR1` described below.
Class description:
Implement the FrontEndLoginR1 class.
Method signatures and docstrings:
- def test_loginFormEmailEmpty(self, *_): This function tests that the user form cannot be empty, if email is empty the message warns the user with an error message
-... | 582e00a4c16016e545fedcbb14a745d125db94e0 | <|skeleton|>
class FrontEndLoginR1:
def test_loginFormEmailEmpty(self, *_):
"""This function tests that the user form cannot be empty, if email is empty the message warns the user with an error message"""
<|body_0|>
def test_loginFormPassEmpty(self, *_):
"""This function tests that the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FrontEndLoginR1:
def test_loginFormEmailEmpty(self, *_):
"""This function tests that the user form cannot be empty, if email is empty the message warns the user with an error message"""
self.open(base_url + '/logout')
self.open(base_url + '/login')
self.type('#password', genera... | the_stack_v2_python_sparse | qa327_test/frontend/login/test_R1_6.py | GraemeBadley/QA-Project | train | 0 | |
689a23e578063f29e15e85e0fe6572fb5a382aa8 | [
"Figure.__init__(self, name=name)\nself.xvar, self.yvar = (xvar, yvar)\nself.render(data, **kwargs)",
"self.fig = self.create_figure(figsize)\nself.add_axes()\nself._add_markers(data[self.xvar], data[self.yvar], c='k', s=1)\nself.format()",
"_ = ax.spines['top'].set_visible(False)\n_ = ax.spines['right'].set_vi... | <|body_start_0|>
Figure.__init__(self, name=name)
self.xvar, self.yvar = (xvar, yvar)
self.render(data, **kwargs)
<|end_body_0|>
<|body_start_1|>
self.fig = self.create_figure(figsize)
self.add_axes()
self._add_markers(data[self.xvar], data[self.yvar], c='k', s=1)
... | Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots) | Scatterplot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scatterplot:
"""Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots)"""
def __ini... | stack_v2_sparse_classes_10k_train_002276 | 8,479 | permissive | [
{
"docstring": "Instantiate scatter plot. Args: data (pd.DataFrame) - selected cell measurement data xvar, yvar (str) - cell measurement features to be scattered name (str) - figure name kwargs: keyword arguments for",
"name": "__init__",
"signature": "def __init__(self, data, xvar, yvar, name, **kwargs... | 3 | stack_v2_sparse_classes_30k_train_000206 | Implement the Python class `Scatterplot` described below.
Class description:
Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotl... | Implement the Python class `Scatterplot` described below.
Class description:
Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotl... | 4a622c3f5fed4456c3b9240f5a96428789fde9bd | <|skeleton|>
class Scatterplot:
"""Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots)"""
def __ini... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Scatterplot:
"""Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots)"""
def __init__(self, dat... | the_stack_v2_python_sparse | flyqma/visualization/figures.py | sbernasek/flyqma | train | 1 |
47ae6aae0321307823f97613e97d8a51af22d6e4 | [
"max_shape = self._find_max_shape(self.fovlist)\nfig = plt.figure(figsize=(20, 16))\ngs = gridspec.GridSpec(max_shape[0], 16, figure=fig)\nself._plot_traces_with_cell_img(self.fovlist, gs, max_shape)",
"shapes = []\nnum_of_labeled = 0\nfor fov in fovlist:\n shapes.append(fov.all_data.shape)\n try:\n ... | <|body_start_0|>
max_shape = self._find_max_shape(self.fovlist)
fig = plt.figure(figsize=(20, 16))
gs = gridspec.GridSpec(max_shape[0], 16, figure=fig)
self._plot_traces_with_cell_img(self.fovlist, gs, max_shape)
<|end_body_0|>
<|body_start_1|>
shapes = []
num_of_labeled... | Plots a simple comparison of the dF/F traces that originated from the unlabeled cells and the labeled cells. | ShowLabeledAndUnlabeled | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowLabeledAndUnlabeled:
"""Plots a simple comparison of the dF/F traces that originated from the unlabeled cells and the labeled cells."""
def run(self):
"""Main pipeline"""
<|body_0|>
def _find_max_shape(self, fovlist):
"""Iterate over the found files and decid... | stack_v2_sparse_classes_10k_train_002277 | 11,294 | permissive | [
{
"docstring": "Main pipeline",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Iterate over the found files and decide upon the shape of the array that will hold the stacked data. This is useful when the number of measurements in each FOV was unequal.",
"name": "_find_max_sha... | 5 | stack_v2_sparse_classes_30k_train_005504 | Implement the Python class `ShowLabeledAndUnlabeled` described below.
Class description:
Plots a simple comparison of the dF/F traces that originated from the unlabeled cells and the labeled cells.
Method signatures and docstrings:
- def run(self): Main pipeline
- def _find_max_shape(self, fovlist): Iterate over the ... | Implement the Python class `ShowLabeledAndUnlabeled` described below.
Class description:
Plots a simple comparison of the dF/F traces that originated from the unlabeled cells and the labeled cells.
Method signatures and docstrings:
- def run(self): Main pipeline
- def _find_max_shape(self, fovlist): Iterate over the ... | 87fcca6fd79f65122b4010d2225d10403450da7e | <|skeleton|>
class ShowLabeledAndUnlabeled:
"""Plots a simple comparison of the dF/F traces that originated from the unlabeled cells and the labeled cells."""
def run(self):
"""Main pipeline"""
<|body_0|>
def _find_max_shape(self, fovlist):
"""Iterate over the found files and decid... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShowLabeledAndUnlabeled:
"""Plots a simple comparison of the dF/F traces that originated from the unlabeled cells and the labeled cells."""
def run(self):
"""Main pipeline"""
max_shape = self._find_max_shape(self.fovlist)
fig = plt.figure(figsize=(20, 16))
gs = gridspec.Gr... | the_stack_v2_python_sparse | calcium_bflow_analysis/colabeled_cells/compare_labeled_unlabeled.py | PBLab/ca-analysis-bloodflow | train | 0 |
de213f968fcfdc57117ad8bd0f5270a113f38785 | [
"courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}\nresult = validate_courses(courses)\nself.assertEqual(result, ['CSC300', 'CSC200', 'CSC100'])",
"courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': [], 'BIO101': [], 'BIO102': ['BIO101'], 'BIO300': ['BIO101', '... | <|body_start_0|>
courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}
result = validate_courses(courses)
self.assertEqual(result, ['CSC300', 'CSC200', 'CSC100'])
<|end_body_0|>
<|body_start_1|>
courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'C... | TestValidateCourses | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestValidateCourses:
def test_courses_short_list(self):
"""This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument"""
<|body_0|>
def test_courses_long_list(self):
"""This test checks to... | stack_v2_sparse_classes_10k_train_002278 | 1,599 | permissive | [
{
"docstring": "This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument",
"name": "test_courses_short_list",
"signature": "def test_courses_short_list(self)"
},
{
"docstring": "This test checks to see if a valid lo... | 3 | null | Implement the Python class `TestValidateCourses` described below.
Class description:
Implement the TestValidateCourses class.
Method signatures and docstrings:
- def test_courses_short_list(self): This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses(... | Implement the Python class `TestValidateCourses` described below.
Class description:
Implement the TestValidateCourses class.
Method signatures and docstrings:
- def test_courses_short_list(self): This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses(... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class TestValidateCourses:
def test_courses_short_list(self):
"""This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument"""
<|body_0|>
def test_courses_long_list(self):
"""This test checks to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestValidateCourses:
def test_courses_short_list(self):
"""This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument"""
courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}
result ... | the_stack_v2_python_sparse | src/daily-coding-problem/hard/validate-courses/test_validate_courses.py | nwthomas/code-challenges | train | 2 | |
6d83e3273401ebbafb25ea5d9be6f4f43936e9f6 | [
"super(BaselineDNN, self).__init__()\n...\n...\n...\n...\n...",
"embeddings = ...\nrepresentations = ...\nrepresentations = ...\nlogits = ...\nreturn logits"
] | <|body_start_0|>
super(BaselineDNN, self).__init__()
...
...
...
...
...
<|end_body_0|>
<|body_start_1|>
embeddings = ...
representations = ...
representations = ...
logits = ...
return logits
<|end_body_1|>
| 1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes.ngth) | BaselineDNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaselineDNN:
"""1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes.ngth)"""... | stack_v2_sparse_classes_10k_train_002279 | 1,913 | permissive | [
{
"docstring": "Args: output_size(int): the number of classes embeddings(bool): the 2D matrix with the pretrained embeddings trainable_emb(bool): train (finetune) or freeze the weights the embedding layer",
"name": "__init__",
"signature": "def __init__(self, output_size, embeddings, trainable_emb=False... | 2 | stack_v2_sparse_classes_30k_train_003459 | Implement the Python class `BaselineDNN` described below.
Class description:
1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the represent... | Implement the Python class `BaselineDNN` described below.
Class description:
1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the represent... | 37b06ac0bff1e380335912d9b442f884aeb3476d | <|skeleton|>
class BaselineDNN:
"""1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes.ngth)"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaselineDNN:
"""1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes.ngth)"""
def __i... | the_stack_v2_python_sparse | lab3/models.py | DidoStoikou/slp-labs | train | 0 |
f011d29e69b62a8de87cdccba2dbb613ca76945a | [
"super().__init__(datapipe, self._read)\nself.feature_store = feature_store\nself.node_feature_keys = node_feature_keys\nself.edge_feature_keys = edge_feature_keys",
"data.node_features = {}\nnum_layer = len(data.sampled_subgraphs) if data.sampled_subgraphs else 0\ndata.edge_features = [{} for _ in range(num_laye... | <|body_start_0|>
super().__init__(datapipe, self._read)
self.feature_store = feature_store
self.node_feature_keys = node_feature_keys
self.edge_feature_keys = edge_feature_keys
<|end_body_0|>
<|body_start_1|>
data.node_features = {}
num_layer = len(data.sampled_subgraphs... | A feature fetcher used to fetch features for node/edge in graphbolt. | FeatureFetcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureFetcher:
"""A feature fetcher used to fetch features for node/edge in graphbolt."""
def __init__(self, datapipe, feature_store, node_feature_keys=None, edge_feature_keys=None):
"""Initlization for a feature fetcher. Parameters ---------- datapipe : DataPipe The datapipe. featu... | stack_v2_sparse_classes_10k_train_002280 | 4,846 | permissive | [
{
"docstring": "Initlization for a feature fetcher. Parameters ---------- datapipe : DataPipe The datapipe. feature_store : FeatureStore A storage for features, support read and update. node_feature_keys : List[str] or Dict[str, List[str]] Node features keys indicates the node features need to be read. - If `no... | 2 | null | Implement the Python class `FeatureFetcher` described below.
Class description:
A feature fetcher used to fetch features for node/edge in graphbolt.
Method signatures and docstrings:
- def __init__(self, datapipe, feature_store, node_feature_keys=None, edge_feature_keys=None): Initlization for a feature fetcher. Para... | Implement the Python class `FeatureFetcher` described below.
Class description:
A feature fetcher used to fetch features for node/edge in graphbolt.
Method signatures and docstrings:
- def __init__(self, datapipe, feature_store, node_feature_keys=None, edge_feature_keys=None): Initlization for a feature fetcher. Para... | bbc8ff6261f2e0d2b5982e992b6fbe545e2a4aa1 | <|skeleton|>
class FeatureFetcher:
"""A feature fetcher used to fetch features for node/edge in graphbolt."""
def __init__(self, datapipe, feature_store, node_feature_keys=None, edge_feature_keys=None):
"""Initlization for a feature fetcher. Parameters ---------- datapipe : DataPipe The datapipe. featu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeatureFetcher:
"""A feature fetcher used to fetch features for node/edge in graphbolt."""
def __init__(self, datapipe, feature_store, node_feature_keys=None, edge_feature_keys=None):
"""Initlization for a feature fetcher. Parameters ---------- datapipe : DataPipe The datapipe. feature_store : Fe... | the_stack_v2_python_sparse | python/dgl/graphbolt/feature_fetcher.py | dmlc/dgl | train | 12,631 |
3c50a64ffc3294bbe3e19cff20596dfe35a5a8b1 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceConfigurationSettingState()",
"from .compliance_status import ComplianceStatus\nfrom .setting_source import SettingSource\nfrom .compliance_status import ComplianceStatus\nfrom .setting_source import SettingSource\nfields: Dict[s... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceConfigurationSettingState()
<|end_body_0|>
<|body_start_1|>
from .compliance_status import ComplianceStatus
from .setting_source import SettingSource
from .compliance_statu... | Device Configuration Setting State for a given device. | DeviceConfigurationSettingState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceConfigurationSettingState:
"""Device Configuration Setting State for a given device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState:
"""Creates a new instance of the appropriate class based on discriminator value ... | stack_v2_sparse_classes_10k_train_002281 | 5,456 | 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: DeviceConfigurationSettingState",
"name": "create_from_discriminator_value",
"signature": "def create_from_d... | 3 | null | Implement the Python class `DeviceConfigurationSettingState` described below.
Class description:
Device Configuration Setting State for a given device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState: Creates a new instan... | Implement the Python class `DeviceConfigurationSettingState` described below.
Class description:
Device Configuration Setting State for a given device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState: Creates a new instan... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceConfigurationSettingState:
"""Device Configuration Setting State for a given device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState:
"""Creates a new instance of the appropriate class based on discriminator value ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeviceConfigurationSettingState:
"""Device Configuration Setting State for a given device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_n... | the_stack_v2_python_sparse | msgraph/generated/models/device_configuration_setting_state.py | microsoftgraph/msgraph-sdk-python | train | 135 |
211ee0ce1ab31abfd625e1e603f21f2bf180e5a5 | [
"JobRunner.__init__(self)\nself.setParam('batchqueue', 'workday', 'Batch queue')\nfor k in params.keys():\n self.setParam(k, params[k])\nself.checkParams()",
"condorScript = condorScriptTemplate % jobConfig\nprint(condorScript)\nscript = open('condorSubmit.sub', 'w')\nscript.write(condorScript)\nscript.close()... | <|body_start_0|>
JobRunner.__init__(self)
self.setParam('batchqueue', 'workday', 'Batch queue')
for k in params.keys():
self.setParam(k, params[k])
self.checkParams()
<|end_body_0|>
<|body_start_1|>
condorScript = condorScriptTemplate % jobConfig
print(condor... | HTCondorJobRunner - run jobs using the HTCondor batch system | HTCondorJobRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTCondorJobRunner:
"""HTCondorJobRunner - run jobs using the HTCondor batch system"""
def __init__(self, **params):
"""Constructor (takes any number of parameters as an argument)."""
<|body_0|>
def submitJob(self, jobConfig):
"""Submit a JobRunner job as a LSF ba... | stack_v2_sparse_classes_10k_train_002282 | 1,782 | permissive | [
{
"docstring": "Constructor (takes any number of parameters as an argument).",
"name": "__init__",
"signature": "def __init__(self, **params)"
},
{
"docstring": "Submit a JobRunner job as a LSF batch job.",
"name": "submitJob",
"signature": "def submitJob(self, jobConfig)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000191 | Implement the Python class `HTCondorJobRunner` described below.
Class description:
HTCondorJobRunner - run jobs using the HTCondor batch system
Method signatures and docstrings:
- def __init__(self, **params): Constructor (takes any number of parameters as an argument).
- def submitJob(self, jobConfig): Submit a JobR... | Implement the Python class `HTCondorJobRunner` described below.
Class description:
HTCondorJobRunner - run jobs using the HTCondor batch system
Method signatures and docstrings:
- def __init__(self, **params): Constructor (takes any number of parameters as an argument).
- def submitJob(self, jobConfig): Submit a JobR... | 354f92551294f7be678aebcd7b9d67d2c4448176 | <|skeleton|>
class HTCondorJobRunner:
"""HTCondorJobRunner - run jobs using the HTCondor batch system"""
def __init__(self, **params):
"""Constructor (takes any number of parameters as an argument)."""
<|body_0|>
def submitJob(self, jobConfig):
"""Submit a JobRunner job as a LSF ba... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HTCondorJobRunner:
"""HTCondorJobRunner - run jobs using the HTCondor batch system"""
def __init__(self, **params):
"""Constructor (takes any number of parameters as an argument)."""
JobRunner.__init__(self)
self.setParam('batchqueue', 'workday', 'Batch queue')
for k in pa... | the_stack_v2_python_sparse | InnerDetector/InDetExample/InDetBeamSpotExample/python/HTCondorJobRunner.py | strigazi/athena | train | 0 |
e5e8f20f1c2d992ca4e010d7fda8c7b3a97f46c0 | [
"assert len(images) == 2, AttributeError('Can stitch only two images')\nself.images = images\nself.nfeatures = nfeatures\nself.details = details\nself.keypoints = []\nself.descriptors = []\nself.good_matches = []",
"orb = ORB_create(nfeatures=self.nfeatures)\nkeypoints1, descriptors1 = orb.detectAndCompute(self.i... | <|body_start_0|>
assert len(images) == 2, AttributeError('Can stitch only two images')
self.images = images
self.nfeatures = nfeatures
self.details = details
self.keypoints = []
self.descriptors = []
self.good_matches = []
<|end_body_0|>
<|body_start_1|>
... | The Stitcher class implements manual stitching between two images. Panorama (stitch) algorithm: - Detect keypoints and descriptors. - Detect a set of matching points that is present in both images (overlapping area). - Apply the RANSAC method to improve the matching process detection. - Apply perspective transformation... | Stitcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stitcher:
"""The Stitcher class implements manual stitching between two images. Panorama (stitch) algorithm: - Detect keypoints and descriptors. - Detect a set of matching points that is present in both images (overlapping area). - Apply the RANSAC method to improve the matching process detection... | stack_v2_sparse_classes_10k_train_002283 | 6,130 | permissive | [
{
"docstring": "Create a new Stitcher instance. :param images: The two images to stitch :type images: list :param nfeatures: The maximum number of features to be detected in each image :type nfeatures: int :param details: The flag to indicate whether show keypoints or not :type details: bool",
"name": "__in... | 5 | stack_v2_sparse_classes_30k_train_003379 | Implement the Python class `Stitcher` described below.
Class description:
The Stitcher class implements manual stitching between two images. Panorama (stitch) algorithm: - Detect keypoints and descriptors. - Detect a set of matching points that is present in both images (overlapping area). - Apply the RANSAC method to... | Implement the Python class `Stitcher` described below.
Class description:
The Stitcher class implements manual stitching between two images. Panorama (stitch) algorithm: - Detect keypoints and descriptors. - Detect a set of matching points that is present in both images (overlapping area). - Apply the RANSAC method to... | 5613440dc04140845600b8c37a2b28786d504815 | <|skeleton|>
class Stitcher:
"""The Stitcher class implements manual stitching between two images. Panorama (stitch) algorithm: - Detect keypoints and descriptors. - Detect a set of matching points that is present in both images (overlapping area). - Apply the RANSAC method to improve the matching process detection... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Stitcher:
"""The Stitcher class implements manual stitching between two images. Panorama (stitch) algorithm: - Detect keypoints and descriptors. - Detect a set of matching points that is present in both images (overlapping area). - Apply the RANSAC method to improve the matching process detection. - Apply per... | the_stack_v2_python_sparse | src/panorama/stitcher.py | vmariiechko/python-image-processing | train | 2 |
56193e4a7cfda0884088689b116a56ef6c698665 | [
"if params:\n raise ValueError(f'Observation parameters not supported; passed {params}')\npieces = [('player', 2, (2,))]\nif iig_obs_type.private_info == pyspiel.PrivateInfoType.SINGLE_PLAYER:\n pieces.append(('private_card', 3, (3,)))\nif iig_obs_type.public_info:\n if iig_obs_type.perfect_recall:\n ... | <|body_start_0|>
if params:
raise ValueError(f'Observation parameters not supported; passed {params}')
pieces = [('player', 2, (2,))]
if iig_obs_type.private_info == pyspiel.PrivateInfoType.SINGLE_PLAYER:
pieces.append(('private_card', 3, (3,)))
if iig_obs_type.pu... | Observer, conforming to the PyObserver interface (see observation.py). | KuhnPokerObserver | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KuhnPokerObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
def __init__(self, iig_obs_type, params):
"""Initializes an empty observation tensor."""
<|body_0|>
def set_from(self, state, player):
"""Updates `tensor` and `dict` t... | stack_v2_sparse_classes_10k_train_002284 | 7,683 | permissive | [
{
"docstring": "Initializes an empty observation tensor.",
"name": "__init__",
"signature": "def __init__(self, iig_obs_type, params)"
},
{
"docstring": "Updates `tensor` and `dict` to reflect `state` from PoV of `player`.",
"name": "set_from",
"signature": "def set_from(self, state, pla... | 3 | null | Implement the Python class `KuhnPokerObserver` described below.
Class description:
Observer, conforming to the PyObserver interface (see observation.py).
Method signatures and docstrings:
- def __init__(self, iig_obs_type, params): Initializes an empty observation tensor.
- def set_from(self, state, player): Updates ... | Implement the Python class `KuhnPokerObserver` described below.
Class description:
Observer, conforming to the PyObserver interface (see observation.py).
Method signatures and docstrings:
- def __init__(self, iig_obs_type, params): Initializes an empty observation tensor.
- def set_from(self, state, player): Updates ... | 6f3551fd990053cf2287b380fb9ad0b2a2607c18 | <|skeleton|>
class KuhnPokerObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
def __init__(self, iig_obs_type, params):
"""Initializes an empty observation tensor."""
<|body_0|>
def set_from(self, state, player):
"""Updates `tensor` and `dict` t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KuhnPokerObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
def __init__(self, iig_obs_type, params):
"""Initializes an empty observation tensor."""
if params:
raise ValueError(f'Observation parameters not supported; passed {params}')
... | the_stack_v2_python_sparse | open_spiel/python/games/kuhn_poker.py | sarahperrin/open_spiel | train | 3 |
70bc1997ebe1d638bb68e184e23626b1691aec92 | [
"if self.initial_extra:\n return 0\nelse:\n return forms.BaseInlineFormSet.initial_form_count(self)",
"if self.initial_extra:\n count = len(self.initial_extra) if self.initial_extra else 0\n count += self.extra\n return count\nelse:\n return forms.BaseInlineFormSet.total_form_count(self)"
] | <|body_start_0|>
if self.initial_extra:
return 0
else:
return forms.BaseInlineFormSet.initial_form_count(self)
<|end_body_0|>
<|body_start_1|>
if self.initial_extra:
count = len(self.initial_extra) if self.initial_extra else 0
count += self.extra
... | Custom formset that support initial data | CustomInlineFormset | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomInlineFormset:
"""Custom formset that support initial data"""
def initial_form_count(self):
"""set 0 to use initial_extra explicitly."""
<|body_0|>
def total_form_count(self):
"""here use the initial_extra len to determine needed forms"""
<|body_1|>... | stack_v2_sparse_classes_10k_train_002285 | 7,933 | permissive | [
{
"docstring": "set 0 to use initial_extra explicitly.",
"name": "initial_form_count",
"signature": "def initial_form_count(self)"
},
{
"docstring": "here use the initial_extra len to determine needed forms",
"name": "total_form_count",
"signature": "def total_form_count(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004474 | Implement the Python class `CustomInlineFormset` described below.
Class description:
Custom formset that support initial data
Method signatures and docstrings:
- def initial_form_count(self): set 0 to use initial_extra explicitly.
- def total_form_count(self): here use the initial_extra len to determine needed forms | Implement the Python class `CustomInlineFormset` described below.
Class description:
Custom formset that support initial data
Method signatures and docstrings:
- def initial_form_count(self): set 0 to use initial_extra explicitly.
- def total_form_count(self): here use the initial_extra len to determine needed forms
... | 5367a8aed309fade0f17bc72efa099b0afc76aa7 | <|skeleton|>
class CustomInlineFormset:
"""Custom formset that support initial data"""
def initial_form_count(self):
"""set 0 to use initial_extra explicitly."""
<|body_0|>
def total_form_count(self):
"""here use the initial_extra len to determine needed forms"""
<|body_1|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomInlineFormset:
"""Custom formset that support initial data"""
def initial_form_count(self):
"""set 0 to use initial_extra explicitly."""
if self.initial_extra:
return 0
else:
return forms.BaseInlineFormSet.initial_form_count(self)
def total_form_... | the_stack_v2_python_sparse | mc2/controllers/base/forms.py | praekeltfoundation/mc2 | train | 0 |
fff7b890da23348a6c8b6afa9e22bb9afec32872 | [
"article = ArticleInst.fetch(slug)\ntry:\n comment = Comment.objects.get(pk=id, article=article)\nexcept Comment.DoesNotExist:\n data = {'error': f'Comment of ID {id} nonexistent'}\n status_ = status.HTTP_404_NOT_FOUND\nelse:\n serializer = self.serializer_class(comment)\n status_ = status.HTTP_200_O... | <|body_start_0|>
article = ArticleInst.fetch(slug)
try:
comment = Comment.objects.get(pk=id, article=article)
except Comment.DoesNotExist:
data = {'error': f'Comment of ID {id} nonexistent'}
status_ = status.HTTP_404_NOT_FOUND
else:
seriali... | Creates, Updates and Deletes a single comment | CommentAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentAPIView:
"""Creates, Updates and Deletes a single comment"""
def get(self, request, slug, id):
"""Fetches a comment on an article"""
<|body_0|>
def update(self, request, slug, id):
"""Updates an existing comment"""
<|body_1|>
def destroy(self,... | stack_v2_sparse_classes_10k_train_002286 | 10,918 | permissive | [
{
"docstring": "Fetches a comment on an article",
"name": "get",
"signature": "def get(self, request, slug, id)"
},
{
"docstring": "Updates an existing comment",
"name": "update",
"signature": "def update(self, request, slug, id)"
},
{
"docstring": "Removes a comment from an arti... | 4 | stack_v2_sparse_classes_30k_train_007358 | Implement the Python class `CommentAPIView` described below.
Class description:
Creates, Updates and Deletes a single comment
Method signatures and docstrings:
- def get(self, request, slug, id): Fetches a comment on an article
- def update(self, request, slug, id): Updates an existing comment
- def destroy(self, req... | Implement the Python class `CommentAPIView` described below.
Class description:
Creates, Updates and Deletes a single comment
Method signatures and docstrings:
- def get(self, request, slug, id): Fetches a comment on an article
- def update(self, request, slug, id): Updates an existing comment
- def destroy(self, req... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class CommentAPIView:
"""Creates, Updates and Deletes a single comment"""
def get(self, request, slug, id):
"""Fetches a comment on an article"""
<|body_0|>
def update(self, request, slug, id):
"""Updates an existing comment"""
<|body_1|>
def destroy(self,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommentAPIView:
"""Creates, Updates and Deletes a single comment"""
def get(self, request, slug, id):
"""Fetches a comment on an article"""
article = ArticleInst.fetch(slug)
try:
comment = Comment.objects.get(pk=id, article=article)
except Comment.DoesNotExist:... | the_stack_v2_python_sparse | authors/apps/comments/views.py | deferral/ah-django | train | 1 |
bb003d516105792ed8a10df40845499e9ef8b639 | [
"io.logger.debug('FarFieldIntensity forward 1')\nwave_shifted = wave.ifftshift((3, 4))\nwave_farfield = wave_shifted.fft2_()\nctx.wave_farfield = wave_farfield\nctx.gradient_mask = gradient_mask\nI_model = th.cuda.FloatTensor(wave.size())\nwave_farfield.expect(out=I_model)\nfor dim in range(1, I_model.ndimension() ... | <|body_start_0|>
io.logger.debug('FarFieldIntensity forward 1')
wave_shifted = wave.ifftshift((3, 4))
wave_farfield = wave_shifted.fft2_()
ctx.wave_farfield = wave_farfield
ctx.gradient_mask = gradient_mask
I_model = th.cuda.FloatTensor(wave.size())
wave_farfield.... | FarFieldIntensityNoSubpixel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FarFieldIntensityNoSubpixel:
def forward(ctx, wave, gradient_mask):
"""Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities"""
<|body_0|>
def backward(ctx, grad_output):
"""bac... | stack_v2_sparse_classes_10k_train_002287 | 2,707 | permissive | [
{
"docstring": "Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities",
"name": "forward",
"signature": "def forward(ctx, wave, gradient_mask)"
},
{
"docstring": "backward. Parameters ---------- grad_output... | 2 | stack_v2_sparse_classes_30k_train_000917 | Implement the Python class `FarFieldIntensityNoSubpixel` described below.
Class description:
Implement the FarFieldIntensityNoSubpixel class.
Method signatures and docstrings:
- def forward(ctx, wave, gradient_mask): Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M... | Implement the Python class `FarFieldIntensityNoSubpixel` described below.
Class description:
Implement the FarFieldIntensityNoSubpixel class.
Method signatures and docstrings:
- def forward(ctx, wave, gradient_mask): Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M... | 50833b13160b6afe0a743d63d560bddeee2c18b5 | <|skeleton|>
class FarFieldIntensityNoSubpixel:
def forward(ctx, wave, gradient_mask):
"""Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities"""
<|body_0|>
def backward(ctx, grad_output):
"""bac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FarFieldIntensityNoSubpixel:
def forward(ctx, wave, gradient_mask):
"""Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities"""
io.logger.debug('FarFieldIntensity forward 1')
wave_shifted = wave.i... | the_stack_v2_python_sparse | skpr/nn/_functions/FarfieldIntensityNoSubpixel.py | 1034776739/scikit-pr-open | train | 0 | |
cf2989a1475be7f01e38af99e8c92b541d370bf2 | [
"assert branches, 'At least one branch is required'\nif __debug__:\n for branch in branches:\n assert isinstance(branch, IBranch), 'Invalid branch %s' % branch\nself.branches = branches\nsuper().__init__(function)",
"assert isinstance(calls, list), 'Invalid calls %s' % calls\nassert isinstance(report, I... | <|body_start_0|>
assert branches, 'At least one branch is required'
if __debug__:
for branch in branches:
assert isinstance(branch, IBranch), 'Invalid branch %s' % branch
self.branches = branches
super().__init__(function)
<|end_body_0|>
<|body_start_1|>
... | Implementation for @see: IProcessor that provides branching of other processors containers. | Brancher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Brancher:
"""Implementation for @see: IProcessor that provides branching of other processors containers."""
def __init__(self, function, *branches):
"""Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching.""... | stack_v2_sparse_classes_10k_train_002288 | 19,255 | no_license | [
{
"docstring": "Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching.",
"name": "__init__",
"signature": "def __init__(self, function, *branches)"
},
{
"docstring": "@see: IProcessor.register",
"name": "register",
... | 3 | stack_v2_sparse_classes_30k_train_002872 | Implement the Python class `Brancher` described below.
Class description:
Implementation for @see: IProcessor that provides branching of other processors containers.
Method signatures and docstrings:
- def __init__(self, function, *branches): Construct the branching processor. @see: Contextual.__init__ @param branche... | Implement the Python class `Brancher` described below.
Class description:
Implementation for @see: IProcessor that provides branching of other processors containers.
Method signatures and docstrings:
- def __init__(self, function, *branches): Construct the branching processor. @see: Contextual.__init__ @param branche... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class Brancher:
"""Implementation for @see: IProcessor that provides branching of other processors containers."""
def __init__(self, function, *branches):
"""Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching.""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Brancher:
"""Implementation for @see: IProcessor that provides branching of other processors containers."""
def __init__(self, function, *branches):
"""Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching."""
ass... | the_stack_v2_python_sparse | components/ally/ally/design/processor/processor.py | cristidomsa/Ally-Py | train | 0 |
9a271f9b08b3c1b6fd0d99f87872cbeb78d93115 | [
"if db_field.name == 'dep':\n if not request.user.is_superuser:\n kwargs['queryset'] = Department.objects.filter(id=request.user.profile.department.id)\n else:\n kwargs['queryset'] = Department.objects.all()\nelif db_field.name == 'faculty' and request.user.is_superuser:\n kwargs['queryset'] ... | <|body_start_0|>
if db_field.name == 'dep':
if not request.user.is_superuser:
kwargs['queryset'] = Department.objects.filter(id=request.user.profile.department.id)
else:
kwargs['queryset'] = Department.objects.all()
elif db_field.name == 'faculty' ... | EventAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits department to user's departments."""
<|body_0|>
def get_queryset(self, request):
"""Returns events that lays in SV scope in case of staff, returns all events otherwise."""
... | stack_v2_sparse_classes_10k_train_002289 | 9,167 | permissive | [
{
"docstring": "limits department to user's departments.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "Returns events that lays in SV scope in case of staff, returns all events otherwise.",
"name": "get... | 3 | stack_v2_sparse_classes_30k_train_003363 | Implement the Python class `EventAdmin` described below.
Class description:
Implement the EventAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits department to user's departments.
- def get_queryset(self, request): Returns events that lays in SV sc... | Implement the Python class `EventAdmin` described below.
Class description:
Implement the EventAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits department to user's departments.
- def get_queryset(self, request): Returns events that lays in SV sc... | 70638c121ea85ff0e6a650c5f2641b0b3b04d6d0 | <|skeleton|>
class EventAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits department to user's departments."""
<|body_0|>
def get_queryset(self, request):
"""Returns events that lays in SV scope in case of staff, returns all events otherwise."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits department to user's departments."""
if db_field.name == 'dep':
if not request.user.is_superuser:
kwargs['queryset'] = Department.objects.filter(id=request.user.profile.department... | the_stack_v2_python_sparse | cms/admin.py | Ibrahem3amer/bala7 | train | 0 | |
7d7e589b11a4ef6a52dcfcb0423815e2f290ec39 | [
"super().__init__(**kwargs)\ndim = len(voxel_size)\nassert len(spatial_size) == 2 * dim, f'{spatial_size}'\nself._voxel_size = voxel_size\nself._spatial_size = spatial_size\nself._voxel_spatial_size = voxel_utils.compute_voxel_spatial_size(spatial_size, self._voxel_size)",
"point_voxel_xyz_float = ops.floor(point... | <|body_start_0|>
super().__init__(**kwargs)
dim = len(voxel_size)
assert len(spatial_size) == 2 * dim, f'{spatial_size}'
self._voxel_size = voxel_size
self._spatial_size = spatial_size
self._voxel_spatial_size = voxel_utils.compute_voxel_spatial_size(spatial_size, self._v... | Voxelization layer. | PointToVoxel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointToVoxel:
"""Voxelization layer."""
def __init__(self, voxel_size, spatial_size, **kwargs):
"""Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additi... | stack_v2_sparse_classes_10k_train_002290 | 9,351 | permissive | [
{
"docstring": "Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additional key value args (e.g. dtype) passed to the parent class.",
"name": "__init__",
"signature": "def __... | 2 | null | Implement the Python class `PointToVoxel` described below.
Class description:
Voxelization layer.
Method signatures and docstrings:
- def __init__(self, voxel_size, spatial_size, **kwargs): Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in g... | Implement the Python class `PointToVoxel` described below.
Class description:
Voxelization layer.
Method signatures and docstrings:
- def __init__(self, voxel_size, spatial_size, **kwargs): Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in g... | e83f229f1b7b847cd712d5cd4810097d3e06d14e | <|skeleton|>
class PointToVoxel:
"""Voxelization layer."""
def __init__(self, voxel_size, spatial_size, **kwargs):
"""Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PointToVoxel:
"""Voxelization layer."""
def __init__(self, voxel_size, spatial_size, **kwargs):
"""Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additional key valu... | the_stack_v2_python_sparse | keras_cv/layers/object_detection_3d/voxelization.py | keras-team/keras-cv | train | 818 |
546293c0e1c5c4cad1fdb179d54019c5dfc89714 | [
"self.filename = filename\nself.state = state\nself.init_args = init_args",
"filename = os.path.join(unpickler._dirname, self.filename)\narray = unpickler.np.core.multiarray._reconstruct(*self.init_args)\nwith open(filename, 'rb') as f:\n data = read_zfile(f)\nstate = self.state + (data,)\narray.__setstate__(s... | <|body_start_0|>
self.filename = filename
self.state = state
self.init_args = init_args
<|end_body_0|>
<|body_start_1|>
filename = os.path.join(unpickler._dirname, self.filename)
array = unpickler.np.core.multiarray._reconstruct(*self.init_args)
with open(filename, 'rb')... | An object to be persisted instead of numpy arrays. This object store the Zfile filename in which the data array has been persisted, and the meta information to retrieve it. The reason that we store the raw buffer data of the array and the meta information, rather than array representation routine (tostring) is that it ... | ZNDArrayWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZNDArrayWrapper:
"""An object to be persisted instead of numpy arrays. This object store the Zfile filename in which the data array has been persisted, and the meta information to retrieve it. The reason that we store the raw buffer data of the array and the meta information, rather than array re... | stack_v2_sparse_classes_10k_train_002291 | 17,419 | permissive | [
{
"docstring": "Store the useful information for later",
"name": "__init__",
"signature": "def __init__(self, filename, init_args, state)"
},
{
"docstring": "Reconstruct the array from the meta-information and the z-file",
"name": "read",
"signature": "def read(self, unpickler)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001763 | Implement the Python class `ZNDArrayWrapper` described below.
Class description:
An object to be persisted instead of numpy arrays. This object store the Zfile filename in which the data array has been persisted, and the meta information to retrieve it. The reason that we store the raw buffer data of the array and the... | Implement the Python class `ZNDArrayWrapper` described below.
Class description:
An object to be persisted instead of numpy arrays. This object store the Zfile filename in which the data array has been persisted, and the meta information to retrieve it. The reason that we store the raw buffer data of the array and the... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class ZNDArrayWrapper:
"""An object to be persisted instead of numpy arrays. This object store the Zfile filename in which the data array has been persisted, and the meta information to retrieve it. The reason that we store the raw buffer data of the array and the meta information, rather than array re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZNDArrayWrapper:
"""An object to be persisted instead of numpy arrays. This object store the Zfile filename in which the data array has been persisted, and the meta information to retrieve it. The reason that we store the raw buffer data of the array and the meta information, rather than array representation ... | the_stack_v2_python_sparse | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | ryfeus/lambda-packs | train | 1,283 |
ac002677d76544540f077ca4c941b5bbc524e074 | [
"l = 0\nr = len(nums) - 1\nmid = self.findMid(l, r, nums, target)\nif mid != -1:\n l = mid\n r = mid\n while l >= 0 and nums[l] == target:\n l -= 1\n while r < len(nums) and nums[r] == target:\n r += 1\n return [l + 1, r - 1]\nreturn [-1, -1]",
"while l <= r:\n mid = (l + r) / 2\n ... | <|body_start_0|>
l = 0
r = len(nums) - 1
mid = self.findMid(l, r, nums, target)
if mid != -1:
l = mid
r = mid
while l >= 0 and nums[l] == target:
l -= 1
while r < len(nums) and nums[r] == target:
r += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def findMid(self, l, r, nums, target):
"""Binary search"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = 0
r = len(n... | stack_v2_sparse_classes_10k_train_002292 | 845 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "searchRange",
"signature": "def searchRange(self, nums, target)"
},
{
"docstring": "Binary search",
"name": "findMid",
"signature": "def findMid(self, l, r, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001383 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def findMid(self, l, r, nums, target): Binary search | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def findMid(self, l, r, nums, target): Binary search
<|skeleton|>
class Solution... | ca8b2662330776d14962532ed8994dfeedadef70 | <|skeleton|>
class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def findMid(self, l, r, nums, target):
"""Binary search"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
l = 0
r = len(nums) - 1
mid = self.findMid(l, r, nums, target)
if mid != -1:
l = mid
r = mid
while l >= 0 and nums[l] == ta... | the_stack_v2_python_sparse | Algo/Leetcode/034FirstAndLastPosInSortedArray.py | lawy623/Algorithm_Interview_Prep | train | 2 | |
81b6f4e1c22093d23e46af50fe947a8d93a89e39 | [
"A = solution1[:point].append(solution2[point:])\nB = solution2[:point].append(solution1[point:])\nreturn (A, B)",
"A = solution1\nB = solution2\nfor p in points:\n A, B = Crossover.single_point_crossover(A, B, p)\nreturn (A, B)",
"A = solution1\nB = solution2\nfor i in range(len(chances)):\n if chances[i... | <|body_start_0|>
A = solution1[:point].append(solution2[point:])
B = solution2[:point].append(solution1[point:])
return (A, B)
<|end_body_0|>
<|body_start_1|>
A = solution1
B = solution2
for p in points:
A, B = Crossover.single_point_crossover(A, B, p)
... | Crossover | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crossover:
def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]:
"""Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n ... | stack_v2_sparse_classes_10k_train_002293 | 19,927 | no_license | [
{
"docstring": "Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n being the solution size. Args: solution1: One solution to be used in crossover with size N. solution2: Another solution to be used in crossover with size N. point: An intege... | 3 | stack_v2_sparse_classes_30k_train_006019 | Implement the Python class `Crossover` described below.
Class description:
Implement the Crossover class.
Method signatures and docstrings:
- def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]: Returns two children solu... | Implement the Python class `Crossover` described below.
Class description:
Implement the Crossover class.
Method signatures and docstrings:
- def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]: Returns two children solu... | f1e705a80f60d28d56f3a1c2e0b700438078496c | <|skeleton|>
class Crossover:
def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]:
"""Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Crossover:
def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]:
"""Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n being the solu... | the_stack_v2_python_sparse | code/python/genetic.py | akahenry/INF05100_Problems | train | 0 | |
b31f4e139658a1ac6b3fbf3ff20beb012c45f11e | [
"super().__init__(config_entry, driver, info)\nself._target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)\nassert self.info.platform_data_template\nself._lookup_map = cast(dict[int, str], self.info.platform_data_template.static_data)\nself._attr_options = list(self._lookup_map.values())",
"if self.info.prim... | <|body_start_0|>
super().__init__(config_entry, driver, info)
self._target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
assert self.info.platform_data_template
self._lookup_map = cast(dict[int, str], self.info.platform_data_template.static_data)
self._attr_options = list(s... | Representation of a Z-Wave Multilevel Switch CC select entity. | ZwaveMultilevelSwitchSelectEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZwaveMultilevelSwitchSelectEntity:
"""Representation of a Z-Wave Multilevel Switch CC select entity."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZwaveSelectEntity entity."""
<|body_0|>
def current_op... | stack_v2_sparse_classes_10k_train_002294 | 7,555 | permissive | [
{
"docstring": "Initialize a ZwaveSelectEntity entity.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None"
},
{
"docstring": "Return the selected entity option to represent the entity state.",
"name": "current_o... | 3 | null | Implement the Python class `ZwaveMultilevelSwitchSelectEntity` described below.
Class description:
Representation of a Z-Wave Multilevel Switch CC select entity.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None: Initialize a ZwaveSelec... | Implement the Python class `ZwaveMultilevelSwitchSelectEntity` described below.
Class description:
Representation of a Z-Wave Multilevel Switch CC select entity.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None: Initialize a ZwaveSelec... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZwaveMultilevelSwitchSelectEntity:
"""Representation of a Z-Wave Multilevel Switch CC select entity."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZwaveSelectEntity entity."""
<|body_0|>
def current_op... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZwaveMultilevelSwitchSelectEntity:
"""Representation of a Z-Wave Multilevel Switch CC select entity."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZwaveSelectEntity entity."""
super().__init__(config_entry, driver, info... | the_stack_v2_python_sparse | homeassistant/components/zwave_js/select.py | home-assistant/core | train | 35,501 |
2002a2cb97c69129b4ac16445eee3d9be3f38a2e | [
"attrs = attrs or []\nself.attrs = list(attrs)\nif ORTH in self.attrs:\n self.attrs.pop(ORTH)\nif SPACY in self.attrs:\n self.attrs.pop(SPACY)\nself.attrs.insert(0, ORTH)\nself.tokens = []\nself.spaces = []\nself.strings = set()",
"array = doc.to_array(self.attrs)\nif len(array.shape) == 1:\n array = arr... | <|body_start_0|>
attrs = attrs or []
self.attrs = list(attrs)
if ORTH in self.attrs:
self.attrs.pop(ORTH)
if SPACY in self.attrs:
self.attrs.pop(SPACY)
self.attrs.insert(0, ORTH)
self.tokens = []
self.spaces = []
self.strings = set(... | Serialize analyses from a collection of doc objects. | Binder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binder:
"""Serialize analyses from a collection of doc objects."""
def __init__(self, attrs=None):
"""Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to ... | stack_v2_sparse_classes_10k_train_002295 | 4,226 | permissive | [
{
"docstring": "Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to None.",
"name": "__init__",
"signature": "def __init__(self, attrs=None)"
},
{
"docstring": "Add a... | 6 | stack_v2_sparse_classes_30k_train_002443 | Implement the Python class `Binder` described below.
Class description:
Serialize analyses from a collection of doc objects.
Method signatures and docstrings:
- def __init__(self, attrs=None): Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are... | Implement the Python class `Binder` described below.
Class description:
Serialize analyses from a collection of doc objects.
Method signatures and docstrings:
- def __init__(self, attrs=None): Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are... | a062c118f12b93172e31e8ca115ce3f871b64461 | <|skeleton|>
class Binder:
"""Serialize analyses from a collection of doc objects."""
def __init__(self, attrs=None):
"""Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Binder:
"""Serialize analyses from a collection of doc objects."""
def __init__(self, attrs=None):
"""Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to None."""
... | the_stack_v2_python_sparse | python/spaCy/2018/12/_serialize.py | rosoareslv/SED99 | train | 1 |
9ebf934704aeea1f8dc1e4c39359380d1e810cce | [
"invitee = get_object_or_404(models.Invitee, pk=pk)\nif not invitee.invitation_sent_date:\n email = emails.InvitationEmail(invitee, request)\n custom_send_mail(subject=email.subject, html_message=email.message, from_email=email.from_email, recipient_list=email.to_list)\n invitee.invitation_sent_date = time... | <|body_start_0|>
invitee = get_object_or_404(models.Invitee, pk=pk)
if not invitee.invitation_sent_date:
email = emails.InvitationEmail(invitee, request)
custom_send_mail(subject=email.subject, html_message=email.message, from_email=email.from_email, recipient_list=email.to_list)... | InviteeSendInvitationAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InviteeSendInvitationAPIView:
def post(self, request, pk):
"""send the email"""
<|body_0|>
def get(self, request, pk):
"""get a preview of the email to be sent"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
invitee = get_object_or_404(models.Invite... | stack_v2_sparse_classes_10k_train_002296 | 7,363 | no_license | [
{
"docstring": "send the email",
"name": "post",
"signature": "def post(self, request, pk)"
},
{
"docstring": "get a preview of the email to be sent",
"name": "get",
"signature": "def get(self, request, pk)"
}
] | 2 | null | Implement the Python class `InviteeSendInvitationAPIView` described below.
Class description:
Implement the InviteeSendInvitationAPIView class.
Method signatures and docstrings:
- def post(self, request, pk): send the email
- def get(self, request, pk): get a preview of the email to be sent | Implement the Python class `InviteeSendInvitationAPIView` described below.
Class description:
Implement the InviteeSendInvitationAPIView class.
Method signatures and docstrings:
- def post(self, request, pk): send the email
- def get(self, request, pk): get a preview of the email to be sent
<|skeleton|>
class Invite... | 483f855b19876fd60c0017a270df74e076aa0d8b | <|skeleton|>
class InviteeSendInvitationAPIView:
def post(self, request, pk):
"""send the email"""
<|body_0|>
def get(self, request, pk):
"""get a preview of the email to be sent"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InviteeSendInvitationAPIView:
def post(self, request, pk):
"""send the email"""
invitee = get_object_or_404(models.Invitee, pk=pk)
if not invitee.invitation_sent_date:
email = emails.InvitationEmail(invitee, request)
custom_send_mail(subject=email.subject, html_... | the_stack_v2_python_sparse | events/api/views.py | yc-hu/dm_apps | train | 0 | |
202b6c8ea2cd12df4a1ed63eb25345dd2057e5bf | [
"if user_index >= self.num_users or following_index >= self.num_users:\n raise ValueError(f'Number of users is {self.num_users}, but indices {user_index} and {following_index} were requested.')\nif self.users_hat[following_index, user_index] == 0:\n self.users_hat[following_index, user_index] = 1\nelif self.i... | <|body_start_0|>
if user_index >= self.num_users or following_index >= self.num_users:
raise ValueError(f'Number of users is {self.num_users}, but indices {user_index} and {following_index} were requested.')
if self.users_hat[following_index, user_index] == 0:
self.users_hat[foll... | A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`. | BinarySocialGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySocialGraph:
"""A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
... | stack_v2_sparse_classes_10k_train_002297 | 5,088 | permissive | [
{
"docstring": "Method to follow another user -- that is, to create a unidirectional link from one user to the other. Parameters ---------- user_index: int Index of the user initiating the follow. following_index: int Index of the user to be followed. Raises ------ ValueError If either of the user indices does ... | 4 | stack_v2_sparse_classes_30k_train_000649 | Implement the Python class `BinarySocialGraph` described below.
Class description:
A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`.
Method signatures and d... | Implement the Python class `BinarySocialGraph` described below.
Class description:
A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`.
Method signatures and d... | c4db28013f397ccad9eb5f5e530ca301599f36fb | <|skeleton|>
class BinarySocialGraph:
"""A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BinarySocialGraph:
"""A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
"""Method to ... | the_stack_v2_python_sparse | trecs/components/socialgraph.py | amywinecoff/t-recs | train | 1 |
eab9e5ff4b18e6bde7916ea978ca4b746327435e | [
"if not email:\n raise ValueError('Users must have an Email address')\nif not first_name:\n raise ValueError('Users must have a First name')\nif not last_name:\n raise ValueError('Users must have a Last name')\nuser = self.model(email=self.normalize_email(email), first_name=first_name, last_name=last_name,... | <|body_start_0|>
if not email:
raise ValueError('Users must have an Email address')
if not first_name:
raise ValueError('Users must have a First name')
if not last_name:
raise ValueError('Users must have a Last name')
user = self.model(email=self.norma... | AccountManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountManager:
def create_user(self, email, first_name, last_name, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, first_name, last_name, password):
"""Creates and saves a superuser with ... | stack_v2_sparse_classes_10k_train_002298 | 4,129 | no_license | [
{
"docstring": "Creates and saves a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, first_name, last_name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email and password.",
"name": "create_superus... | 2 | stack_v2_sparse_classes_30k_train_005907 | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, first_name, last_name, password=None): Creates and saves a User with the given email and password.
- def create_superuser(self, email, fi... | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, first_name, last_name, password=None): Creates and saves a User with the given email and password.
- def create_superuser(self, email, fi... | 72d2856e76998653e73c6aff17833446a019d1d8 | <|skeleton|>
class AccountManager:
def create_user(self, email, first_name, last_name, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, first_name, last_name, password):
"""Creates and saves a superuser with ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountManager:
def create_user(self, email, first_name, last_name, password=None):
"""Creates and saves a User with the given email and password."""
if not email:
raise ValueError('Users must have an Email address')
if not first_name:
raise ValueError('Users mu... | the_stack_v2_python_sparse | accounts/models.py | w3kernel/sokalbikal | train | 0 | |
42914637a58c9b2509dc8d1e541b0a1aee3af026 | [
"self.mhdr = MACHeader(JOIN_ACCEPT, LORAWAN_R1)\nself.appkey = appkey\nself.appnonce = appnonce\nself.netid = netid\nself.devaddr = devaddr\nself.dlsettings = dlsettings\nself.rxdelay = rxdelay\nself.cflist = cflist\nself.mic = None",
"header = self.mhdr.encode()\nmsg = intPackBytes(self.appnonce, 3, endian='litt... | <|body_start_0|>
self.mhdr = MACHeader(JOIN_ACCEPT, LORAWAN_R1)
self.appkey = appkey
self.appnonce = appnonce
self.netid = netid
self.devaddr = devaddr
self.dlsettings = dlsettings
self.rxdelay = rxdelay
self.cflist = cflist
self.mic = None
<|end_b... | A LoRa Join Accept message. The join accept message contains an application nonce of 3 octets (appnonce), 3 octet a network identifier (netid), a 4 octet device address (devaddr), a 1 octet delay between tx and rx (rxdelay) and an optional list of channel frequencies (cflist). Attributes: mhdr (MACHeader): MAC header a... | JoinAcceptMessage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinAcceptMessage:
"""A LoRa Join Accept message. The join accept message contains an application nonce of 3 octets (appnonce), 3 octet a network identifier (netid), a 4 octet device address (devaddr), a 1 octet delay between tx and rx (rxdelay) and an optional list of channel frequencies (cflist... | stack_v2_sparse_classes_10k_train_002299 | 26,915 | permissive | [
{
"docstring": "JoinAcceptMessage initialisation method.",
"name": "__init__",
"signature": "def __init__(self, appkey, appnonce, netid, devaddr, dlsettings, rxdelay, cflist=[])"
},
{
"docstring": "Create a binary representation of JoinAcceptMessage object. Returns: Packed JoinAccept message.",
... | 2 | stack_v2_sparse_classes_30k_train_002784 | Implement the Python class `JoinAcceptMessage` described below.
Class description:
A LoRa Join Accept message. The join accept message contains an application nonce of 3 octets (appnonce), 3 octet a network identifier (netid), a 4 octet device address (devaddr), a 1 octet delay between tx and rx (rxdelay) and an optio... | Implement the Python class `JoinAcceptMessage` described below.
Class description:
A LoRa Join Accept message. The join accept message contains an application nonce of 3 octets (appnonce), 3 octet a network identifier (netid), a 4 octet device address (devaddr), a 1 octet delay between tx and rx (rxdelay) and an optio... | add5a1129296dca6db55b7980c0c1091f1ca80aa | <|skeleton|>
class JoinAcceptMessage:
"""A LoRa Join Accept message. The join accept message contains an application nonce of 3 octets (appnonce), 3 octet a network identifier (netid), a 4 octet device address (devaddr), a 1 octet delay between tx and rx (rxdelay) and an optional list of channel frequencies (cflist... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JoinAcceptMessage:
"""A LoRa Join Accept message. The join accept message contains an application nonce of 3 octets (appnonce), 3 octet a network identifier (netid), a 4 octet device address (devaddr), a 1 octet delay between tx and rx (rxdelay) and an optional list of channel frequencies (cflist). Attributes... | the_stack_v2_python_sparse | floranet/lora/mac.py | chengzhongkai/floranet | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.