blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
1b3eeae246ef6d8d8f3eb8ee193d45d7b3251bcc
[ "self.screen_width = 1200\nself.screen_height = 800\nself.bg_color = (135, 206, 255)\nself.ship_limit = 3\nself.bullet_width = 3\nself.bullet_height = 15\nself.bullet_color = (255, 0, 0)\nself.bullets_allowed = 3\nself.fleet_drop_speed = 5\nself.speedup_scale = 1.1\nself.score_scale = 1.5\nself.initialize_dynamic_s...
<|body_start_0|> self.screen_width = 1200 self.screen_height = 800 self.bg_color = (135, 206, 255) self.ship_limit = 3 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (255, 0, 0) self.bullets_allowed = 3 self.fleet_drop_speed = 5 ...
存储游戏中所有设置的类
Settings
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Settings: """存储游戏中所有设置的类""" def __init__(self): """初始化游戏的静态设置""" <|body_0|> def initialize_dynamic_settings(self): """初始化游戏的动态设置""" <|body_1|> def increase_speed(self): """提高速度设置和外星人分数""" <|body_2|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_75kplus_train_071600
1,072
no_license
[ { "docstring": "初始化游戏的静态设置", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "初始化游戏的动态设置", "name": "initialize_dynamic_settings", "signature": "def initialize_dynamic_settings(self)" }, { "docstring": "提高速度设置和外星人分数", "name": "increase_speed", "sign...
3
stack_v2_sparse_classes_30k_train_011157
Implement the Python class `Settings` described below. Class description: 存储游戏中所有设置的类 Method signatures and docstrings: - def __init__(self): 初始化游戏的静态设置 - def initialize_dynamic_settings(self): 初始化游戏的动态设置 - def increase_speed(self): 提高速度设置和外星人分数
Implement the Python class `Settings` described below. Class description: 存储游戏中所有设置的类 Method signatures and docstrings: - def __init__(self): 初始化游戏的静态设置 - def initialize_dynamic_settings(self): 初始化游戏的动态设置 - def increase_speed(self): 提高速度设置和外星人分数 <|skeleton|> class Settings: """存储游戏中所有设置的类""" def __init__(se...
1f5f05a90c854ed96b5fd839146fa30a6b33ad61
<|skeleton|> class Settings: """存储游戏中所有设置的类""" def __init__(self): """初始化游戏的静态设置""" <|body_0|> def initialize_dynamic_settings(self): """初始化游戏的动态设置""" <|body_1|> def increase_speed(self): """提高速度设置和外星人分数""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Settings: """存储游戏中所有设置的类""" def __init__(self): """初始化游戏的静态设置""" self.screen_width = 1200 self.screen_height = 800 self.bg_color = (135, 206, 255) self.ship_limit = 3 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (255, 0,...
the_stack_v2_python_sparse
course/alien_invasion/settings.py
Gct96/python_practices
train
0
cb108ac7ae2f8877691df663e0b631d7d5d8c7de
[ "self.df = df\nself.tokenizer = tokenizer\nself.lenght = len(df)\nself.a_fold_length = self.lenght // k\nself.fold_k = k\nself.collect_fn = PadCollate(self.tokenizer)\nself.nclass = nclass\nself.max_len = max_len\nself.batch_size = batch_size\nself.label_smoothing = label_smoothing\nself.eda_alpha = eda_alpha\nself...
<|body_start_0|> self.df = df self.tokenizer = tokenizer self.lenght = len(df) self.a_fold_length = self.lenght // k self.fold_k = k self.collect_fn = PadCollate(self.tokenizer) self.nclass = nclass self.max_len = max_len self.batch_size = batch_si...
K Fold Data Loader
KFoldDataLoader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KFoldDataLoader: """K Fold Data Loader""" def __init__(self, df, tokenizer, batch_size=128, k=5, nclass=17, max_len=70, label_smoothing=0, eda_alpha=0, n_aug=0): """args: k - k Folder, default = 5 df - dataFrame, should have three column ['id','report','label']""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_071601
3,276
no_license
[ { "docstring": "args: k - k Folder, default = 5 df - dataFrame, should have three column ['id','report','label']", "name": "__init__", "signature": "def __init__(self, df, tokenizer, batch_size=128, k=5, nclass=17, max_len=70, label_smoothing=0, eda_alpha=0, n_aug=0)" }, { "docstring": "Get ith ...
2
null
Implement the Python class `KFoldDataLoader` described below. Class description: K Fold Data Loader Method signatures and docstrings: - def __init__(self, df, tokenizer, batch_size=128, k=5, nclass=17, max_len=70, label_smoothing=0, eda_alpha=0, n_aug=0): args: k - k Folder, default = 5 df - dataFrame, should have th...
Implement the Python class `KFoldDataLoader` described below. Class description: K Fold Data Loader Method signatures and docstrings: - def __init__(self, df, tokenizer, batch_size=128, k=5, nclass=17, max_len=70, label_smoothing=0, eda_alpha=0, n_aug=0): args: k - k Folder, default = 5 df - dataFrame, should have th...
4fb32c7799f060042841a62f146ccfe731b98def
<|skeleton|> class KFoldDataLoader: """K Fold Data Loader""" def __init__(self, df, tokenizer, batch_size=128, k=5, nclass=17, max_len=70, label_smoothing=0, eda_alpha=0, n_aug=0): """args: k - k Folder, default = 5 df - dataFrame, should have three column ['id','report','label']""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KFoldDataLoader: """K Fold Data Loader""" def __init__(self, df, tokenizer, batch_size=128, k=5, nclass=17, max_len=70, label_smoothing=0, eda_alpha=0, n_aug=0): """args: k - k Folder, default = 5 df - dataFrame, should have three column ['id','report','label']""" self.df = df sel...
the_stack_v2_python_sparse
code/utils/bert_kFoldData.py
XuHangkun/tianchi_channel_1
train
0
dd02b6a9510b09d4445899b0fb378eb90158609d
[ "if not root:\n return True\nif abs(self.getDepth(root.left) - self.getDepth(root.right)) > 1:\n return False\nreturn self.isBalanced(root.left) and self.isBalanced(root.right)", "if not root:\n return 0\nreturn 1 + max(self.getDepth(root.left), self.getDepth(root.right))" ]
<|body_start_0|> if not root: return True if abs(self.getDepth(root.left) - self.getDepth(root.right)) > 1: return False return self.isBalanced(root.left) and self.isBalanced(root.right) <|end_body_0|> <|body_start_1|> if not root: return 0 re...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isBalanced(self, root): """递归比较各个节点的左孩子和右孩子 :type root: TreeNode :rtype: bool""" <|body_0|> def getDepth(self, root): """求出节点深度 :param root: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: return True ...
stack_v2_sparse_classes_75kplus_train_071602
792
no_license
[ { "docstring": "递归比较各个节点的左孩子和右孩子 :type root: TreeNode :rtype: bool", "name": "isBalanced", "signature": "def isBalanced(self, root)" }, { "docstring": "求出节点深度 :param root: :return:", "name": "getDepth", "signature": "def getDepth(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_051653
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isBalanced(self, root): 递归比较各个节点的左孩子和右孩子 :type root: TreeNode :rtype: bool - def getDepth(self, root): 求出节点深度 :param root: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isBalanced(self, root): 递归比较各个节点的左孩子和右孩子 :type root: TreeNode :rtype: bool - def getDepth(self, root): 求出节点深度 :param root: :return: <|skeleton|> class Solution: def isB...
e2699a43e9f7aecc475e21a4b2582c6ee3b41a1c
<|skeleton|> class Solution: def isBalanced(self, root): """递归比较各个节点的左孩子和右孩子 :type root: TreeNode :rtype: bool""" <|body_0|> def getDepth(self, root): """求出节点深度 :param root: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isBalanced(self, root): """递归比较各个节点的左孩子和右孩子 :type root: TreeNode :rtype: bool""" if not root: return True if abs(self.getDepth(root.left) - self.getDepth(root.right)) > 1: return False return self.isBalanced(root.left) and self.isBalanced(r...
the_stack_v2_python_sparse
leetcode/二叉树/平衡二叉树.py
xxNB/sword-offer
train
0
90632c3b9b52636363679c8089bf38ba0b2af845
[ "topic = model.Topic(18, 'New Topic')\nactual = json.loads(json.dumps(topic, cls=codec.TopicEncoder))\nexpected = [18, 'New Topic']\nself.assertEqual(expected, actual)", "ts = datetime.datetime(2018, 1, 1)\ndatum = model.Datum(ts, 18, 'value')\nactual = json.loads(json.dumps(datum, cls=codec.DatumEncoder))\nexpec...
<|body_start_0|> topic = model.Topic(18, 'New Topic') actual = json.loads(json.dumps(topic, cls=codec.TopicEncoder)) expected = [18, 'New Topic'] self.assertEqual(expected, actual) <|end_body_0|> <|body_start_1|> ts = datetime.datetime(2018, 1, 1) datum = model.Datum(ts,...
A test case for codec operations.
CodecTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CodecTestCase: """A test case for codec operations.""" def test_encode_topic(self): """Encodes a Topic object and ensures it has the correct representation.""" <|body_0|> def test_encode_datum(self): """Encodes a Datum object and ensures it has the correct repres...
stack_v2_sparse_classes_75kplus_train_071603
826
permissive
[ { "docstring": "Encodes a Topic object and ensures it has the correct representation.", "name": "test_encode_topic", "signature": "def test_encode_topic(self)" }, { "docstring": "Encodes a Datum object and ensures it has the correct representation.", "name": "test_encode_datum", "signatu...
2
stack_v2_sparse_classes_30k_train_000659
Implement the Python class `CodecTestCase` described below. Class description: A test case for codec operations. Method signatures and docstrings: - def test_encode_topic(self): Encodes a Topic object and ensures it has the correct representation. - def test_encode_datum(self): Encodes a Datum object and ensures it h...
Implement the Python class `CodecTestCase` described below. Class description: A test case for codec operations. Method signatures and docstrings: - def test_encode_topic(self): Encodes a Topic object and ensures it has the correct representation. - def test_encode_datum(self): Encodes a Datum object and ensures it h...
cbdf9294c4851ed6bd3e0a19f86eb7518df45c15
<|skeleton|> class CodecTestCase: """A test case for codec operations.""" def test_encode_topic(self): """Encodes a Topic object and ensures it has the correct representation.""" <|body_0|> def test_encode_datum(self): """Encodes a Datum object and ensures it has the correct repres...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CodecTestCase: """A test case for codec operations.""" def test_encode_topic(self): """Encodes a Topic object and ensures it has the correct representation.""" topic = model.Topic(18, 'New Topic') actual = json.loads(json.dumps(topic, cls=codec.TopicEncoder)) expected = [1...
the_stack_v2_python_sparse
src/server/codec_test.py
jerome9189/lotus-leaf
train
0
48bb32d6a2610239a9482847456bb0f2eb8db28c
[ "if not non_terminal(start_variable):\n raise ValueError('The start variable must not be terminal')\nself._start_variable = start_variable\nself.deriv_rules = {}", "if not non_terminal(left):\n raise ValueError('The left side must be non terminal')\nif left not in self.deriv_rules and type(right) == list:\n...
<|body_start_0|> if not non_terminal(start_variable): raise ValueError('The start variable must not be terminal') self._start_variable = start_variable self.deriv_rules = {} <|end_body_0|> <|body_start_1|> if not non_terminal(left): raise ValueError('The left sid...
Class representing a CF grammar.
Grammar
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Grammar: """Class representing a CF grammar.""" def __init__(self, start_variable): """Initialize a Grammar object. :param start_variable: The start variable, one of the non-terminals.""" <|body_0|> def add_rule(self, left, right): """Add a new derivation rule to...
stack_v2_sparse_classes_75kplus_train_071604
5,080
no_license
[ { "docstring": "Initialize a Grammar object. :param start_variable: The start variable, one of the non-terminals.", "name": "__init__", "signature": "def __init__(self, start_variable)" }, { "docstring": "Add a new derivation rule to the grammar. :param left: the left side of the rule, a non ter...
5
stack_v2_sparse_classes_30k_train_005475
Implement the Python class `Grammar` described below. Class description: Class representing a CF grammar. Method signatures and docstrings: - def __init__(self, start_variable): Initialize a Grammar object. :param start_variable: The start variable, one of the non-terminals. - def add_rule(self, left, right): Add a n...
Implement the Python class `Grammar` described below. Class description: Class representing a CF grammar. Method signatures and docstrings: - def __init__(self, start_variable): Initialize a Grammar object. :param start_variable: The start variable, one of the non-terminals. - def add_rule(self, left, right): Add a n...
310ab38aa6b2fc573e3530816bfbfd02ac1a0936
<|skeleton|> class Grammar: """Class representing a CF grammar.""" def __init__(self, start_variable): """Initialize a Grammar object. :param start_variable: The start variable, one of the non-terminals.""" <|body_0|> def add_rule(self, left, right): """Add a new derivation rule to...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Grammar: """Class representing a CF grammar.""" def __init__(self, start_variable): """Initialize a Grammar object. :param start_variable: The start variable, one of the non-terminals.""" if not non_terminal(start_variable): raise ValueError('The start variable must not be ter...
the_stack_v2_python_sparse
4Sucipto_Lunkyadi.py
galezon/TheoryAlgorithms
train
1
3159d07ca79c6c349e63b201ac32ba3f921e38c3
[ "rqst = Request(cls.session, 'GET', '/resource/watcher')\nrqst.set_json({'agent_id': agent_id})\nasync with rqst.fetch() as resp:\n data = await resp.json()\n if 'message' in data:\n return data['message']\n else:\n return data", "rqst = Request(cls.session, 'POST', '/resource/watcher/agent...
<|body_start_0|> rqst = Request(cls.session, 'GET', '/resource/watcher') rqst.set_json({'agent_id': agent_id}) async with rqst.fetch() as resp: data = await resp.json() if 'message' in data: return data['message'] else: return d...
Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege.
AgentWatcher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AgentWatcher: """Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege.""" async def get_status(cls, agent_id: str) -> dict: """Get a...
stack_v2_sparse_classes_75kplus_train_071605
5,301
permissive
[ { "docstring": "Get agent and watcher status.", "name": "get_status", "signature": "async def get_status(cls, agent_id: str) -> dict" }, { "docstring": "Start agent.", "name": "agent_start", "signature": "async def agent_start(cls, agent_id: str) -> dict" }, { "docstring": "Stop ...
4
stack_v2_sparse_classes_30k_train_016152
Implement the Python class `AgentWatcher` described below. Class description: Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege. Method signatures and docstrings: ...
Implement the Python class `AgentWatcher` described below. Class description: Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege. Method signatures and docstrings: ...
91a80cb5b1ebec52016db7e976571949386e6bda
<|skeleton|> class AgentWatcher: """Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege.""" async def get_status(cls, agent_id: str) -> dict: """Get a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AgentWatcher: """Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege.""" async def get_status(cls, agent_id: str) -> dict: """Get agent and watc...
the_stack_v2_python_sparse
src/ai/backend/client/func/agent.py
dexterastin/backend.ai-client-py
train
0
6d11d78fff02fb7571563af224e71110fffe64cf
[ "super(FuturesSession, self).__init__(*args, **kwargs)\nif executor is None:\n executor = ThreadPoolExecutor(max_workers=max_workers)\n if max_workers > DEFAULT_POOLSIZE:\n adapter_kwargs = dict(pool_connections=max_workers, pool_maxsize=max_workers)\n self.mount('https://', HTTPAdapter(**adapte...
<|body_start_0|> super(FuturesSession, self).__init__(*args, **kwargs) if executor is None: executor = ThreadPoolExecutor(max_workers=max_workers) if max_workers > DEFAULT_POOLSIZE: adapter_kwargs = dict(pool_connections=max_workers, pool_maxsize=max_workers) ...
FuturesSession
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FuturesSession: def __init__(self, executor=None, max_workers=2, *args, **kwargs): """Creates a FuturesSession Notes ~~~~~ * ProcessPoolExecutor is not supported b/c Response objects are not picklable. * If you provide both `executor` and `max_workers`, the latter is ignored and provided...
stack_v2_sparse_classes_75kplus_train_071606
5,711
no_license
[ { "docstring": "Creates a FuturesSession Notes ~~~~~ * ProcessPoolExecutor is not supported b/c Response objects are not picklable. * If you provide both `executor` and `max_workers`, the latter is ignored and provided executor is used as is.", "name": "__init__", "signature": "def __init__(self, execut...
2
stack_v2_sparse_classes_30k_train_018530
Implement the Python class `FuturesSession` described below. Class description: Implement the FuturesSession class. Method signatures and docstrings: - def __init__(self, executor=None, max_workers=2, *args, **kwargs): Creates a FuturesSession Notes ~~~~~ * ProcessPoolExecutor is not supported b/c Response objects ar...
Implement the Python class `FuturesSession` described below. Class description: Implement the FuturesSession class. Method signatures and docstrings: - def __init__(self, executor=None, max_workers=2, *args, **kwargs): Creates a FuturesSession Notes ~~~~~ * ProcessPoolExecutor is not supported b/c Response objects ar...
0ac6653219c2701c13c508c5c4fc9bc3437eea06
<|skeleton|> class FuturesSession: def __init__(self, executor=None, max_workers=2, *args, **kwargs): """Creates a FuturesSession Notes ~~~~~ * ProcessPoolExecutor is not supported b/c Response objects are not picklable. * If you provide both `executor` and `max_workers`, the latter is ignored and provided...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FuturesSession: def __init__(self, executor=None, max_workers=2, *args, **kwargs): """Creates a FuturesSession Notes ~~~~~ * ProcessPoolExecutor is not supported b/c Response objects are not picklable. * If you provide both `executor` and `max_workers`, the latter is ignored and provided executor is u...
the_stack_v2_python_sparse
repoData/ross-requests-futures/allPythonContent.py
aCoffeeYin/pyreco
train
0
36a37cef169de655c057c2c1c402b2aba722e690
[ "create_test_account(self)\nlogin_test_account(self)\npaste = upload_test_paste(self)\nuser = User.objects.get(username='TestUser')\nuser.is_staff = True\nuser.is_superuser = True\nuser.save()\nresponse = self.client.post(reverse('pastes:report_paste', kwargs={'char_id': paste}), {'text': 'This is a report for the ...
<|body_start_0|> create_test_account(self) login_test_account(self) paste = upload_test_paste(self) user = User.objects.get(username='TestUser') user.is_staff = True user.is_superuser = True user.save() response = self.client.post(reverse('pastes:report_pa...
PasteAdminTests
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasteAdminTests: def test_report_ignored_correctly(self): """Submit a paste report and ignore it""" <|body_0|> def test_report_removed_correctly(self): """Submit a paste report and remove the offending paste""" <|body_1|> def test_report_deleted_correctl...
stack_v2_sparse_classes_75kplus_train_071607
17,949
permissive
[ { "docstring": "Submit a paste report and ignore it", "name": "test_report_ignored_correctly", "signature": "def test_report_ignored_correctly(self)" }, { "docstring": "Submit a paste report and remove the offending paste", "name": "test_report_removed_correctly", "signature": "def test_...
4
stack_v2_sparse_classes_30k_train_001461
Implement the Python class `PasteAdminTests` described below. Class description: Implement the PasteAdminTests class. Method signatures and docstrings: - def test_report_ignored_correctly(self): Submit a paste report and ignore it - def test_report_removed_correctly(self): Submit a paste report and remove the offendi...
Implement the Python class `PasteAdminTests` described below. Class description: Implement the PasteAdminTests class. Method signatures and docstrings: - def test_report_ignored_correctly(self): Submit a paste report and ignore it - def test_report_removed_correctly(self): Submit a paste report and remove the offendi...
5e38637e5a417ab907a353af8544f64a0ad2b127
<|skeleton|> class PasteAdminTests: def test_report_ignored_correctly(self): """Submit a paste report and ignore it""" <|body_0|> def test_report_removed_correctly(self): """Submit a paste report and remove the offending paste""" <|body_1|> def test_report_deleted_correctl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PasteAdminTests: def test_report_ignored_correctly(self): """Submit a paste report and ignore it""" create_test_account(self) login_test_account(self) paste = upload_test_paste(self) user = User.objects.get(username='TestUser') user.is_staff = True user....
the_stack_v2_python_sparse
pastes/tests.py
xeddmc/pastebin-django
train
0
85085b822c9b11af9aabeef824a0293cf484a0a6
[ "self.time_frame = time_frame\nself.max_requests = max_requests\nself.verbose = verbose\nself._requests = deque([])\nself._client, self._db = (None, None)\nself._mongo_coll, self._output_file = (None, None)\nself._connection_type = None", "try:\n self._client = MongoClient('mongodb://localhost:%i/' % port)\n ...
<|body_start_0|> self.time_frame = time_frame self.max_requests = max_requests self.verbose = verbose self._requests = deque([]) self._client, self._db = (None, None) self._mongo_coll, self._output_file = (None, None) self._connection_type = None <|end_body_0|> <...
RequestScheduler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestScheduler: def __init__(self, time_frame, max_requests, verbose=False): """Abstract scheduler object. It enables only 'max_requests' requests in every 'time_frame' seconds.""" <|body_0|> def connect_to_mongodb(self, collection_name, port=27017, db_name='twitter-crawle...
stack_v2_sparse_classes_75kplus_train_071608
3,151
no_license
[ { "docstring": "Abstract scheduler object. It enables only 'max_requests' requests in every 'time_frame' seconds.", "name": "__init__", "signature": "def __init__(self, time_frame, max_requests, verbose=False)" }, { "docstring": "Connect to MongoDB collection", "name": "connect_to_mongodb", ...
6
stack_v2_sparse_classes_30k_train_048906
Implement the Python class `RequestScheduler` described below. Class description: Implement the RequestScheduler class. Method signatures and docstrings: - def __init__(self, time_frame, max_requests, verbose=False): Abstract scheduler object. It enables only 'max_requests' requests in every 'time_frame' seconds. - d...
Implement the Python class `RequestScheduler` described below. Class description: Implement the RequestScheduler class. Method signatures and docstrings: - def __init__(self, time_frame, max_requests, verbose=False): Abstract scheduler object. It enables only 'max_requests' requests in every 'time_frame' seconds. - d...
feb8cd0099c25b7fb36cb75498d1e205616f345d
<|skeleton|> class RequestScheduler: def __init__(self, time_frame, max_requests, verbose=False): """Abstract scheduler object. It enables only 'max_requests' requests in every 'time_frame' seconds.""" <|body_0|> def connect_to_mongodb(self, collection_name, port=27017, db_name='twitter-crawle...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RequestScheduler: def __init__(self, time_frame, max_requests, verbose=False): """Abstract scheduler object. It enables only 'max_requests' requests in every 'time_frame' seconds.""" self.time_frame = time_frame self.max_requests = max_requests self.verbose = verbose se...
the_stack_v2_python_sparse
python/request_scheduler.py
MolnarAnna22/twitter-crawler
train
0
0618702a8cf656c2469e54df5f42e60ee222b728
[ "sn = len(s)\ntn = len(t)\nlists = []\nlistt = []\nif sn != tn:\n return False\nfor i in range(0, sn):\n lists.append(s[i])\nfor j in range(0, tn):\n listt.append(t[j])\nlistt.sort()\nlists.sort()\nif lists == listt:\n return True\nelse:\n return False", "\"\"\"\n 思路:定义一个26长度的列表,每个元素都是0,在s中进...
<|body_start_0|> sn = len(s) tn = len(t) lists = [] listt = [] if sn != tn: return False for i in range(0, sn): lists.append(s[i]) for j in range(0, tn): listt.append(t[j]) listt.sort() lists.sort() if li...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isAnagram(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def isAnagram2(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> sn = len(s) tn = len(t) ...
stack_v2_sparse_classes_75kplus_train_071609
1,833
no_license
[ { "docstring": ":type s: str :type t: str :rtype: bool", "name": "isAnagram", "signature": "def isAnagram(self, s, t)" }, { "docstring": ":type s: str :type t: str :rtype: bool", "name": "isAnagram2", "signature": "def isAnagram2(self, s, t)" } ]
2
stack_v2_sparse_classes_30k_train_039066
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool - def isAnagram2(self, s, t): :type s: str :type t: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool - def isAnagram2(self, s, t): :type s: str :type t: str :rtype: bool <|skeleton|> class Solution: def isAn...
c2250f2c7365976a6767e3c12760474f7a6618eb
<|skeleton|> class Solution: def isAnagram(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def isAnagram2(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isAnagram(self, s, t): """:type s: str :type t: str :rtype: bool""" sn = len(s) tn = len(t) lists = [] listt = [] if sn != tn: return False for i in range(0, sn): lists.append(s[i]) for j in range(0, tn): ...
the_stack_v2_python_sparse
242. Valid Anagram/242. Valid Anagram.py
yaolinxia/leetcode_study
train
0
dcb3401a9110b7c3383f2bb9d596bd8f0e54e97d
[ "outputs = sorted(StreamAlertOutput.get_all_outputs().keys())\nlist_parser = generate_subparser(subparser, 'list', description=cls.description, help=cls.description, subcommand=True)\nlist_parser.add_argument('--service', '-s', choices=outputs, default=outputs, nargs='*', metavar='SERVICE', help='Pass Services to l...
<|body_start_0|> outputs = sorted(StreamAlertOutput.get_all_outputs().keys()) list_parser = generate_subparser(subparser, 'list', description=cls.description, help=cls.description, subcommand=True) list_parser.add_argument('--service', '-s', choices=outputs, default=outputs, nargs='*', metavar='...
OutputListSubCommand
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OutputListSubCommand: def setup_subparser(cls, subparser): """Add the output list subparser: manage.py output list [options]""" <|body_0|> def handler(cls, options, config): """List configured outputs Args: options (argparse.Namespace): Basically a namedtuple with th...
stack_v2_sparse_classes_75kplus_train_071610
19,044
permissive
[ { "docstring": "Add the output list subparser: manage.py output list [options]", "name": "setup_subparser", "signature": "def setup_subparser(cls, subparser)" }, { "docstring": "List configured outputs Args: options (argparse.Namespace): Basically a namedtuple with the service setting config (St...
2
stack_v2_sparse_classes_30k_train_018884
Implement the Python class `OutputListSubCommand` described below. Class description: Implement the OutputListSubCommand class. Method signatures and docstrings: - def setup_subparser(cls, subparser): Add the output list subparser: manage.py output list [options] - def handler(cls, options, config): List configured o...
Implement the Python class `OutputListSubCommand` described below. Class description: Implement the OutputListSubCommand class. Method signatures and docstrings: - def setup_subparser(cls, subparser): Add the output list subparser: manage.py output list [options] - def handler(cls, options, config): List configured o...
75ba140d2e1aa6e903313d88326920adcb8bff45
<|skeleton|> class OutputListSubCommand: def setup_subparser(cls, subparser): """Add the output list subparser: manage.py output list [options]""" <|body_0|> def handler(cls, options, config): """List configured outputs Args: options (argparse.Namespace): Basically a namedtuple with th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OutputListSubCommand: def setup_subparser(cls, subparser): """Add the output list subparser: manage.py output list [options]""" outputs = sorted(StreamAlertOutput.get_all_outputs().keys()) list_parser = generate_subparser(subparser, 'list', description=cls.description, help=cls.descrip...
the_stack_v2_python_sparse
streamalert_cli/outputs/handler.py
avmi/streamalert
train
0
d4fb7af2f12bafbd6483e031b62ade7ccf333eca
[ "stack, result = ([], [])\nnode = root\nwhile stack or node:\n if node:\n stack.append(node)\n result.append(str(node.val))\n node = node.left\n else:\n node = stack.pop().right\nreturn ','.join(result)", "def helper(ser, bound=float('inf')):\n if not ser:\n return None...
<|body_start_0|> stack, result = ([], []) node = root while stack or node: if node: stack.append(node) result.append(str(node.val)) node = node.left else: node = stack.pop().right return ','.join(resu...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> stack, result ...
stack_v2_sparse_classes_75kplus_train_071611
1,871
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
stack_v2_sparse_classes_30k_train_038663
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Co...
085d868ba0458fc8e6b5549aa00fa151c335fa7f
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" stack, result = ([], []) node = root while stack or node: if node: stack.append(node) result.append(str(node.val)) node = node...
the_stack_v2_python_sparse
449-Serialize_and_Deserialize_BST.py
chanyoonzhu/leetcode-python
train
0
d4de752b567143c95d6d3d044a473a0e108b0c25
[ "self.trainable_invertible_ica = trainable_invertible_ica\nself.augmenter = ICATransferAugmenter(self.trainable_invertible_ica.get_invertible_ica_model(), novelty_detector=novelty_detector, max_iter=aug_max_iter)\nself.predictor_model = predictor_model\nself.augmentation_size = augmentation_size", "for evaluator ...
<|body_start_0|> self.trainable_invertible_ica = trainable_invertible_ica self.augmenter = ICATransferAugmenter(self.trainable_invertible_ica.get_invertible_ica_model(), novelty_detector=novelty_detector, max_iter=aug_max_iter) self.predictor_model = predictor_model self.augmentation_siz...
Implementation of Causal Mechanism Transfer. Takes a trainable nonlinear ICA method object and perform transfer learning.
CausalMechanismTransfer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CausalMechanismTransfer: """Implementation of Causal Mechanism Transfer. Takes a trainable nonlinear ICA method object and perform transfer learning.""" def __init__(self, trainable_invertible_ica, predictor_model, novelty_detector=OneClassSVM(nu=0.1, gamma='auto'), aug_max_iter: Optional[in...
stack_v2_sparse_classes_75kplus_train_071612
3,102
permissive
[ { "docstring": "Build CausalMechanismTransfer object. Parameters ---------- trainable_invertible_ica : object Trainable invertible ICA model for estimating the mechanism function. Required to implement ``train()`` and ``inv()``. predictor_model : object Trainable predictor model to be trained on the augmented d...
2
null
Implement the Python class `CausalMechanismTransfer` described below. Class description: Implementation of Causal Mechanism Transfer. Takes a trainable nonlinear ICA method object and perform transfer learning. Method signatures and docstrings: - def __init__(self, trainable_invertible_ica, predictor_model, novelty_d...
Implement the Python class `CausalMechanismTransfer` described below. Class description: Implementation of Causal Mechanism Transfer. Takes a trainable nonlinear ICA method object and perform transfer learning. Method signatures and docstrings: - def __init__(self, trainable_invertible_ica, predictor_model, novelty_d...
2878ced51cfe473aad8fbc1886e2b65dfc9fc060
<|skeleton|> class CausalMechanismTransfer: """Implementation of Causal Mechanism Transfer. Takes a trainable nonlinear ICA method object and perform transfer learning.""" def __init__(self, trainable_invertible_ica, predictor_model, novelty_detector=OneClassSVM(nu=0.1, gamma='auto'), aug_max_iter: Optional[in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CausalMechanismTransfer: """Implementation of Causal Mechanism Transfer. Takes a trainable nonlinear ICA method object and perform transfer learning.""" def __init__(self, trainable_invertible_ica, predictor_model, novelty_detector=OneClassSVM(nu=0.1, gamma='auto'), aug_max_iter: Optional[int]=None, augm...
the_stack_v2_python_sparse
causal_da/algorithm/api.py
SoldierY/few-shot-domain-adaptation-by-causal-mechanism-transfer
train
0
d1ac6c2a5969e92c683b86b29779337e14a7b82e
[ "if self.state_model.op_state in [DevState.ON, DevState.OFF, DevState.DISABLE]:\n tango.Except.throw_exception(f'Reset() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Reset command on CspSubarrayLeafNode.', 'cspsubarrayleafnode.Reset()', tango.ErrSeverity.ERR)\nreturn True", "...
<|body_start_0|> if self.state_model.op_state in [DevState.ON, DevState.OFF, DevState.DISABLE]: tango.Except.throw_exception(f'Reset() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Reset command on CspSubarrayLeafNode.', 'cspsubarrayleafnode.Reset()', tango.ErrSever...
A class for CSPSubarrayLeafNode's Reset() command. Command to reset the current operation being done on the CSP Subarray Leaf Node.
ResetCommand
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResetCommand: """A class for CSPSubarrayLeafNode's Reset() command. Command to reset the current operation being done on the CSP Subarray Leaf Node.""" def check_allowed(self): """Checks whether this command is allowed to be run in current device state :return: True if this command i...
stack_v2_sparse_classes_75kplus_train_071613
2,419
permissive
[ { "docstring": "Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean :raises: DevFailed if this command is not allowed to be run in current device state", "name": "check_allowed", "signature": ...
2
stack_v2_sparse_classes_30k_train_051248
Implement the Python class `ResetCommand` described below. Class description: A class for CSPSubarrayLeafNode's Reset() command. Command to reset the current operation being done on the CSP Subarray Leaf Node. Method signatures and docstrings: - def check_allowed(self): Checks whether this command is allowed to be ru...
Implement the Python class `ResetCommand` described below. Class description: A class for CSPSubarrayLeafNode's Reset() command. Command to reset the current operation being done on the CSP Subarray Leaf Node. Method signatures and docstrings: - def check_allowed(self): Checks whether this command is allowed to be ru...
7ee65a9c8dada9b28893144b372a398bd0646195
<|skeleton|> class ResetCommand: """A class for CSPSubarrayLeafNode's Reset() command. Command to reset the current operation being done on the CSP Subarray Leaf Node.""" def check_allowed(self): """Checks whether this command is allowed to be run in current device state :return: True if this command i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResetCommand: """A class for CSPSubarrayLeafNode's Reset() command. Command to reset the current operation being done on the CSP Subarray Leaf Node.""" def check_allowed(self): """Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to ...
the_stack_v2_python_sparse
temp_src/ska_tmc_cspsubarrayleafnode_mid/reset_command.py
ska-telescope/tmc-prototype
train
4
c4c1a7de2ede4f57a6b9369f9275cc188d894722
[ "Frame.__init__(self, master, bg='white')\nself.master.rowconfigure(0, weight=1)\nself.master.columnconfigure(0, weight=1)\nself.master.title('Project 8 - Framer.py')\nself.grid(sticky=N + S + E + W)\nfor r in range(2):\n self.rowconfigure(r, weight=1)\nfor c in range(5):\n self.columnconfigure(c, weight=1)\n...
<|body_start_0|> Frame.__init__(self, master, bg='white') self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) self.master.title('Project 8 - Framer.py') self.grid(sticky=N + S + E + W) for r in range(2): self.rowconfigure(r, weight=1...
Creates the main application window.
Application
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Application: """Creates the main application window.""" def __init__(self, master=None): """Initialize the parent frame.""" <|body_0|> def createWidgets(self): """Place widgets in application window.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_071614
3,069
no_license
[ { "docstring": "Initialize the parent frame.", "name": "__init__", "signature": "def __init__(self, master=None)" }, { "docstring": "Place widgets in application window.", "name": "createWidgets", "signature": "def createWidgets(self)" } ]
2
stack_v2_sparse_classes_30k_train_017875
Implement the Python class `Application` described below. Class description: Creates the main application window. Method signatures and docstrings: - def __init__(self, master=None): Initialize the parent frame. - def createWidgets(self): Place widgets in application window.
Implement the Python class `Application` described below. Class description: Creates the main application window. Method signatures and docstrings: - def __init__(self, master=None): Initialize the parent frame. - def createWidgets(self): Place widgets in application window. <|skeleton|> class Application: """Cr...
06c45545ed064d0e9c4fd15cc81cf454cb079c9d
<|skeleton|> class Application: """Creates the main application window.""" def __init__(self, master=None): """Initialize the parent frame.""" <|body_0|> def createWidgets(self): """Place widgets in application window.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Application: """Creates the main application window.""" def __init__(self, master=None): """Initialize the parent frame.""" Frame.__init__(self, master, bg='white') self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) self.master.title('Pr...
the_stack_v2_python_sparse
Lesson 8 - GUI Layout/project/attempt_1/framer.py
jmwoloso/Python_2
train
0
06dc9ab83153f9ba95c38f89d83e8cd0338ab204
[ "with allure.step(f'输入用户名{username}'):\n self.find(By.ID, 'username').send_keys(username)\nwith allure.step(f'输入账户{account}'):\n self.find(By.ID, 'memberAdd_acctid').send_keys(account)\nwith allure.step(f'输入手机号码{phonenum}'):\n self.find(By.ID, 'memberAdd_phone').send_keys(phonenum)\nwith allure.step('点击保存按...
<|body_start_0|> with allure.step(f'输入用户名{username}'): self.find(By.ID, 'username').send_keys(username) with allure.step(f'输入账户{account}'): self.find(By.ID, 'memberAdd_acctid').send_keys(account) with allure.step(f'输入手机号码{phonenum}'): self.find(By.ID, 'memberA...
AddMemberPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddMemberPage: def add_member(self, username, account, phonenum): """添加联系人 :param username: 姓名 :param account: 账号 :param phonenum: 手机 :return:""" <|body_0|> def get_members(self): """获取所有已添加联系人姓名 :return: 联系人姓名列表""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_75kplus_train_071615
1,741
no_license
[ { "docstring": "添加联系人 :param username: 姓名 :param account: 账号 :param phonenum: 手机 :return:", "name": "add_member", "signature": "def add_member(self, username, account, phonenum)" }, { "docstring": "获取所有已添加联系人姓名 :return: 联系人姓名列表", "name": "get_members", "signature": "def get_members(self)...
2
stack_v2_sparse_classes_30k_train_028818
Implement the Python class `AddMemberPage` described below. Class description: Implement the AddMemberPage class. Method signatures and docstrings: - def add_member(self, username, account, phonenum): 添加联系人 :param username: 姓名 :param account: 账号 :param phonenum: 手机 :return: - def get_members(self): 获取所有已添加联系人姓名 :retu...
Implement the Python class `AddMemberPage` described below. Class description: Implement the AddMemberPage class. Method signatures and docstrings: - def add_member(self, username, account, phonenum): 添加联系人 :param username: 姓名 :param account: 账号 :param phonenum: 手机 :return: - def get_members(self): 获取所有已添加联系人姓名 :retu...
a36880bf669d2ab30eb601f6402dbc876a8cb7a2
<|skeleton|> class AddMemberPage: def add_member(self, username, account, phonenum): """添加联系人 :param username: 姓名 :param account: 账号 :param phonenum: 手机 :return:""" <|body_0|> def get_members(self): """获取所有已添加联系人姓名 :return: 联系人姓名列表""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AddMemberPage: def add_member(self, username, account, phonenum): """添加联系人 :param username: 姓名 :param account: 账号 :param phonenum: 手机 :return:""" with allure.step(f'输入用户名{username}'): self.find(By.ID, 'username').send_keys(username) with allure.step(f'输入账户{account}'): ...
the_stack_v2_python_sparse
taskwork/stage05_live_web/pages/add_member_page.py
fatfatfatFatTiger/HogwartsLG6
train
0
bc43a77d0cc48568eebadf161c3ce5055f5fa56f
[ "super().__init__(client_id, **kwargs)\nself.private_key = private_key\nself.subject = subject\nself.issuer = issuer\nself.audience = audience", "import jwt\nkey = private_key or self.private_key\nif not key:\n raise ValueError('An encryption key must be supplied to make JWT token requests.')\nclaim = {'iss': ...
<|body_start_0|> super().__init__(client_id, **kwargs) self.private_key = private_key self.subject = subject self.issuer = issuer self.audience = audience <|end_body_0|> <|body_start_1|> import jwt key = private_key or self.private_key if not key: ...
A public client utilizing the JWT bearer grant. JWT bearer tokes can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or keyed message digest calculated over) the JWT, without a direct user approval step at the a...
ServiceApplicationClient
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceApplicationClient: """A public client utilizing the JWT bearer grant. JWT bearer tokes can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or keyed message digest calculated over) t...
stack_v2_sparse_classes_75kplus_train_071616
7,812
permissive
[ { "docstring": "Initialize a JWT client with defaults for implicit use later. :param client_id: Client identifier given by the OAuth provider upon registration. :param private_key: Private key used for signing and encrypting. Must be given as a string. :param subject: The principal that is the subject of the JW...
2
null
Implement the Python class `ServiceApplicationClient` described below. Class description: A public client utilizing the JWT bearer grant. JWT bearer tokes can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or ...
Implement the Python class `ServiceApplicationClient` described below. Class description: A public client utilizing the JWT bearer grant. JWT bearer tokes can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or ...
00f9a212004a80df790ed071a59af53a05f5e3f2
<|skeleton|> class ServiceApplicationClient: """A public client utilizing the JWT bearer grant. JWT bearer tokes can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or keyed message digest calculated over) t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServiceApplicationClient: """A public client utilizing the JWT bearer grant. JWT bearer tokes can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or keyed message digest calculated over) the JWT, witho...
the_stack_v2_python_sparse
oauthlib/oauth2/rfc6749/clients/service_application.py
oauthlib/oauthlib
train
1,223
957e428c81d844eaeee92fb03a89f6de9cedb585
[ "exclude = {'program'}\nif self.constraints is not None:\n exclude.add('constraints')\nopt_spec = OptimizationSpecification(program=self.program, keywords=self.dict(exclude=exclude))\nreturn opt_spec", "if optimization_specification.keywords is None:\n return GeometricProcedure()\nelse:\n data = optimiza...
<|body_start_0|> exclude = {'program'} if self.constraints is not None: exclude.add('constraints') opt_spec = OptimizationSpecification(program=self.program, keywords=self.dict(exclude=exclude)) return opt_spec <|end_body_0|> <|body_start_1|> if optimization_specific...
This is a settings class controlling the various runtime options that can be used when running geometric. Note: The coordinate systems supported by geometric are: - `cart` Cartesian - `prim` Primitive a.k.a redundant - `dlc` Delocalised Internal Coordinates - `hdlc` Hybrid Delocalised Internal Coordinates - `tric` Tran...
GeometricProcedure
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeometricProcedure: """This is a settings class controlling the various runtime options that can be used when running geometric. Note: The coordinate systems supported by geometric are: - `cart` Cartesian - `prim` Primitive a.k.a redundant - `dlc` Delocalised Internal Coordinates - `hdlc` Hybrid ...
stack_v2_sparse_classes_75kplus_train_071617
5,785
permissive
[ { "docstring": "Create the optimization specification to be used in qcarchive. Returns: A dictionary representation of the optimization specification.", "name": "get_optimzation_spec", "signature": "def get_optimzation_spec(self) -> OptimizationSpecification" }, { "docstring": "Create a geometri...
2
stack_v2_sparse_classes_30k_train_020489
Implement the Python class `GeometricProcedure` described below. Class description: This is a settings class controlling the various runtime options that can be used when running geometric. Note: The coordinate systems supported by geometric are: - `cart` Cartesian - `prim` Primitive a.k.a redundant - `dlc` Delocalise...
Implement the Python class `GeometricProcedure` described below. Class description: This is a settings class controlling the various runtime options that can be used when running geometric. Note: The coordinate systems supported by geometric are: - `cart` Cartesian - `prim` Primitive a.k.a redundant - `dlc` Delocalise...
48943d8e7a5b6947001d29a9c629a65c4133dbd6
<|skeleton|> class GeometricProcedure: """This is a settings class controlling the various runtime options that can be used when running geometric. Note: The coordinate systems supported by geometric are: - `cart` Cartesian - `prim` Primitive a.k.a redundant - `dlc` Delocalised Internal Coordinates - `hdlc` Hybrid ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GeometricProcedure: """This is a settings class controlling the various runtime options that can be used when running geometric. Note: The coordinate systems supported by geometric are: - `cart` Cartesian - `prim` Primitive a.k.a redundant - `dlc` Delocalised Internal Coordinates - `hdlc` Hybrid Delocalised I...
the_stack_v2_python_sparse
openff/qcsubmit/procedures.py
openforcefield/openff-qcsubmit
train
15
01fcd3c46c175e63960dada22aafc7ae4fa1445d
[ "if not nums:\n return\ncount_dict = defaultdict(int)\nfor num in nums:\n if num in count_dict:\n count_dict[num] += 1\n else:\n count_dict[num] = 1\nnums[:] = [0] * count_dict[0] + [1] * count_dict[1] + [2] * count_dict[2]", "p0, curr, p2 = (0, 0, len(nums) - 1)\nwhile curr <= p2:\n if ...
<|body_start_0|> if not nums: return count_dict = defaultdict(int) for num in nums: if num in count_dict: count_dict[num] += 1 else: count_dict[num] = 1 nums[:] = [0] * count_dict[0] + [1] * count_dict[1] + [2] * count_d...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sortColors(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def sortColors2(self, nums: List[int]) -> None: """荷兰三色旗问题解""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not nums: ...
stack_v2_sparse_classes_75kplus_train_071618
2,824
no_license
[ { "docstring": "Do not return anything, modify nums in-place instead.", "name": "sortColors", "signature": "def sortColors(self, nums: List[int]) -> None" }, { "docstring": "荷兰三色旗问题解", "name": "sortColors2", "signature": "def sortColors2(self, nums: List[int]) -> None" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def sortColors2(self, nums: List[int]) -> None: 荷兰三色旗问题解
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def sortColors2(self, nums: List[int]) -> None: 荷兰三色旗问题解 <|skeleton|> clas...
af5dc310534f12a6ded10226ce05aba65ec119d9
<|skeleton|> class Solution: def sortColors(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def sortColors2(self, nums: List[int]) -> None: """荷兰三色旗问题解""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def sortColors(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" if not nums: return count_dict = defaultdict(int) for num in nums: if num in count_dict: count_dict[num] += 1 ...
the_stack_v2_python_sparse
TwoPointer/SortColors.py
tcandzq/LeetCode
train
23
fd11976e89ca00ee97c567afceacb0e1beeb501a
[ "ret = 0\nfor i in range(len(data) - 1, -1, -1):\n ret <<= 8\n ret += data[i]\nreturn ret", "ret = [0] * 16\nfor i, _ in enumerate(ret):\n ret[i] = num & 255\n num >>= 8\nreturn bytearray(ret)", "if len(key) != 32:\n raise ValueError('Key must be 256 bit long')\nself.acc = 0\nself.r = self.le_byt...
<|body_start_0|> ret = 0 for i in range(len(data) - 1, -1, -1): ret <<= 8 ret += data[i] return ret <|end_body_0|> <|body_start_1|> ret = [0] * 16 for i, _ in enumerate(ret): ret[i] = num & 255 num >>= 8 return bytearray(re...
Poly1305 authenticator
Poly1305
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Poly1305: """Poly1305 authenticator""" def le_bytes_to_num(data): """Convert a number from little endian byte format""" <|body_0|> def num_to_16_le_bytes(num): """Convert number to 16 bytes in little endian format""" <|body_1|> def __init__(self, key...
stack_v2_sparse_classes_75kplus_train_071619
1,504
permissive
[ { "docstring": "Convert a number from little endian byte format", "name": "le_bytes_to_num", "signature": "def le_bytes_to_num(data)" }, { "docstring": "Convert number to 16 bytes in little endian format", "name": "num_to_16_le_bytes", "signature": "def num_to_16_le_bytes(num)" }, { ...
4
stack_v2_sparse_classes_30k_train_004039
Implement the Python class `Poly1305` described below. Class description: Poly1305 authenticator Method signatures and docstrings: - def le_bytes_to_num(data): Convert a number from little endian byte format - def num_to_16_le_bytes(num): Convert number to 16 bytes in little endian format - def __init__(self, key): S...
Implement the Python class `Poly1305` described below. Class description: Poly1305 authenticator Method signatures and docstrings: - def le_bytes_to_num(data): Convert a number from little endian byte format - def num_to_16_le_bytes(num): Convert number to 16 bytes in little endian format - def __init__(self, key): S...
b26ebb6a74c2670ae28052079f2fac95d88e832a
<|skeleton|> class Poly1305: """Poly1305 authenticator""" def le_bytes_to_num(data): """Convert a number from little endian byte format""" <|body_0|> def num_to_16_le_bytes(num): """Convert number to 16 bytes in little endian format""" <|body_1|> def __init__(self, key...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Poly1305: """Poly1305 authenticator""" def le_bytes_to_num(data): """Convert a number from little endian byte format""" ret = 0 for i in range(len(data) - 1, -1, -1): ret <<= 8 ret += data[i] return ret def num_to_16_le_bytes(num): """C...
the_stack_v2_python_sparse
scalyr_agent/third_party_tls/tlslite/utils/poly1305.py
Kami/scalyr-agent-2
train
0
7af5707aa90e29bf6247a5a57e2d8720530e7abc
[ "gamer = Gamer.objects.get(user=request.auth.user)\ngametype = GameType.objects.get(pk=request.data['gameTypeId'])\ngame = Game()\ngame.title = request.data['title']\ngame.maker = request.data['maker']\ngame.number_of_players = request.data['numberOfPlayers']\ngame.skill_level = request.data['skillLevel']\ngame.gam...
<|body_start_0|> gamer = Gamer.objects.get(user=request.auth.user) gametype = GameType.objects.get(pk=request.data['gameTypeId']) game = Game() game.title = request.data['title'] game.maker = request.data['maker'] game.number_of_players = request.data['numberOfPlayers'] ...
Levelup game type viewset.
GameViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameViewSet: """Levelup game type viewset.""" def create(self, request): """Handle POST requests. Returns: Response -- serialized JSON game instance.""" <|body_0|> def retrieve(self, request, pk=None): """Handle GET requests for single game. Returns: Response : J...
stack_v2_sparse_classes_75kplus_train_071620
5,294
no_license
[ { "docstring": "Handle POST requests. Returns: Response -- serialized JSON game instance.", "name": "create", "signature": "def create(self, request)" }, { "docstring": "Handle GET requests for single game. Returns: Response : JSON serialized game.", "name": "retrieve", "signature": "def...
5
stack_v2_sparse_classes_30k_train_051788
Implement the Python class `GameViewSet` described below. Class description: Levelup game type viewset. Method signatures and docstrings: - def create(self, request): Handle POST requests. Returns: Response -- serialized JSON game instance. - def retrieve(self, request, pk=None): Handle GET requests for single game. ...
Implement the Python class `GameViewSet` described below. Class description: Levelup game type viewset. Method signatures and docstrings: - def create(self, request): Handle POST requests. Returns: Response -- serialized JSON game instance. - def retrieve(self, request, pk=None): Handle GET requests for single game. ...
16dd4eb3b24f580a5e3bd98199cb8ff034335d68
<|skeleton|> class GameViewSet: """Levelup game type viewset.""" def create(self, request): """Handle POST requests. Returns: Response -- serialized JSON game instance.""" <|body_0|> def retrieve(self, request, pk=None): """Handle GET requests for single game. Returns: Response : J...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GameViewSet: """Levelup game type viewset.""" def create(self, request): """Handle POST requests. Returns: Response -- serialized JSON game instance.""" gamer = Gamer.objects.get(user=request.auth.user) gametype = GameType.objects.get(pk=request.data['gameTypeId']) game = ...
the_stack_v2_python_sparse
levelupapi/views/gameviewset.py
CheoR/levelup
train
0
302486e74ceafbb2d150000fe34e65a3f95e3e78
[ "obj = Project(name='test')\nobj.save()\nself.assertEquals('test', obj.name)\nself.assertNotEquals(obj.id, None)\nobj.delete()", "project = Project(name='test')\nproject.save()\nstatus = TaskStatus(name='test')\nstatus.save()\nobj = Task(name='test', project=project, status=status, priority=3)\nobj.save()\nself.a...
<|body_start_0|> obj = Project(name='test') obj.save() self.assertEquals('test', obj.name) self.assertNotEquals(obj.id, None) obj.delete() <|end_body_0|> <|body_start_1|> project = Project(name='test') project.save() status = TaskStatus(name='test') ...
Documents models tests
ProjectsModelsTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectsModelsTest: """Documents models tests""" def test_model_project(self): """Test project""" <|body_0|> def test_model_task(self): """Test task""" <|body_1|> def test_model_task_status(self): """Test task status""" <|body_2|> <|...
stack_v2_sparse_classes_75kplus_train_071621
25,070
permissive
[ { "docstring": "Test project", "name": "test_model_project", "signature": "def test_model_project(self)" }, { "docstring": "Test task", "name": "test_model_task", "signature": "def test_model_task(self)" }, { "docstring": "Test task status", "name": "test_model_task_status", ...
3
stack_v2_sparse_classes_30k_train_049992
Implement the Python class `ProjectsModelsTest` described below. Class description: Documents models tests Method signatures and docstrings: - def test_model_project(self): Test project - def test_model_task(self): Test task - def test_model_task_status(self): Test task status
Implement the Python class `ProjectsModelsTest` described below. Class description: Documents models tests Method signatures and docstrings: - def test_model_project(self): Test project - def test_model_task(self): Test task - def test_model_task_status(self): Test task status <|skeleton|> class ProjectsModelsTest: ...
001e85eaf489c93b565efe679eb159cfcfef4c67
<|skeleton|> class ProjectsModelsTest: """Documents models tests""" def test_model_project(self): """Test project""" <|body_0|> def test_model_task(self): """Test task""" <|body_1|> def test_model_task_status(self): """Test task status""" <|body_2|> <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProjectsModelsTest: """Documents models tests""" def test_model_project(self): """Test project""" obj = Project(name='test') obj.save() self.assertEquals('test', obj.name) self.assertNotEquals(obj.id, None) obj.delete() def test_model_task(self): ...
the_stack_v2_python_sparse
projects/tests.py
alejo8591/maker
train
0
f363efa9af9881501129cc3336798bf47f20b12b
[ "conv_data = Bech32BaseUtils.ConvertBits(data, 8, 5)\nif conv_data is None:\n raise ValueError('Invalid data, cannot perform conversion to base32')\nreturn conv_data", "conv_data = Bech32BaseUtils.ConvertBits(data, 5, 8, False)\nif conv_data is None:\n raise ValueError('Invalid data, cannot perform conversi...
<|body_start_0|> conv_data = Bech32BaseUtils.ConvertBits(data, 8, 5) if conv_data is None: raise ValueError('Invalid data, cannot perform conversion to base32') return conv_data <|end_body_0|> <|body_start_1|> conv_data = Bech32BaseUtils.ConvertBits(data, 5, 8, False) ...
Class container for Bech32 utility functions.
Bech32BaseUtils
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bech32BaseUtils: """Class container for Bech32 utility functions.""" def ConvertToBase32(data: Union[List[int], bytes]) -> List[int]: """Convert data to base32. Args: data (list[int] or bytes): Data to be converted Returns: list[int]: Converted data Raises: ValueError: If the string ...
stack_v2_sparse_classes_75kplus_train_071622
8,003
permissive
[ { "docstring": "Convert data to base32. Args: data (list[int] or bytes): Data to be converted Returns: list[int]: Converted data Raises: ValueError: If the string is not valid", "name": "ConvertToBase32", "signature": "def ConvertToBase32(data: Union[List[int], bytes]) -> List[int]" }, { "docstr...
3
stack_v2_sparse_classes_30k_val_002603
Implement the Python class `Bech32BaseUtils` described below. Class description: Class container for Bech32 utility functions. Method signatures and docstrings: - def ConvertToBase32(data: Union[List[int], bytes]) -> List[int]: Convert data to base32. Args: data (list[int] or bytes): Data to be converted Returns: lis...
Implement the Python class `Bech32BaseUtils` described below. Class description: Class container for Bech32 utility functions. Method signatures and docstrings: - def ConvertToBase32(data: Union[List[int], bytes]) -> List[int]: Convert data to base32. Args: data (list[int] or bytes): Data to be converted Returns: lis...
d15c75ddd74e4838c396a0d036ef6faf11b06a4b
<|skeleton|> class Bech32BaseUtils: """Class container for Bech32 utility functions.""" def ConvertToBase32(data: Union[List[int], bytes]) -> List[int]: """Convert data to base32. Args: data (list[int] or bytes): Data to be converted Returns: list[int]: Converted data Raises: ValueError: If the string ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Bech32BaseUtils: """Class container for Bech32 utility functions.""" def ConvertToBase32(data: Union[List[int], bytes]) -> List[int]: """Convert data to base32. Args: data (list[int] or bytes): Data to be converted Returns: list[int]: Converted data Raises: ValueError: If the string is not valid"...
the_stack_v2_python_sparse
bip_utils/bech32/bech32_base.py
ebellocchia/bip_utils
train
244
f347914c6c0126343762c81b6f2ccb8d05a2f7e5
[ "try:\n user = self.request.user\n tasks = Task.objects(user_id=user.id)\n serializer = self.serializer_class(tasks, many=True)\n return Response(serializer.data)\nexcept Exception as e:\n Utils.log_exception(e)\n raise e", "try:\n data = request.data.copy()\n data['user_id'] = request.use...
<|body_start_0|> try: user = self.request.user tasks = Task.objects(user_id=user.id) serializer = self.serializer_class(tasks, many=True) return Response(serializer.data) except Exception as e: Utils.log_exception(e) raise e <|end_b...
TaskViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskViewSet: def list(self, request, *args, **kwargs): """@apiVersion 1.0.0 @api {GET} /task Get list task @apiName TaskList @apiGroup Ribo_api Task @apiPermission Authentication @apiHeader {string} Authorization format: token <token_string> @apiHeaderExample {json} Request Header Exampl...
stack_v2_sparse_classes_75kplus_train_071623
5,383
permissive
[ { "docstring": "@apiVersion 1.0.0 @api {GET} /task Get list task @apiName TaskList @apiGroup Ribo_api Task @apiPermission Authentication @apiHeader {string} Authorization format: token <token_string> @apiHeaderExample {json} Request Header Example: { \"Authorization\": \"token QL7RXWUJKDIISITBDLPRUPQZAXD81XYEHZ...
4
null
Implement the Python class `TaskViewSet` described below. Class description: Implement the TaskViewSet class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): @apiVersion 1.0.0 @api {GET} /task Get list task @apiName TaskList @apiGroup Ribo_api Task @apiPermission Authentication @apiHeade...
Implement the Python class `TaskViewSet` described below. Class description: Implement the TaskViewSet class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): @apiVersion 1.0.0 @api {GET} /task Get list task @apiName TaskList @apiGroup Ribo_api Task @apiPermission Authentication @apiHeade...
8c5a00a215b42aad2f6a4167b9cb97fe11d78823
<|skeleton|> class TaskViewSet: def list(self, request, *args, **kwargs): """@apiVersion 1.0.0 @api {GET} /task Get list task @apiName TaskList @apiGroup Ribo_api Task @apiPermission Authentication @apiHeader {string} Authorization format: token <token_string> @apiHeaderExample {json} Request Header Exampl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TaskViewSet: def list(self, request, *args, **kwargs): """@apiVersion 1.0.0 @api {GET} /task Get list task @apiName TaskList @apiGroup Ribo_api Task @apiPermission Authentication @apiHeader {string} Authorization format: token <token_string> @apiHeaderExample {json} Request Header Example: { "Authoriz...
the_stack_v2_python_sparse
src/ribo_api/views/api/task.py
wahello/RiBo-Core
train
0
669d87757f3be036c1f9421489221e332c9a2d63
[ "try:\n inst = Tenant.objects.get(pk=inst_id)\nexcept Tenant.DoesNotExist:\n return api_error(code=404, msg=_('Tenant not existed.'))\ninst_admins = [x.user for x in TenantAdmin.objects.filter(tenant=inst)]\nusernames = [x.user for x in Profile.objects.filter(tenant=inst.name)]\nusers = [User.objects.get(x) f...
<|body_start_0|> try: inst = Tenant.objects.get(pk=inst_id) except Tenant.DoesNotExist: return api_error(code=404, msg=_('Tenant not existed.')) inst_admins = [x.user for x in TenantAdmin.objects.filter(tenant=inst)] usernames = [x.user for x in Profile.objects.fi...
AdminTenant
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdminTenant: def get(self, request, inst_id): """Get tenant details""" <|body_0|> def put(self, request, inst_id): """Update tenant quota""" <|body_1|> def delete(self, request, inst_id): """Delete a tenant""" <|body_2|> <|end_skeleton|>...
stack_v2_sparse_classes_75kplus_train_071624
34,523
permissive
[ { "docstring": "Get tenant details", "name": "get", "signature": "def get(self, request, inst_id)" }, { "docstring": "Update tenant quota", "name": "put", "signature": "def put(self, request, inst_id)" }, { "docstring": "Delete a tenant", "name": "delete", "signature": "d...
3
stack_v2_sparse_classes_30k_train_011338
Implement the Python class `AdminTenant` described below. Class description: Implement the AdminTenant class. Method signatures and docstrings: - def get(self, request, inst_id): Get tenant details - def put(self, request, inst_id): Update tenant quota - def delete(self, request, inst_id): Delete a tenant
Implement the Python class `AdminTenant` described below. Class description: Implement the AdminTenant class. Method signatures and docstrings: - def get(self, request, inst_id): Get tenant details - def put(self, request, inst_id): Update tenant quota - def delete(self, request, inst_id): Delete a tenant <|skeleton...
13b3ed26a04248211ef91ca70dccc617be27a3c3
<|skeleton|> class AdminTenant: def get(self, request, inst_id): """Get tenant details""" <|body_0|> def put(self, request, inst_id): """Update tenant quota""" <|body_1|> def delete(self, request, inst_id): """Delete a tenant""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AdminTenant: def get(self, request, inst_id): """Get tenant details""" try: inst = Tenant.objects.get(pk=inst_id) except Tenant.DoesNotExist: return api_error(code=404, msg=_('Tenant not existed.')) inst_admins = [x.user for x in TenantAdmin.objects.filt...
the_stack_v2_python_sparse
fhs/usr/share/python/syncwerk/restapi/restapi/api3/custom/admin/tenants.py
syncwerk/syncwerk-server-restapi
train
0
c584d949d24151ba2130fabbdc73ff211176a33c
[ "if len(postorder) == 0:\n return None\nhead = TreeNode(postorder[-1])\nstack = [head]\ni = len(postorder) - 2\nj = len(postorder) - 1\nwhile i >= 0:\n temp = None\n t = TreeNode(postorder[i])\n while stack and stack[-1].val == inorder[j]:\n temp = stack.pop()\n j -= 1\n if temp:\n ...
<|body_start_0|> if len(postorder) == 0: return None head = TreeNode(postorder[-1]) stack = [head] i = len(postorder) - 2 j = len(postorder) - 1 while i >= 0: temp = None t = TreeNode(postorder[i]) while stack and stack[-1]....
Solution
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: """if not inorder or not postorder: return i = inorder.index(postorder[-1]) root = TreeNode(postorder[-1]) root.left = self.buildTree(inorder[:i], postorder[:i]) root.right = self.buildTree(inorder[i + 1...
stack_v2_sparse_classes_75kplus_train_071625
2,912
permissive
[ { "docstring": "if not inorder or not postorder: return i = inorder.index(postorder[-1]) root = TreeNode(postorder[-1]) root.left = self.buildTree(inorder[:i], postorder[:i]) root.right = self.buildTree(inorder[i + 1:], postorder[i:-1]) return root", "name": "buildTree", "signature": "def buildTree(self...
3
stack_v2_sparse_classes_30k_train_039498
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: if not inorder or not postorder: return i = inorder.index(postorder[-1]) root = TreeNode(postorder[-1])...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: if not inorder or not postorder: return i = inorder.index(postorder[-1]) root = TreeNode(postorder[-1])...
4ea4c1579c28308455be4dfa02bd45ebd88b2d0a
<|skeleton|> class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: """if not inorder or not postorder: return i = inorder.index(postorder[-1]) root = TreeNode(postorder[-1]) root.left = self.buildTree(inorder[:i], postorder[:i]) root.right = self.buildTree(inorder[i + 1...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: """if not inorder or not postorder: return i = inorder.index(postorder[-1]) root = TreeNode(postorder[-1]) root.left = self.buildTree(inorder[:i], postorder[:i]) root.right = self.buildTree(inorder[i + 1:], postorder[...
the_stack_v2_python_sparse
src/trees/buildTree.py
way2arun/datastructures_algorithms
train
1
41dbaa4784397caab500635b32d3fb139f83c1b6
[ "root_copy = root\nself.result = []\n\ndef visit(root):\n if root.left:\n visit(root.left)\n self.result.append(root.val)\n if root.right:\n visit(root.right)\n\ndef change(root):\n if root.left:\n change(root.left)\n root.val = self.result[self.start]\n self.start += 1\n i...
<|body_start_0|> root_copy = root self.result = [] def visit(root): if root.left: visit(root.left) self.result.append(root.val) if root.right: visit(root.right) def change(root): if root.left: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def recoverTree(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms""" <|body_0|> def recoverTree_1(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place inst...
stack_v2_sparse_classes_75kplus_train_071626
3,724
no_license
[ { "docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms", "name": "recoverTree", "signature": "def recoverTree(self, root)" }, { "docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 125ms", ...
3
stack_v2_sparse_classes_30k_train_037989
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms - def recoverTree_1(self, root): :type root: TreeNode :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms - def recoverTree_1(self, root): :type root: TreeNode :...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def recoverTree(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms""" <|body_0|> def recoverTree_1(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place inst...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def recoverTree(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms""" root_copy = root self.result = [] def visit(root): if root.left: visit(root.left) self.result.appe...
the_stack_v2_python_sparse
RecoverBinarySearchTree_HARD_99.py
953250587/leetcode-python
train
2
fd0ab845463dbedfb11b44276bb0828927b70605
[ "patron_bot = PatronBot(last_name=last_name, iii_id=iii_id)\nuser = None\nif patron_bot.is_valid:\n try:\n user = User.objects.get(username=iii_id)\n except User.DoesNotExist:\n user = User(username=iii_id, last_name=last_name, is_active=True)\n user.save()\nreturn user", "try:\n ret...
<|body_start_0|> patron_bot = PatronBot(last_name=last_name, iii_id=iii_id) user = None if patron_bot.is_valid: try: user = User.objects.get(username=iii_id) except User.DoesNotExist: user = User(username=iii_id, last_name=last_name, is_act...
This backend is used with III's Patron API to authenticate a user using a last name and an III identification number.
IIIUserBackend
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IIIUserBackend: """This backend is used with III's Patron API to authenticate a user using a last name and an III identification number.""" def authenticate(self, last_name=None, iii_id=None): """The ``last_name`` and ``iii_id`` are used to authenticate againest the III server using ...
stack_v2_sparse_classes_75kplus_train_071627
1,308
permissive
[ { "docstring": "The ``last_name`` and ``iii_id`` are used to authenticate againest the III server using the PatronBot Returns None if ``last_name`` and ``iii_id`` fail to authenticate.", "name": "authenticate", "signature": "def authenticate(self, last_name=None, iii_id=None)" }, { "docstring": ...
2
stack_v2_sparse_classes_30k_train_013911
Implement the Python class `IIIUserBackend` described below. Class description: This backend is used with III's Patron API to authenticate a user using a last name and an III identification number. Method signatures and docstrings: - def authenticate(self, last_name=None, iii_id=None): The ``last_name`` and ``iii_id`...
Implement the Python class `IIIUserBackend` described below. Class description: This backend is used with III's Patron API to authenticate a user using a last name and an III identification number. Method signatures and docstrings: - def authenticate(self, last_name=None, iii_id=None): The ``last_name`` and ``iii_id`...
b5c44fa008f9afb4441988803921a93ffd615c30
<|skeleton|> class IIIUserBackend: """This backend is used with III's Patron API to authenticate a user using a last name and an III identification number.""" def authenticate(self, last_name=None, iii_id=None): """The ``last_name`` and ``iii_id`` are used to authenticate againest the III server using ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IIIUserBackend: """This backend is used with III's Patron API to authenticate a user using a last name and an III identification number.""" def authenticate(self, last_name=None, iii_id=None): """The ``last_name`` and ``iii_id`` are used to authenticate againest the III server using the PatronBot...
the_stack_v2_python_sparse
aristotle/apps/vendors/iii/backends.py
jermnelson/Discover-Aristotle
train
15
2cef49fffb8d421edd29556df88897e97487f498
[ "self.now = 0\nself.cap = capacity\nself.map = {}\nself.time = {}\nself.object = {}", "if key not in self.map:\n return -1\nif key == self.object[self.now]:\n return self.map[key]\nself.now += 1\nself.object[self.now] = key\ndel self.object[self.time[key]]\nself.time[key] = self.now\nreturn self.map[key]", ...
<|body_start_0|> self.now = 0 self.cap = capacity self.map = {} self.time = {} self.object = {} <|end_body_0|> <|body_start_1|> if key not in self.map: return -1 if key == self.object[self.now]: return self.map[key] self.now += 1 ...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus_train_071628
1,337
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
null
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
7c443f85217ab96ceac717ece7fc472271e1d3ab
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.now = 0 self.cap = capacity self.map = {} self.time = {} self.object = {} def get(self, key): """:type key: int :rtype: int""" if key not in self.map: return ...
the_stack_v2_python_sparse
zemiao/146.py
Zichuanyun/go-shuati
train
9
8160eb85ee1fa73be0df6b69e73e2857380dada5
[ "actual = stock_price_summary([])\nexpected = (0, 0)\nself.assertEqual(expected, actual)", "actual = stock_price_summary([0.5, 0.7])\nexpected = (1.2, 0)\nself.assertEqual(expected, actual)", "actual = stock_price_summary([-0.5, -0.7])\nexpected = (0, -1.2)\nself.assertEqual(expected, actual)", "actual = stoc...
<|body_start_0|> actual = stock_price_summary([]) expected = (0, 0) self.assertEqual(expected, actual) <|end_body_0|> <|body_start_1|> actual = stock_price_summary([0.5, 0.7]) expected = (1.2, 0) self.assertEqual(expected, actual) <|end_body_1|> <|body_start_2|> ...
Test class for function a1.stock_price_summary.
TestStockPriceSummary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_stock_price_summary_1(self): """Test stock_price_summary against an empty set""" <|body_0|> def test_stock_price_summary_2(self): """Test stock_price_summary against two positiv...
stack_v2_sparse_classes_75kplus_train_071629
1,450
no_license
[ { "docstring": "Test stock_price_summary against an empty set", "name": "test_stock_price_summary_1", "signature": "def test_stock_price_summary_1(self)" }, { "docstring": "Test stock_price_summary against two positive entries", "name": "test_stock_price_summary_2", "signature": "def tes...
5
stack_v2_sparse_classes_30k_train_046884
Implement the Python class `TestStockPriceSummary` described below. Class description: Test class for function a1.stock_price_summary. Method signatures and docstrings: - def test_stock_price_summary_1(self): Test stock_price_summary against an empty set - def test_stock_price_summary_2(self): Test stock_price_summar...
Implement the Python class `TestStockPriceSummary` described below. Class description: Test class for function a1.stock_price_summary. Method signatures and docstrings: - def test_stock_price_summary_1(self): Test stock_price_summary against an empty set - def test_stock_price_summary_2(self): Test stock_price_summar...
ff1ebfe2294472e38edaccca981cc467c78dcbc9
<|skeleton|> class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_stock_price_summary_1(self): """Test stock_price_summary against an empty set""" <|body_0|> def test_stock_price_summary_2(self): """Test stock_price_summary against two positiv...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_stock_price_summary_1(self): """Test stock_price_summary against an empty set""" actual = stock_price_summary([]) expected = (0, 0) self.assertEqual(expected, actual) def test_stock_...
the_stack_v2_python_sparse
Courses/1402-craftingqualitycode-coursera/code/test_stock_price_summary.py
BruceHad/notes-dev
train
1
5cc06d7b28f74db07919c51ec63fba673e933e54
[ "n = 3\nk = 2\ninput_bytes = b'abcdefgh' + b'ijklmnop'\noutput_shares = botan.zfec_encode(k, n, input_bytes)\nself.assertEqual(output_shares, [b'abcdefgh', b'ijklmnop', b'qrstuvwX'])", "def byte_iter():\n b = 0\n while True:\n yield bytes([b])\n b = (b + 1) % 256\nrandom_bytes = byte_iter()\nf...
<|body_start_0|> n = 3 k = 2 input_bytes = b'abcdefgh' + b'ijklmnop' output_shares = botan.zfec_encode(k, n, input_bytes) self.assertEqual(output_shares, [b'abcdefgh', b'ijklmnop', b'qrstuvwX']) <|end_body_0|> <|body_start_1|> def byte_iter(): b = 0 ...
Tests relating to the ZFEC bindings
BotanPythonZfecTests
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BotanPythonZfecTests: """Tests relating to the ZFEC bindings""" def test_encode(self): """Simple encoder test. Could benefit from more variations""" <|body_0|> def test_encode_decode(self): """Simple round-trip tests.""" <|body_1|> def _encode_decode...
stack_v2_sparse_classes_75kplus_train_071630
41,200
permissive
[ { "docstring": "Simple encoder test. Could benefit from more variations", "name": "test_encode", "signature": "def test_encode(self)" }, { "docstring": "Simple round-trip tests.", "name": "test_encode_decode", "signature": "def test_encode_decode(self)" }, { "docstring": "one ins...
3
stack_v2_sparse_classes_30k_train_009514
Implement the Python class `BotanPythonZfecTests` described below. Class description: Tests relating to the ZFEC bindings Method signatures and docstrings: - def test_encode(self): Simple encoder test. Could benefit from more variations - def test_encode_decode(self): Simple round-trip tests. - def _encode_decode_tes...
Implement the Python class `BotanPythonZfecTests` described below. Class description: Tests relating to the ZFEC bindings Method signatures and docstrings: - def test_encode(self): Simple encoder test. Could benefit from more variations - def test_encode_decode(self): Simple round-trip tests. - def _encode_decode_tes...
560aec3a8bfa2456cc309bac478aca9ae53f0fff
<|skeleton|> class BotanPythonZfecTests: """Tests relating to the ZFEC bindings""" def test_encode(self): """Simple encoder test. Could benefit from more variations""" <|body_0|> def test_encode_decode(self): """Simple round-trip tests.""" <|body_1|> def _encode_decode...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BotanPythonZfecTests: """Tests relating to the ZFEC bindings""" def test_encode(self): """Simple encoder test. Could benefit from more variations""" n = 3 k = 2 input_bytes = b'abcdefgh' + b'ijklmnop' output_shares = botan.zfec_encode(k, n, input_bytes) sel...
the_stack_v2_python_sparse
src/scripts/test_python.py
randombit/botan
train
2,362
dc3810119a143505151e54df5d5111996050d806
[ "assert len(scheduler_list) > 0\nfor i in six.moves.range(len(scheduler_list) - 1):\n assert scheduler_list[i][0] < scheduler_list[i + 1][0], 'step of scheduler_list should be incremental.'\nself.scheduler_list = scheduler_list\nself.cur_index = 0\nself.cur_step = 0\nself.cur_value = self.scheduler_list[0][1]\ns...
<|body_start_0|> assert len(scheduler_list) > 0 for i in six.moves.range(len(scheduler_list) - 1): assert scheduler_list[i][0] < scheduler_list[i + 1][0], 'step of scheduler_list should be incremental.' self.scheduler_list = scheduler_list self.cur_index = 0 self.cur_...
PiecewiseScheduler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PiecewiseScheduler: def __init__(self, scheduler_list): """Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]""" <|body_0|> def step(self): """Step one and fetch value according to following ru...
stack_v2_sparse_classes_75kplus_train_071631
1,944
permissive
[ { "docstring": "Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]", "name": "__init__", "signature": "def __init__(self, scheduler_list)" }, { "docstring": "Step one and fetch value according to following rule: Given sche...
2
null
Implement the Python class `PiecewiseScheduler` described below. Class description: Implement the PiecewiseScheduler class. Method signatures and docstrings: - def __init__(self, scheduler_list): Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005...
Implement the Python class `PiecewiseScheduler` described below. Class description: Implement the PiecewiseScheduler class. Method signatures and docstrings: - def __init__(self, scheduler_list): Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005...
e91150b84c631ed58a3f53232d463f8193f43dee
<|skeleton|> class PiecewiseScheduler: def __init__(self, scheduler_list): """Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]""" <|body_0|> def step(self): """Step one and fetch value according to following ru...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PiecewiseScheduler: def __init__(self, scheduler_list): """Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]""" assert len(scheduler_list) > 0 for i in six.moves.range(len(scheduler_list) - 1): asser...
the_stack_v2_python_sparse
parl/utils/scheduler.py
alexqdh/PARL
train
0
98038c928d72199c57ba7858b87c025f130e2f4e
[ "sender_name = request.json.get('sender_name', None)\ndescr = request.json.get('descr', None)\nsent_from = request.json.get('sent_from', None)\nquantity = request.json.get('quantity', None)\nprice = request.json.get('price', None)\nrecipient_name = request.json.get('recipient_name', None)\ndestination = request.jso...
<|body_start_0|> sender_name = request.json.get('sender_name', None) descr = request.json.get('descr', None) sent_from = request.json.get('sent_from', None) quantity = request.json.get('quantity', None) price = request.json.get('price', None) recipient_name = request.json...
Class to handle the creation of parcel orders
Parcels
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Parcels: """Class to handle the creation of parcel orders""" def add_parcel_order(self, sender_name, descr, sent_from, quantity, price, recipient_name, destination, status): """Add an order to the parcel delivery order list""" <|body_0|> def get_all_parcels(self): ...
stack_v2_sparse_classes_75kplus_train_071632
5,285
permissive
[ { "docstring": "Add an order to the parcel delivery order list", "name": "add_parcel_order", "signature": "def add_parcel_order(self, sender_name, descr, sent_from, quantity, price, recipient_name, destination, status)" }, { "docstring": "Fetch all parcels delivery orders from the list", "na...
4
stack_v2_sparse_classes_30k_train_008288
Implement the Python class `Parcels` described below. Class description: Class to handle the creation of parcel orders Method signatures and docstrings: - def add_parcel_order(self, sender_name, descr, sent_from, quantity, price, recipient_name, destination, status): Add an order to the parcel delivery order list - d...
Implement the Python class `Parcels` described below. Class description: Class to handle the creation of parcel orders Method signatures and docstrings: - def add_parcel_order(self, sender_name, descr, sent_from, quantity, price, recipient_name, destination, status): Add an order to the parcel delivery order list - d...
914b5cba4b82442cc7a9a01adaee321948d6abfa
<|skeleton|> class Parcels: """Class to handle the creation of parcel orders""" def add_parcel_order(self, sender_name, descr, sent_from, quantity, price, recipient_name, destination, status): """Add an order to the parcel delivery order list""" <|body_0|> def get_all_parcels(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Parcels: """Class to handle the creation of parcel orders""" def add_parcel_order(self, sender_name, descr, sent_from, quantity, price, recipient_name, destination, status): """Add an order to the parcel delivery order list""" sender_name = request.json.get('sender_name', None) de...
the_stack_v2_python_sparse
app/version1/parcel_delivery_order/models.py
SimonAwiti/sentIT-endpoints
train
0
e8d059f09f073f9569871df34e88dae4a05e5a90
[ "self.pool = object()\nself.rcs = _FakeRCS()\nself.expected_kwargs = {'headers': headers('token'), 'pool': self.pool}", "self.expected_kwargs['params'] = {'limit': 10000}\ntreq = get_fake_treq(self, 'get', 'novaurl/servers/detail', ((), self.expected_kwargs), (Response(200), '{\"servers\": {}}'))\nd = nova.list_s...
<|body_start_0|> self.pool = object() self.rcs = _FakeRCS() self.expected_kwargs = {'headers': headers('token'), 'pool': self.pool} <|end_body_0|> <|body_start_1|> self.expected_kwargs['params'] = {'limit': 10000} treq = get_fake_treq(self, 'get', 'novaurl/servers/detail', ((), ...
Tests for multi-server api helpers in :mod:`otter.integration.lib.nova`.
NovaServerCollectionTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NovaServerCollectionTestCase: """Tests for multi-server api helpers in :mod:`otter.integration.lib.nova`.""" def setUp(self): """Set up fake pool, treq, responses, and RCS.""" <|body_0|> def test_list_servers(self): """Get all addresses with a particular name and...
stack_v2_sparse_classes_75kplus_train_071633
9,051
permissive
[ { "docstring": "Set up fake pool, treq, responses, and RCS.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Get all addresses with a particular name and succeeds on 200.", "name": "test_list_servers", "signature": "def test_list_servers(self)" }, { "docstring...
3
stack_v2_sparse_classes_30k_train_000773
Implement the Python class `NovaServerCollectionTestCase` described below. Class description: Tests for multi-server api helpers in :mod:`otter.integration.lib.nova`. Method signatures and docstrings: - def setUp(self): Set up fake pool, treq, responses, and RCS. - def test_list_servers(self): Get all addresses with ...
Implement the Python class `NovaServerCollectionTestCase` described below. Class description: Tests for multi-server api helpers in :mod:`otter.integration.lib.nova`. Method signatures and docstrings: - def setUp(self): Set up fake pool, treq, responses, and RCS. - def test_list_servers(self): Get all addresses with ...
7199cdd67255fe116dbcbedea660c13453671134
<|skeleton|> class NovaServerCollectionTestCase: """Tests for multi-server api helpers in :mod:`otter.integration.lib.nova`.""" def setUp(self): """Set up fake pool, treq, responses, and RCS.""" <|body_0|> def test_list_servers(self): """Get all addresses with a particular name and...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NovaServerCollectionTestCase: """Tests for multi-server api helpers in :mod:`otter.integration.lib.nova`.""" def setUp(self): """Set up fake pool, treq, responses, and RCS.""" self.pool = object() self.rcs = _FakeRCS() self.expected_kwargs = {'headers': headers('token'), '...
the_stack_v2_python_sparse
otter/integration/lib/test_nova.py
rackerlabs/otter
train
20
3dc96e269e33553c2f05b3cf3572d1d41a41ba4c
[ "self.c_puct = c_puct\nself.n_iters = n_iters\nself.root = Node(1, c_puct, parent=None)", "for i in range(self.n_iters):\n board = chess_board.copy()\n node = self.root\n while not node.is_leaf_node():\n action, node = node.select()\n board.do_action(action)\n is_over, winner = board.is_...
<|body_start_0|> self.c_puct = c_puct self.n_iters = n_iters self.root = Node(1, c_puct, parent=None) <|end_body_0|> <|body_start_1|> for i in range(self.n_iters): board = chess_board.copy() node = self.root while not node.is_leaf_node(): ...
基于随机走棋策略的蒙特卡洛树搜索
RolloutMCTS
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RolloutMCTS: """基于随机走棋策略的蒙特卡洛树搜索""" def __init__(self, c_puct: float=5, n_iters=1000): """Parameters ---------- c_puct: float 探索常数 n_iters: int 迭代搜索次数""" <|body_0|> def get_action(self, chess_board: ChessBoard) -> int: """根据当前局面返回下一步动作 Parameters ---------- chess...
stack_v2_sparse_classes_75kplus_train_071634
2,709
permissive
[ { "docstring": "Parameters ---------- c_puct: float 探索常数 n_iters: int 迭代搜索次数", "name": "__init__", "signature": "def __init__(self, c_puct: float=5, n_iters=1000)" }, { "docstring": "根据当前局面返回下一步动作 Parameters ---------- chess_board: ChessBoard 棋盘", "name": "get_action", "signature": "def ...
4
null
Implement the Python class `RolloutMCTS` described below. Class description: 基于随机走棋策略的蒙特卡洛树搜索 Method signatures and docstrings: - def __init__(self, c_puct: float=5, n_iters=1000): Parameters ---------- c_puct: float 探索常数 n_iters: int 迭代搜索次数 - def get_action(self, chess_board: ChessBoard) -> int: 根据当前局面返回下一步动作 Parame...
Implement the Python class `RolloutMCTS` described below. Class description: 基于随机走棋策略的蒙特卡洛树搜索 Method signatures and docstrings: - def __init__(self, c_puct: float=5, n_iters=1000): Parameters ---------- c_puct: float 探索常数 n_iters: int 迭代搜索次数 - def get_action(self, chess_board: ChessBoard) -> int: 根据当前局面返回下一步动作 Parame...
f836aee7147aa2aeb47dd8b370f94950b833718d
<|skeleton|> class RolloutMCTS: """基于随机走棋策略的蒙特卡洛树搜索""" def __init__(self, c_puct: float=5, n_iters=1000): """Parameters ---------- c_puct: float 探索常数 n_iters: int 迭代搜索次数""" <|body_0|> def get_action(self, chess_board: ChessBoard) -> int: """根据当前局面返回下一步动作 Parameters ---------- chess...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RolloutMCTS: """基于随机走棋策略的蒙特卡洛树搜索""" def __init__(self, c_puct: float=5, n_iters=1000): """Parameters ---------- c_puct: float 探索常数 n_iters: int 迭代搜索次数""" self.c_puct = c_puct self.n_iters = n_iters self.root = Node(1, c_puct, parent=None) def get_action(self, chess_bo...
the_stack_v2_python_sparse
alphazero/rollout_mcts.py
wlmsoft/Alpha-Gobang-Zero
train
0
46ef8270f95a390447d1b040233d4689fcfcb1dc
[ "session = session or _Session()\ngroup_id = group_id or RecommendationGroup.latest(session).id\nreturn session.query(cls).order_by(cls.priority).filter(cls.group_id == group_id, cls.user_id == user_id).all()", "session = _Session()\nquery = session.query(cls)\nquery = query.order_by(cls.priority)\nquery = query....
<|body_start_0|> session = session or _Session() group_id = group_id or RecommendationGroup.latest(session).id return session.query(cls).order_by(cls.priority).filter(cls.group_id == group_id, cls.user_id == user_id).all() <|end_body_0|> <|body_start_1|> session = _Session() que...
Recommendation table.
Recommendation
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Recommendation: """Recommendation table.""" def for_user(cls, user_id: int, group_id: int=None, session: _Session=None) -> List[Recommendation]: """Select recommendations for the given user and group.""" <|body_0|> def next(cls, user_id: int, group_id: int=None, limit: i...
stack_v2_sparse_classes_75kplus_train_071635
49,365
permissive
[ { "docstring": "Select recommendations for the given user and group.", "name": "for_user", "signature": "def for_user(cls, user_id: int, group_id: int=None, session: _Session=None) -> List[Recommendation]" }, { "docstring": "Select next recommendation(s) for the given user and group, with the hi...
2
stack_v2_sparse_classes_30k_train_015506
Implement the Python class `Recommendation` described below. Class description: Recommendation table. Method signatures and docstrings: - def for_user(cls, user_id: int, group_id: int=None, session: _Session=None) -> List[Recommendation]: Select recommendations for the given user and group. - def next(cls, user_id: i...
Implement the Python class `Recommendation` described below. Class description: Recommendation table. Method signatures and docstrings: - def for_user(cls, user_id: int, group_id: int=None, session: _Session=None) -> List[Recommendation]: Select recommendations for the given user and group. - def next(cls, user_id: i...
3f226912ec8d303a067b7c2b794afbb15af00cf9
<|skeleton|> class Recommendation: """Recommendation table.""" def for_user(cls, user_id: int, group_id: int=None, session: _Session=None) -> List[Recommendation]: """Select recommendations for the given user and group.""" <|body_0|> def next(cls, user_id: int, group_id: int=None, limit: i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Recommendation: """Recommendation table.""" def for_user(cls, user_id: int, group_id: int=None, session: _Session=None) -> List[Recommendation]: """Select recommendations for the given user and group.""" session = session or _Session() group_id = group_id or RecommendationGroup.la...
the_stack_v2_python_sparse
refitt/database/model.py
Feliconut/refitt
train
0
45bf13a685742b214d65078cb482a5a5daa4e9f7
[ "self.shots = shots\nself.n_hidden = n_hidden\nself.n_outputs = n_hidden\nself.wxr = np.random.randn(n_hidden, n_weights_ent)\nself.n_weights_a = n_weights_a if not bias else n_weights_a + 1\nself.n_weights_ent = n_weights_ent\nself.w_size = self.n_hidden * n_weights_ent\nif n_parallel > 1:\n self.wxa = np.rando...
<|body_start_0|> self.shots = shots self.n_hidden = n_hidden self.n_outputs = n_hidden self.wxr = np.random.randn(n_hidden, n_weights_ent) self.n_weights_a = n_weights_a if not bias else n_weights_a + 1 self.n_weights_ent = n_weights_ent self.w_size = self.n_hidde...
Calculates a dense quantum layer consisting of an arbitrary encoder, ansatz and entangler
GeneralRecurrent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeneralRecurrent: """Calculates a dense quantum layer consisting of an arbitrary encoder, ansatz and entangler""" def __init__(self, n_qubits=None, n_hidden=None, n_weights_a=None, n_weights_ent=None, U_enc=None, U_a=None, U_ent=None, bias=False, n_parallel=1, shots=1000, seed_simulator=None...
stack_v2_sparse_classes_75kplus_train_071636
40,089
no_license
[ { "docstring": "Input: n_qubits (int) - The number of qubits required for input and hidden vector encoding and ansatz n_hidden (int) - The dimension of hidden feature vector n_weights_a (int) - The number of weights required per activation for ansatz n_weights_ent (int) - The number of weights required per acti...
3
stack_v2_sparse_classes_30k_train_051052
Implement the Python class `GeneralRecurrent` described below. Class description: Calculates a dense quantum layer consisting of an arbitrary encoder, ansatz and entangler Method signatures and docstrings: - def __init__(self, n_qubits=None, n_hidden=None, n_weights_a=None, n_weights_ent=None, U_enc=None, U_a=None, U...
Implement the Python class `GeneralRecurrent` described below. Class description: Calculates a dense quantum layer consisting of an arbitrary encoder, ansatz and entangler Method signatures and docstrings: - def __init__(self, n_qubits=None, n_hidden=None, n_weights_a=None, n_weights_ent=None, U_enc=None, U_a=None, U...
c3f3243fdeed6a099a16006d2bf529e2ceedc2b4
<|skeleton|> class GeneralRecurrent: """Calculates a dense quantum layer consisting of an arbitrary encoder, ansatz and entangler""" def __init__(self, n_qubits=None, n_hidden=None, n_weights_a=None, n_weights_ent=None, U_enc=None, U_a=None, U_ent=None, bias=False, n_parallel=1, shots=1000, seed_simulator=None...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GeneralRecurrent: """Calculates a dense quantum layer consisting of an arbitrary encoder, ansatz and entangler""" def __init__(self, n_qubits=None, n_hidden=None, n_weights_a=None, n_weights_ent=None, U_enc=None, U_a=None, U_ent=None, bias=False, n_parallel=1, shots=1000, seed_simulator=None, backend=qk....
the_stack_v2_python_sparse
Deep-Learning/layers.py
stiandb/Thesis
train
0
b4aa72e9ed4c749ec32e82787713d2eac4ff022e
[ "if 'update' not in self.base_url:\n self.base_url = self.base_url + '/update'\nself._assert_json_response_stop_on_error(self._login(username, password))", "if 'update' not in self.base_url:\n self.base_url = self.base_url + '/update'\nself._assert_json_response_stop_on_error(self._post('logout', session_in...
<|body_start_0|> if 'update' not in self.base_url: self.base_url = self.base_url + '/update' self._assert_json_response_stop_on_error(self._login(username, password)) <|end_body_0|> <|body_start_1|> if 'update' not in self.base_url: self.base_url = self.base_url + '/upda...
_Updatewebservice_Keywords
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Updatewebservice_Keywords: def upgrade_login(self, username, password): """Logs in user and return Session ID Login request is being forwarded to the DataWebService. For more information, visit `/update/login`_. .. _/update/login: http://wiki:8090/display/ERD/Update+Web+Service+API#Upda...
stack_v2_sparse_classes_75kplus_train_071637
6,509
no_license
[ { "docstring": "Logs in user and return Session ID Login request is being forwarded to the DataWebService. For more information, visit `/update/login`_. .. _/update/login: http://wiki:8090/display/ERD/Update+Web+Service+API#UpdateWebServiceAPI-/api/update/login", "name": "upgrade_login", "signature": "d...
5
stack_v2_sparse_classes_30k_train_002213
Implement the Python class `_Updatewebservice_Keywords` described below. Class description: Implement the _Updatewebservice_Keywords class. Method signatures and docstrings: - def upgrade_login(self, username, password): Logs in user and return Session ID Login request is being forwarded to the DataWebService. For mo...
Implement the Python class `_Updatewebservice_Keywords` described below. Class description: Implement the _Updatewebservice_Keywords class. Method signatures and docstrings: - def upgrade_login(self, username, password): Logs in user and return Session ID Login request is being forwarded to the DataWebService. For mo...
5911412b58008a4198e79853cb0eb7949c460b56
<|skeleton|> class _Updatewebservice_Keywords: def upgrade_login(self, username, password): """Logs in user and return Session ID Login request is being forwarded to the DataWebService. For more information, visit `/update/login`_. .. _/update/login: http://wiki:8090/display/ERD/Update+Web+Service+API#Upda...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _Updatewebservice_Keywords: def upgrade_login(self, username, password): """Logs in user and return Session ID Login request is being forwarded to the DataWebService. For more information, visit `/update/login`_. .. _/update/login: http://wiki:8090/display/ERD/Update+Web+Service+API#UpdateWebServiceAP...
the_stack_v2_python_sparse
src/WebServiceLibrary/keywords/_updatewebservice_keywords.py
qijia00/RobotFramework_AcceptanceTestDrivenDevelopment_Python
train
0
7f9a2b359c9ebfc98dfb9b3ffb294e55f64c586d
[ "M = 1000000007\ndp = [[0] * (k + 1) for _ in range(n + 1)]\ndp[0][0] = 1\nfor i in range(1, n + 1):\n dp[i][0] = 1\n for j in range(1, k + 1):\n dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % M\n if j >= i:\n dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + M) % M\nprint(dp)\nreturn dp[n][k]", ...
<|body_start_0|> M = 1000000007 dp = [[0] * (k + 1) for _ in range(n + 1)] dp[0][0] = 1 for i in range(1, n + 1): dp[i][0] = 1 for j in range(1, k + 1): dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % M if j >= i: dp[...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def kInversePairs(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_0|> def kInversePairs2(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_1|> def kInversePairs3(self, n, k): """:type n: int :type k: int :r...
stack_v2_sparse_classes_75kplus_train_071638
3,029
no_license
[ { "docstring": ":type n: int :type k: int :rtype: int", "name": "kInversePairs", "signature": "def kInversePairs(self, n, k)" }, { "docstring": ":type n: int :type k: int :rtype: int", "name": "kInversePairs2", "signature": "def kInversePairs2(self, n, k)" }, { "docstring": ":typ...
3
stack_v2_sparse_classes_30k_train_041471
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int - def kInversePairs2(self, n, k): :type n: int :type k: int :rtype: int - def kInversePairs3(self, n, k): :ty...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int - def kInversePairs2(self, n, k): :type n: int :type k: int :rtype: int - def kInversePairs3(self, n, k): :ty...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution: def kInversePairs(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_0|> def kInversePairs2(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_1|> def kInversePairs3(self, n, k): """:type n: int :type k: int :r...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def kInversePairs(self, n, k): """:type n: int :type k: int :rtype: int""" M = 1000000007 dp = [[0] * (k + 1) for _ in range(n + 1)] dp[0][0] = 1 for i in range(1, n + 1): dp[i][0] = 1 for j in range(1, k + 1): dp[i][j] ...
the_stack_v2_python_sparse
code629KInversePairsArray.py
cybelewang/leetcode-python
train
0
0e854a71321f5444b3a2f992ed4427f0f0f830c8
[ "self.run.start()\ncurrent_stage = self.run.start_stage\ntry:\n intent_input = self.intent_input\n if current_stage == PipelineStage.STT:\n assert self.stt_metadata is not None\n assert self.stt_stream is not None\n intent_input = await self.run.speech_to_text(self.stt_metadata, self.stt_...
<|body_start_0|> self.run.start() current_stage = self.run.start_stage try: intent_input = self.intent_input if current_stage == PipelineStage.STT: assert self.stt_metadata is not None assert self.stt_stream is not None inte...
Input to a pipeline run.
PipelineInput
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PipelineInput: """Input to a pipeline run.""" async def execute(self) -> None: """Run pipeline.""" <|body_0|> async def validate(self) -> None: """Validate pipeline input against start stage.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self....
stack_v2_sparse_classes_75kplus_train_071639
31,871
permissive
[ { "docstring": "Run pipeline.", "name": "execute", "signature": "async def execute(self) -> None" }, { "docstring": "Validate pipeline input against start stage.", "name": "validate", "signature": "async def validate(self) -> None" } ]
2
stack_v2_sparse_classes_30k_val_001993
Implement the Python class `PipelineInput` described below. Class description: Input to a pipeline run. Method signatures and docstrings: - async def execute(self) -> None: Run pipeline. - async def validate(self) -> None: Validate pipeline input against start stage.
Implement the Python class `PipelineInput` described below. Class description: Input to a pipeline run. Method signatures and docstrings: - async def execute(self) -> None: Run pipeline. - async def validate(self) -> None: Validate pipeline input against start stage. <|skeleton|> class PipelineInput: """Input to...
2e65b77b2b5c17919939481f327963abdfdc53f0
<|skeleton|> class PipelineInput: """Input to a pipeline run.""" async def execute(self) -> None: """Run pipeline.""" <|body_0|> async def validate(self) -> None: """Validate pipeline input against start stage.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PipelineInput: """Input to a pipeline run.""" async def execute(self) -> None: """Run pipeline.""" self.run.start() current_stage = self.run.start_stage try: intent_input = self.intent_input if current_stage == PipelineStage.STT: ass...
the_stack_v2_python_sparse
homeassistant/components/assist_pipeline/pipeline.py
konnected-io/home-assistant
train
24
ba18002aaabe090cabaf8c8dd270e858783b0f1b
[ "super(LoadPostgresStep, self).__init__(**kwargs)\nregion = POSTGRES_CONFIG[host_db_key]['REGION']\nrds_instance_id = POSTGRES_CONFIG[host_db_key]['RDS_INSTANCE_ID']\nuser = POSTGRES_CONFIG[host_db_key]['USERNAME']\npassword = POSTGRES_CONFIG[host_db_key]['PASSWORD']\ndatabase_node = self.create_pipeline_object(obj...
<|body_start_0|> super(LoadPostgresStep, self).__init__(**kwargs) region = POSTGRES_CONFIG[host_db_key]['REGION'] rds_instance_id = POSTGRES_CONFIG[host_db_key]['RDS_INSTANCE_ID'] user = POSTGRES_CONFIG[host_db_key]['USERNAME'] password = POSTGRES_CONFIG[host_db_key]['PASSWORD'] ...
Load Postgres Step class that helps load data into postgres
LoadPostgresStep
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadPostgresStep: """Load Postgres Step class that helps load data into postgres""" def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): """Constructor for the LoadPostgresStep class Args: table(path): table na...
stack_v2_sparse_classes_75kplus_train_071640
2,945
permissive
[ { "docstring": "Constructor for the LoadPostgresStep class Args: table(path): table name for load sql(str): sql query to be executed postgres_database(PostgresDatabase): database to excute the query output_path(str): s3 path where sql output should be saved **kwargs(optional): Keyword arguments directly passed ...
2
stack_v2_sparse_classes_30k_train_053011
Implement the Python class `LoadPostgresStep` described below. Class description: Load Postgres Step class that helps load data into postgres Method signatures and docstrings: - def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): Constructor f...
Implement the Python class `LoadPostgresStep` described below. Class description: Load Postgres Step class that helps load data into postgres Method signatures and docstrings: - def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): Constructor f...
797cb719e6c2abeda0751ada3339c72bfb19c8f2
<|skeleton|> class LoadPostgresStep: """Load Postgres Step class that helps load data into postgres""" def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): """Constructor for the LoadPostgresStep class Args: table(path): table na...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LoadPostgresStep: """Load Postgres Step class that helps load data into postgres""" def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): """Constructor for the LoadPostgresStep class Args: table(path): table name for load s...
the_stack_v2_python_sparse
dataduct/steps/load_postgres.py
EverFi/dataduct
train
3
df22a1e2abf1dd222d939296e3fc2c6d9b88e1ee
[ "for donor_name in donors:\n newFile = open(donor_name[0] + '.txt', mode='w')\n newFile.write(thankyou_dispacth[int_option](donor_name[0], lifetime_donations(tup_donor_names)))\n newFile.close()\n print(donor_name[0] + 'saved')", "str_salutation = 'Dear {},'.format(donor)\nstr_body = '\\n\\n' + 'Thank...
<|body_start_0|> for donor_name in donors: newFile = open(donor_name[0] + '.txt', mode='w') newFile.write(thankyou_dispacth[int_option](donor_name[0], lifetime_donations(tup_donor_names))) newFile.close() print(donor_name[0] + 'saved') <|end_body_0|> <|body_start...
files
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class files: def write_email(donors): """Writes emails to the donors and saves them to text files. :param donors: Tuple table that stores all the donor's donation information. :return:""" <|body_0|> def donor_email(donor, dictionary): """Formats the email with donor's name...
stack_v2_sparse_classes_75kplus_train_071641
14,291
no_license
[ { "docstring": "Writes emails to the donors and saves them to text files. :param donors: Tuple table that stores all the donor's donation information. :return:", "name": "write_email", "signature": "def write_email(donors)" }, { "docstring": "Formats the email with donor's name and total lifetim...
2
stack_v2_sparse_classes_30k_test_001323
Implement the Python class `files` described below. Class description: Implement the files class. Method signatures and docstrings: - def write_email(donors): Writes emails to the donors and saves them to text files. :param donors: Tuple table that stores all the donor's donation information. :return: - def donor_ema...
Implement the Python class `files` described below. Class description: Implement the files class. Method signatures and docstrings: - def write_email(donors): Writes emails to the donors and saves them to text files. :param donors: Tuple table that stores all the donor's donation information. :return: - def donor_ema...
e298b1151dab639659d8dfa56f47bcb43dd3438f
<|skeleton|> class files: def write_email(donors): """Writes emails to the donors and saves them to text files. :param donors: Tuple table that stores all the donor's donation information. :return:""" <|body_0|> def donor_email(donor, dictionary): """Formats the email with donor's name...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class files: def write_email(donors): """Writes emails to the donors and saves them to text files. :param donors: Tuple table that stores all the donor's donation information. :return:""" for donor_name in donors: newFile = open(donor_name[0] + '.txt', mode='w') newFile.write...
the_stack_v2_python_sparse
students/rhamersky/Lesson_5/mailroom_part3.py
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
train
13
c723ebd6d7d3e289a3454c872487d8818aa8e219
[ "pub.subscribe(self.updatePositions, 'POSITION_UPDATE')\nself.th = th\nself.parentnotebook = parentnotebook\nself.mainframe = mainframe\nwx.Panel.__init__(self, parent=parentnotebook)\nself.drawPanel()", "if self.th.df['Date'].iloc[-1] != datetime.datetime.today().strftime('%d/%m/%y'):\n return 'Last updated o...
<|body_start_0|> pub.subscribe(self.updatePositions, 'POSITION_UPDATE') self.th = th self.parentnotebook = parentnotebook self.mainframe = mainframe wx.Panel.__init__(self, parent=parentnotebook) self.drawPanel() <|end_body_0|> <|body_start_1|> if self.th.df['Dat...
TradeActivityTabPanel class: Class to define the Trade Activity tab panel
TradeActivityTabPanel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TradeActivityTabPanel: """TradeActivityTabPanel class: Class to define the Trade Activity tab panel""" def __init__(self, th, parentnotebook, mainframe): """Keyword argument: th : TradeHistory object, see TradeHistoryAnalysis.TradeHistory parentnotebook : wx.Python notebook object ma...
stack_v2_sparse_classes_75kplus_train_071642
30,343
no_license
[ { "docstring": "Keyword argument: th : TradeHistory object, see TradeHistoryAnalysis.TradeHistory parentnotebook : wx.Python notebook object mainframe : wx.Python frame object", "name": "__init__", "signature": "def __init__(self, th, parentnotebook, mainframe)" }, { "docstring": "Defines lastUp...
4
stack_v2_sparse_classes_30k_train_050860
Implement the Python class `TradeActivityTabPanel` described below. Class description: TradeActivityTabPanel class: Class to define the Trade Activity tab panel Method signatures and docstrings: - def __init__(self, th, parentnotebook, mainframe): Keyword argument: th : TradeHistory object, see TradeHistoryAnalysis.T...
Implement the Python class `TradeActivityTabPanel` described below. Class description: TradeActivityTabPanel class: Class to define the Trade Activity tab panel Method signatures and docstrings: - def __init__(self, th, parentnotebook, mainframe): Keyword argument: th : TradeHistory object, see TradeHistoryAnalysis.T...
4785714afa800147602065b6cc61242bb21f76b4
<|skeleton|> class TradeActivityTabPanel: """TradeActivityTabPanel class: Class to define the Trade Activity tab panel""" def __init__(self, th, parentnotebook, mainframe): """Keyword argument: th : TradeHistory object, see TradeHistoryAnalysis.TradeHistory parentnotebook : wx.Python notebook object ma...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TradeActivityTabPanel: """TradeActivityTabPanel class: Class to define the Trade Activity tab panel""" def __init__(self, th, parentnotebook, mainframe): """Keyword argument: th : TradeHistory object, see TradeHistoryAnalysis.TradeHistory parentnotebook : wx.Python notebook object mainframe : wx....
the_stack_v2_python_sparse
guiWidgets.py
analyticd/FlowTradingTools
train
0
74cd6f65830cc02fd088e17565b10a5e86b2668d
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('alanbur_jcaluag', 'alanbur_jcaluag')\nwith open('auth.json') as json_file:\n key = json.load(json_file)\napi_key = key['MBTA_api_key']\nurl1 = 'http://realtime.mbta.com/developer/api/v2/routes?api_key...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('alanbur_jcaluag', 'alanbur_jcaluag') with open('auth.json') as json_file: key = json.load(json_file) api_key = key['MBTA_api_key'] ...
makes an API call using the MBTA API key to get a list of all MBTA routes. for each bus route, makes an API call to get all the stops on the bus route. Finally, concatenates all the bus stops.
mbta
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class mbta: """makes an API call using the MBTA API key to get a list of all MBTA routes. for each bus route, makes an API call to get all the stops on the bus route. Finally, concatenates all the bus stops.""" def execute(trial=False): """Retrieve some data sets (not using the API here fo...
stack_v2_sparse_classes_75kplus_train_071643
4,161
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
stack_v2_sparse_classes_30k_train_053429
Implement the Python class `mbta` described below. Class description: makes an API call using the MBTA API key to get a list of all MBTA routes. for each bus route, makes an API call to get all the stops on the bus route. Finally, concatenates all the bus stops. Method signatures and docstrings: - def execute(trial=F...
Implement the Python class `mbta` described below. Class description: makes an API call using the MBTA API key to get a list of all MBTA routes. for each bus route, makes an API call to get all the stops on the bus route. Finally, concatenates all the bus stops. Method signatures and docstrings: - def execute(trial=F...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class mbta: """makes an API call using the MBTA API key to get a list of all MBTA routes. for each bus route, makes an API call to get all the stops on the bus route. Finally, concatenates all the bus stops.""" def execute(trial=False): """Retrieve some data sets (not using the API here fo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class mbta: """makes an API call using the MBTA API key to get a list of all MBTA routes. for each bus route, makes an API call to get all the stops on the bus route. Finally, concatenates all the bus stops.""" def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of...
the_stack_v2_python_sparse
alanbur_jcaluag/mbta.py
ROODAY/course-2017-fal-proj
train
3
ab40361a5a8e9d636520b13cb97550c685535c45
[ "if id:\n return session_manager.get_session_by_id(id)\nuser = getattr(current_user, 'name', None)\nif not user:\n self.abort(404, 'User not found')\nreturn session_manager.get_user_sessions(user)", "if not id:\n self.abort(400, 'Missing id')\nuser = getattr(current_user, 'name', None)\nif not user:\n ...
<|body_start_0|> if id: return session_manager.get_session_by_id(id) user = getattr(current_user, 'name', None) if not user: self.abort(404, 'User not found') return session_manager.get_user_sessions(user) <|end_body_0|> <|body_start_1|> if not id: ...
The :class:`burpui.api.admin.MySessions` resource allows you to retrieve a list of sessions and invalidate them for the current user. This resource is part of the :mod:`burpui.api.admin` module.
MySessions
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MySessions: """The :class:`burpui.api.admin.MySessions` resource allows you to retrieve a list of sessions and invalidate them for the current user. This resource is part of the :mod:`burpui.api.admin` module.""" def get(self, id=None): """Returns a list of sessions **GET** method pr...
stack_v2_sparse_classes_75kplus_train_071644
12,359
permissive
[ { "docstring": "Returns a list of sessions **GET** method provided by the webservice. :returns: Sessions", "name": "get", "signature": "def get(self, id=None)" }, { "docstring": "Delete a given session Note: ``id`` is mandatory", "name": "delete", "signature": "def delete(self, id=None)"...
2
stack_v2_sparse_classes_30k_train_033901
Implement the Python class `MySessions` described below. Class description: The :class:`burpui.api.admin.MySessions` resource allows you to retrieve a list of sessions and invalidate them for the current user. This resource is part of the :mod:`burpui.api.admin` module. Method signatures and docstrings: - def get(sel...
Implement the Python class `MySessions` described below. Class description: The :class:`burpui.api.admin.MySessions` resource allows you to retrieve a list of sessions and invalidate them for the current user. This resource is part of the :mod:`burpui.api.admin` module. Method signatures and docstrings: - def get(sel...
254f683a58baef2a7943af0895d7b1f65e79fc4c
<|skeleton|> class MySessions: """The :class:`burpui.api.admin.MySessions` resource allows you to retrieve a list of sessions and invalidate them for the current user. This resource is part of the :mod:`burpui.api.admin` module.""" def get(self, id=None): """Returns a list of sessions **GET** method pr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MySessions: """The :class:`burpui.api.admin.MySessions` resource allows you to retrieve a list of sessions and invalidate them for the current user. This resource is part of the :mod:`burpui.api.admin` module.""" def get(self, id=None): """Returns a list of sessions **GET** method provided by the...
the_stack_v2_python_sparse
burpui/api/admin.py
JanCejka/burp-ui
train
0
72d7d3ecd83133d878b17a2613ea957a2043728f
[ "status = ErrorCode.SUCCESS\ntry:\n umobile = self.get_argument('umobile')\n logging.info('[UWEB] Alarmoption request: %s', self.request.arguments)\nexcept Exception as e:\n status = ErrorCode.ILLEGAL_DATA_FORMAT\n logging.exception('[UWEB] Invalid data format. Exception: %s', e.args)\n self.write_re...
<|body_start_0|> status = ErrorCode.SUCCESS try: umobile = self.get_argument('umobile') logging.info('[UWEB] Alarmoption request: %s', self.request.arguments) except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT logging.exception('[UWEB] I...
Options about alarm info.: url: /alarmoption Key options of alarm info are as follows: 1, # login 2, # powerlow 3, # illegalshake 4, # illegalmove 5, # sos 6, # hearbeat lost 7, # region enter 8, # retion out 9, # power off 10, # stop 11, # speed_limit The alarmoption is associate with user(administrator or operator in...
AlarmOptionHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlarmOptionHandler: """Options about alarm info.: url: /alarmoption Key options of alarm info are as follows: 1, # login 2, # powerlow 3, # illegalshake 4, # illegalmove 5, # sos 6, # hearbeat lost 7, # region enter 8, # retion out 9, # power off 10, # stop 11, # speed_limit The alarmoption is as...
stack_v2_sparse_classes_75kplus_train_071645
3,171
no_license
[ { "docstring": "Display smsoption of current user. workflow: if alarmoption is exist: return alarmoption else: initialize the alarmoption return alarmoption", "name": "get", "signature": "def get(self)" }, { "docstring": "Modify alarmoptions for current user. :arg data: dict, e.g. { 'umobile':'x...
2
stack_v2_sparse_classes_30k_train_029837
Implement the Python class `AlarmOptionHandler` described below. Class description: Options about alarm info.: url: /alarmoption Key options of alarm info are as follows: 1, # login 2, # powerlow 3, # illegalshake 4, # illegalmove 5, # sos 6, # hearbeat lost 7, # region enter 8, # retion out 9, # power off 10, # stop ...
Implement the Python class `AlarmOptionHandler` described below. Class description: Options about alarm info.: url: /alarmoption Key options of alarm info are as follows: 1, # login 2, # powerlow 3, # illegalshake 4, # illegalmove 5, # sos 6, # hearbeat lost 7, # region enter 8, # retion out 9, # power off 10, # stop ...
3b095a325581b1fc48497c234f0ad55e928586a1
<|skeleton|> class AlarmOptionHandler: """Options about alarm info.: url: /alarmoption Key options of alarm info are as follows: 1, # login 2, # powerlow 3, # illegalshake 4, # illegalmove 5, # sos 6, # hearbeat lost 7, # region enter 8, # retion out 9, # power off 10, # stop 11, # speed_limit The alarmoption is as...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlarmOptionHandler: """Options about alarm info.: url: /alarmoption Key options of alarm info are as follows: 1, # login 2, # powerlow 3, # illegalshake 4, # illegalmove 5, # sos 6, # hearbeat lost 7, # region enter 8, # retion out 9, # power off 10, # stop 11, # speed_limit The alarmoption is associate with ...
the_stack_v2_python_sparse
apps/uweb/handlers/alarmoption.py
jcsy521/ydws
train
0
8099d6e0003613f125e4831fc65ba8684820cec3
[ "self.sums = {}\nif len(nums) > 0:\n self.sums[0] = nums[0]\n for i in range(1, len(nums)):\n self.sums[i] = self.sums[i - 1] + nums[i]", "if len(self.sums) == 0 or j >= len(self.sums):\n return None\nreturn self.sums[j] if i == 0 else self.sums[j] - self.sums[i - 1]" ]
<|body_start_0|> self.sums = {} if len(nums) > 0: self.sums[0] = nums[0] for i in range(1, len(nums)): self.sums[i] = self.sums[i - 1] + nums[i] <|end_body_0|> <|body_start_1|> if len(self.sums) == 0 or j >= len(self.sums): return None ...
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.sums = {} if len(nums) > 0: self.s...
stack_v2_sparse_classes_75kplus_train_071646
645
no_license
[ { "docstring": ":type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": ":type i: int :type j: int :rtype: int", "name": "sumRange", "signature": "def sumRange(self, i, j)" } ]
2
stack_v2_sparse_classes_30k_train_009232
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int <|skeleton|> class NumArray: def __init__(self, nums): ...
1d0572efd88f9ad7eccccefe3fe170e92a9b6487
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NumArray: def __init__(self, nums): """:type nums: List[int]""" self.sums = {} if len(nums) > 0: self.sums[0] = nums[0] for i in range(1, len(nums)): self.sums[i] = self.sums[i - 1] + nums[i] def sumRange(self, i, j): """:type i: int...
the_stack_v2_python_sparse
Python3/Range Sum Query - Immutable.py
alexfy/LeetCode
train
0
17af97c1b2350a2b9299788d2423628893ae3c59
[ "print('init vtkAnimCameraAroundZ')\nvtkAnimation.__init__(self, t)\nself.turn = turn\nself.time_anim_ends = t + abs(self.turn) / 10\nprint('time_anim_starts', self.time_anim_starts)\nprint('time_anim_ends', self.time_anim_ends)\nprint('turn', self.turn)\nself.camera = cam", "do = vtkAnimation.pre_execute(self)\n...
<|body_start_0|> print('init vtkAnimCameraAroundZ') vtkAnimation.__init__(self, t) self.turn = turn self.time_anim_ends = t + abs(self.turn) / 10 print('time_anim_starts', self.time_anim_starts) print('time_anim_ends', self.time_anim_ends) print('turn', self.turn)...
Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method).
vtkAnimCameraAroundZ
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class vtkAnimCameraAroundZ: """Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method).""" def __init__(self, t, cam, turn=360): """Initialize t...
stack_v2_sparse_classes_75kplus_train_071647
12,455
permissive
[ { "docstring": "Initialize the animation. The animation perform a full turn in 36 frames by default.", "name": "__init__", "signature": "def __init__(self, t, cam, turn=360)" }, { "docstring": "Execute method called to rotate the camera.", "name": "execute", "signature": "def execute(sel...
2
stack_v2_sparse_classes_30k_train_033018
Implement the Python class `vtkAnimCameraAroundZ` described below. Class description: Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method). Method signatures and docstri...
Implement the Python class `vtkAnimCameraAroundZ` described below. Class description: Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method). Method signatures and docstri...
c1546b7a8925fd1b2e887beb8bf1f86e2a40216f
<|skeleton|> class vtkAnimCameraAroundZ: """Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method).""" def __init__(self, t, cam, turn=360): """Initialize t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class vtkAnimCameraAroundZ: """Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method).""" def __init__(self, t, cam, turn=360): """Initialize the animation....
the_stack_v2_python_sparse
pymicro/view/vtk_anim.py
heprom/pymicro
train
39
2cb7875bec75f1dd54b2829700a5befe6aa410d2
[ "sentinel_sectPr = self.get_or_add_sectPr()\nself.add_p().set_sectPr(sentinel_sectPr.clone())\nfor hdrftr_ref in sentinel_sectPr.xpath('w:headerReference|w:footerReference'):\n sentinel_sectPr.remove(hdrftr_ref)\nreturn sentinel_sectPr", "if self.sectPr is not None:\n content_elms = self[:-1]\nelse:\n co...
<|body_start_0|> sentinel_sectPr = self.get_or_add_sectPr() self.add_p().set_sectPr(sentinel_sectPr.clone()) for hdrftr_ref in sentinel_sectPr.xpath('w:headerReference|w:footerReference'): sentinel_sectPr.remove(hdrftr_ref) return sentinel_sectPr <|end_body_0|> <|body_start_...
``<w:body>``, the container element for the main document story in ``document.xml``.
CT_Body
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CT_Body: """``<w:body>``, the container element for the main document story in ``document.xml``.""" def add_section_break(self): """Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exa...
stack_v2_sparse_classes_75kplus_train_071648
2,543
permissive
[ { "docstring": "Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exact clone of the previous one, except that all header and footer references are removed (and are therefore now \"inherited\" from the prior secti...
2
stack_v2_sparse_classes_30k_train_023329
Implement the Python class `CT_Body` described below. Class description: ``<w:body>``, the container element for the main document story in ``document.xml``. Method signatures and docstrings: - def add_section_break(self): Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes...
Implement the Python class `CT_Body` described below. Class description: ``<w:body>``, the container element for the main document story in ``document.xml``. Method signatures and docstrings: - def add_section_break(self): Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes...
2bfcf6b9779bf1abd41e1bc42c27007127ddbefb
<|skeleton|> class CT_Body: """``<w:body>``, the container element for the main document story in ``document.xml``.""" def add_section_break(self): """Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CT_Body: """``<w:body>``, the container element for the main document story in ``document.xml``.""" def add_section_break(self): """Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exact clone of t...
the_stack_v2_python_sparse
anuvaad-etl/anuvaad-extractor/file_translator/etl-file-translator/docx/oxml/document.py
project-anuvaad/anuvaad
train
41
6a57930adec9ff76f9348442e2131342311a2ea9
[ "info_list = []\nele_list = self.finds(By.CSS_SELECTOR, '.member_colRight_memberTable_td')\nfor ele in ele_list:\n info_list.append(ele.get_attribute('title'))\ntry:\n while 1:\n self.click(By.CSS_SELECTOR, '.js_next_page')\n ele_list = self.finds(By.CSS_SELECTOR, '.member_colRight_memberTable_t...
<|body_start_0|> info_list = [] ele_list = self.finds(By.CSS_SELECTOR, '.member_colRight_memberTable_td') for ele in ele_list: info_list.append(ele.get_attribute('title')) try: while 1: self.click(By.CSS_SELECTOR, '.js_next_page') e...
MenuContactsPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MenuContactsPage: def get_user_info(self): """兼容分页问题 1、直接取第一页内容 2、当 js_next_page 翻页元素不存在时,直接pass 3、当 js_next_page 翻页元素存在时,循环点击并取出当页内容,直到该元素属性不可点击 :return: 通讯录的全部信息""" <|body_0|> def check_user_info(self, info): """1、设置默认参数 False 2、获取首页信息,判断用户名存在,则更新参数为 True 3、首页不存在 i...
stack_v2_sparse_classes_75kplus_train_071649
5,116
no_license
[ { "docstring": "兼容分页问题 1、直接取第一页内容 2、当 js_next_page 翻页元素不存在时,直接pass 3、当 js_next_page 翻页元素存在时,循环点击并取出当页内容,直到该元素属性不可点击 :return: 通讯录的全部信息", "name": "get_user_info", "signature": "def get_user_info(self)" }, { "docstring": "1、设置默认参数 False 2、获取首页信息,判断用户名存在,则更新参数为 True 3、首页不存在 info,(1) js_next_page 翻页元...
3
null
Implement the Python class `MenuContactsPage` described below. Class description: Implement the MenuContactsPage class. Method signatures and docstrings: - def get_user_info(self): 兼容分页问题 1、直接取第一页内容 2、当 js_next_page 翻页元素不存在时,直接pass 3、当 js_next_page 翻页元素存在时,循环点击并取出当页内容,直到该元素属性不可点击 :return: 通讯录的全部信息 - def check_user_in...
Implement the Python class `MenuContactsPage` described below. Class description: Implement the MenuContactsPage class. Method signatures and docstrings: - def get_user_info(self): 兼容分页问题 1、直接取第一页内容 2、当 js_next_page 翻页元素不存在时,直接pass 3、当 js_next_page 翻页元素存在时,循环点击并取出当页内容,直到该元素属性不可点击 :return: 通讯录的全部信息 - def check_user_in...
502e5fd0521e82129c8434ada86987d4c3759c38
<|skeleton|> class MenuContactsPage: def get_user_info(self): """兼容分页问题 1、直接取第一页内容 2、当 js_next_page 翻页元素不存在时,直接pass 3、当 js_next_page 翻页元素存在时,循环点击并取出当页内容,直到该元素属性不可点击 :return: 通讯录的全部信息""" <|body_0|> def check_user_info(self, info): """1、设置默认参数 False 2、获取首页信息,判断用户名存在,则更新参数为 True 3、首页不存在 i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MenuContactsPage: def get_user_info(self): """兼容分页问题 1、直接取第一页内容 2、当 js_next_page 翻页元素不存在时,直接pass 3、当 js_next_page 翻页元素存在时,循环点击并取出当页内容,直到该元素属性不可点击 :return: 通讯录的全部信息""" info_list = [] ele_list = self.finds(By.CSS_SELECTOR, '.member_colRight_memberTable_td') for ele in ele_list: ...
the_stack_v2_python_sparse
homework_05/live/page/menu_contacts_page.py
guoccf/HogwartsLG6Gcc
train
0
1975f136643f26728a6846cbca65cdafcf5c2a1b
[ "if N == 1:\n return 1\nif N == 2:\n return 2\ndp = [1 for _ in range(N + 1)]\ndp[2] = 2\nfor i in range(3, N + 1):\n dp[i] = (2 * dp[i - 1] + dp[i - 3]) % int(1000000000.0 + 7)\nreturn dp[-1]", "import numpy as np\nif N == 1:\n return 1\nif N == 2:\n return 2\nif N % 2 == 1:\n k = (N - 2) // 2\...
<|body_start_0|> if N == 1: return 1 if N == 2: return 2 dp = [1 for _ in range(N + 1)] dp[2] = 2 for i in range(3, N + 1): dp[i] = (2 * dp[i - 1] + dp[i - 3]) % int(1000000000.0 + 7) return dp[-1] <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numTilings(self, N): """:type N: int :rtype: int 35MS""" <|body_0|> def numTilings_1(self, N): """:type N: int :rtype: int 95MS""" <|body_1|> <|end_skeleton|> <|body_start_0|> if N == 1: return 1 if N == 2: ...
stack_v2_sparse_classes_75kplus_train_071650
1,973
no_license
[ { "docstring": ":type N: int :rtype: int 35MS", "name": "numTilings", "signature": "def numTilings(self, N)" }, { "docstring": ":type N: int :rtype: int 95MS", "name": "numTilings_1", "signature": "def numTilings_1(self, N)" } ]
2
stack_v2_sparse_classes_30k_train_009600
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numTilings(self, N): :type N: int :rtype: int 35MS - def numTilings_1(self, N): :type N: int :rtype: int 95MS
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numTilings(self, N): :type N: int :rtype: int 35MS - def numTilings_1(self, N): :type N: int :rtype: int 95MS <|skeleton|> class Solution: def numTilings(self, N): ...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def numTilings(self, N): """:type N: int :rtype: int 35MS""" <|body_0|> def numTilings_1(self, N): """:type N: int :rtype: int 95MS""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def numTilings(self, N): """:type N: int :rtype: int 35MS""" if N == 1: return 1 if N == 2: return 2 dp = [1 for _ in range(N + 1)] dp[2] = 2 for i in range(3, N + 1): dp[i] = (2 * dp[i - 1] + dp[i - 3]) % int(100000...
the_stack_v2_python_sparse
DominoAndTrominoTiling_MID_790.py
953250587/leetcode-python
train
2
124c97729075dc788d84f7b3a36dfd1a0820525b
[ "from pygtt import PyGTT\nself._pygtt = PyGTT()\nself._stop = stop\nself._bus_name = bus_name\nself.bus_list = {}\nself.state_bus = {}", "self.bus_list = self._pygtt.get_by_stop(self._stop)\nself.bus_list.sort(key=get_datetime)\nif self._bus_name is not None:\n self.state_bus = self.get_bus_by_name()\n retu...
<|body_start_0|> from pygtt import PyGTT self._pygtt = PyGTT() self._stop = stop self._bus_name = bus_name self.bus_list = {} self.state_bus = {} <|end_body_0|> <|body_start_1|> self.bus_list = self._pygtt.get_by_stop(self._stop) self.bus_list.sort(key=ge...
Inteface to PyGTT.
GttData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GttData: """Inteface to PyGTT.""" def __init__(self, stop, bus_name): """Initialize the GttData class.""" <|body_0|> def get_data(self): """Get the data from the api.""" <|body_1|> def get_bus_by_name(self): """Get the bus by name.""" ...
stack_v2_sparse_classes_75kplus_train_071651
3,266
permissive
[ { "docstring": "Initialize the GttData class.", "name": "__init__", "signature": "def __init__(self, stop, bus_name)" }, { "docstring": "Get the data from the api.", "name": "get_data", "signature": "def get_data(self)" }, { "docstring": "Get the bus by name.", "name": "get_b...
3
stack_v2_sparse_classes_30k_train_011471
Implement the Python class `GttData` described below. Class description: Inteface to PyGTT. Method signatures and docstrings: - def __init__(self, stop, bus_name): Initialize the GttData class. - def get_data(self): Get the data from the api. - def get_bus_by_name(self): Get the bus by name.
Implement the Python class `GttData` described below. Class description: Inteface to PyGTT. Method signatures and docstrings: - def __init__(self, stop, bus_name): Initialize the GttData class. - def get_data(self): Get the data from the api. - def get_bus_by_name(self): Get the bus by name. <|skeleton|> class GttDa...
534eee0796950f3f6aade978316418a194a6b2a1
<|skeleton|> class GttData: """Inteface to PyGTT.""" def __init__(self, stop, bus_name): """Initialize the GttData class.""" <|body_0|> def get_data(self): """Get the data from the api.""" <|body_1|> def get_bus_by_name(self): """Get the bus by name.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GttData: """Inteface to PyGTT.""" def __init__(self, stop, bus_name): """Initialize the GttData class.""" from pygtt import PyGTT self._pygtt = PyGTT() self._stop = stop self._bus_name = bus_name self.bus_list = {} self.state_bus = {} def get_d...
the_stack_v2_python_sparse
homeassistant/custom_components/gtt/sensor.py
eliseomartelli/HomeAutomation-Config
train
32
a58e4160d68b175df5879c1827ff418d3db60558
[ "taskPath = self.basePath / taskName\nkeys: Set[str] = set()\nif taskPath.is_dir():\n keys.update((path.name for path in taskPath.iterdir()))\nreturn keys", "valuePath = self.basePath / taskName / key\nfor run in runIds:\n try:\n with open(valuePath / run) as inp:\n value = inp.readline()\...
<|body_start_0|> taskPath = self.basePath / taskName keys: Set[str] = set() if taskPath.is_dir(): keys.update((path.name for path in taskPath.iterdir())) return keys <|end_body_0|> <|body_start_1|> valuePath = self.basePath / taskName / key for run in runIds:...
ResultStorage
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResultStorage: def getCustomKeys(self, taskName: str) -> Set[str]: """Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key.""" <|body_0|...
stack_v2_sparse_classes_75kplus_train_071652
2,681
permissive
[ { "docstring": "Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key.", "name": "getCustomKeys", "signature": "def getCustomKeys(self, taskName: str) -> Set[str...
3
stack_v2_sparse_classes_30k_train_004965
Implement the Python class `ResultStorage` described below. Class description: Implement the ResultStorage class. Method signatures and docstrings: - def getCustomKeys(self, taskName: str) -> Set[str]: Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one ...
Implement the Python class `ResultStorage` described below. Class description: Implement the ResultStorage class. Method signatures and docstrings: - def getCustomKeys(self, taskName: str) -> Set[str]: Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one ...
0ecf899f66a1fb046ee869cbfa3b5374b3f8aa14
<|skeleton|> class ResultStorage: def getCustomKeys(self, taskName: str) -> Set[str]: """Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key.""" <|body_0|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResultStorage: def getCustomKeys(self, taskName: str) -> Set[str]: """Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key.""" taskPath = self.basePat...
the_stack_v2_python_sparse
src/softfab/resultlib.py
boxingbeetle/softfab
train
20
fee941112eda563154ec9e1ea07d7daf775ca48e
[ "\"\"\"\n string是一种不可变的数据类型\n O(n)的时间复杂度,还有各种类型转换\n \"\"\"\nx_s = list(str(x))\nif len(x_s) <= 1:\n return x\nsign = 1\nif x_s[0] == '-':\n sign = -1\n x_s = x_s[1:]\ni, j = (0, len(x_s) - 1)\nwhile i < j:\n x_s[i], x_s[j] = (x_s[j], x_s[i])\n i += 1\n j -= 1\nresult = sign * ...
<|body_start_0|> """ string是一种不可变的数据类型 O(n)的时间复杂度,还有各种类型转换 """ x_s = list(str(x)) if len(x_s) <= 1: return x sign = 1 if x_s[0] == '-': sign = -1 x_s = x_s[1:] i, j = (0, len(x_s) - 1) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse(self, x): """:type x: int :rtype: int""" <|body_0|> def reverse_2(self, x): """rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> """ string是一种不可变的数据...
stack_v2_sparse_classes_75kplus_train_071653
1,619
no_license
[ { "docstring": ":type x: int :rtype: int", "name": "reverse", "signature": "def reverse(self, x)" }, { "docstring": "rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:", "name": "reverse_2", "signature": "def reverse_2(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_043478
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x): :type x: int :rtype: int - def reverse_2(self, x): rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x): :type x: int :rtype: int - def reverse_2(self, x): rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return: <|skeleton|> class Solution: def r...
09b7121628df824f432b8cdd25c55f045b013c0b
<|skeleton|> class Solution: def reverse(self, x): """:type x: int :rtype: int""" <|body_0|> def reverse_2(self, x): """rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverse(self, x): """:type x: int :rtype: int""" """ string是一种不可变的数据类型 O(n)的时间复杂度,还有各种类型转换 """ x_s = list(str(x)) if len(x_s) <= 1: return x sign = 1 if x_s[0] == '-': sign = -...
the_stack_v2_python_sparse
tuter_start/7_int.py
cainingning/leetcode
train
1
33ef1fffcfec905b8f6068d382f5aeb94a0ad81a
[ "context = {}\ncotizacion = CotizacionOrdenDeTrabajo.objects.get(id=kwargs['pk'])\nif cotizacion.es_valida():\n info_repuestos_faltantes = self.verificar_inventario_sucursal(cotizacion)\n if info_repuestos_faltantes:\n self.cargar_mensajes_de_errores(info_repuestos_faltantes)\n return HttpRespon...
<|body_start_0|> context = {} cotizacion = CotizacionOrdenDeTrabajo.objects.get(id=kwargs['pk']) if cotizacion.es_valida(): info_repuestos_faltantes = self.verificar_inventario_sucursal(cotizacion) if info_repuestos_faltantes: self.cargar_mensajes_de_error...
FacturaOrdenDeTrabajoCreateView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FacturaOrdenDeTrabajoCreateView: def get(self, request, *args, **kwargs): """Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que...
stack_v2_sparse_classes_75kplus_train_071654
7,599
no_license
[ { "docstring": "Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que en inventario de la sucursal esten todos los repuestos necesarios para reparar el ve...
4
stack_v2_sparse_classes_30k_test_002385
Implement the Python class `FacturaOrdenDeTrabajoCreateView` described below. Class description: Implement the FacturaOrdenDeTrabajoCreateView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Documentacion get Permite generar la factura que es el paso siguiente a una cotización de u...
Implement the Python class `FacturaOrdenDeTrabajoCreateView` described below. Class description: Implement the FacturaOrdenDeTrabajoCreateView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Documentacion get Permite generar la factura que es el paso siguiente a una cotización de u...
3e74310b47c82d2dc420e6aaa743a2bc077fd635
<|skeleton|> class FacturaOrdenDeTrabajoCreateView: def get(self, request, *args, **kwargs): """Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FacturaOrdenDeTrabajoCreateView: def get(self, request, *args, **kwargs): """Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que en inventario...
the_stack_v2_python_sparse
concesionario/apps/factura_orden_de_trabajo/forms.py
DonAurelio/SIGIA
train
2
013c9018ed5c308ede628fd084f5bb063abb065f
[ "LOG.info('Initializing - Version:{}'.format(__version__))\nself.m_pyhouse_obj = p_pyhouse_obj\nself.m_config = Config(p_pyhouse_obj)\nself.m_utility = Utility(p_pyhouse_obj)\np_pyhouse_obj.House = HouseInformation()\nself.m_location_api = location.Api(p_pyhouse_obj)\nself.m_floor_api = floors.Api(p_pyhouse_obj)\ns...
<|body_start_0|> LOG.info('Initializing - Version:{}'.format(__version__)) self.m_pyhouse_obj = p_pyhouse_obj self.m_config = Config(p_pyhouse_obj) self.m_utility = Utility(p_pyhouse_obj) p_pyhouse_obj.House = HouseInformation() self.m_location_api = location.Api(p_pyhous...
API
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class API: def __init__(self, p_pyhouse_obj): """**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running.""" <|body_0|> def LoadConfig(self): """The house is always present but the components of the house ar...
stack_v2_sparse_classes_75kplus_train_071655
14,568
no_license
[ { "docstring": "**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running.", "name": "__init__", "signature": "def __init__(self, p_pyhouse_obj)" }, { "docstring": "The house is always present but the components of the house are plu...
5
stack_v2_sparse_classes_30k_train_003113
Implement the Python class `API` described below. Class description: Implement the API class. Method signatures and docstrings: - def __init__(self, p_pyhouse_obj): **NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running. - def LoadConfig(self): The ho...
Implement the Python class `API` described below. Class description: Implement the API class. Method signatures and docstrings: - def __init__(self, p_pyhouse_obj): **NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running. - def LoadConfig(self): The ho...
8ccbbd1494b7b33ff5099d321cda634fbb254ceb
<|skeleton|> class API: def __init__(self, p_pyhouse_obj): """**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running.""" <|body_0|> def LoadConfig(self): """The house is always present but the components of the house ar...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class API: def __init__(self, p_pyhouse_obj): """**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running.""" LOG.info('Initializing - Version:{}'.format(__version__)) self.m_pyhouse_obj = p_pyhouse_obj self.m_config = ...
the_stack_v2_python_sparse
Project/src/Modules/House/house.py
bopopescu/PyHouse
train
0
8a3c8a046cbc91b4aee99771a107e0101f23ef7c
[ "if (serial_no := data_service.serial_no) is not None:\n self._attr_unique_id = f'{serial_no}_{description.key}'\nself._attr_device_info = data_service.device_info\nself.entity_description = description\nself._data_service = data_service", "try:\n self._data_service.update()\nexcept OSError as ex:\n if s...
<|body_start_0|> if (serial_no := data_service.serial_no) is not None: self._attr_unique_id = f'{serial_no}_{description.key}' self._attr_device_info = data_service.device_info self.entity_description = description self._data_service = data_service <|end_body_0|> <|body_star...
Representation of a UPS online status.
OnlineStatus
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OnlineStatus: """Representation of a UPS online status.""" def __init__(self, data_service: APCUPSdData, description: BinarySensorEntityDescription) -> None: """Initialize the APCUPSd binary device.""" <|body_0|> def update(self) -> None: """Get the status report...
stack_v2_sparse_classes_75kplus_train_071656
2,445
permissive
[ { "docstring": "Initialize the APCUPSd binary device.", "name": "__init__", "signature": "def __init__(self, data_service: APCUPSdData, description: BinarySensorEntityDescription) -> None" }, { "docstring": "Get the status report from APCUPSd and set this entity's state.", "name": "update", ...
2
stack_v2_sparse_classes_30k_train_020152
Implement the Python class `OnlineStatus` described below. Class description: Representation of a UPS online status. Method signatures and docstrings: - def __init__(self, data_service: APCUPSdData, description: BinarySensorEntityDescription) -> None: Initialize the APCUPSd binary device. - def update(self) -> None: ...
Implement the Python class `OnlineStatus` described below. Class description: Representation of a UPS online status. Method signatures and docstrings: - def __init__(self, data_service: APCUPSdData, description: BinarySensorEntityDescription) -> None: Initialize the APCUPSd binary device. - def update(self) -> None: ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class OnlineStatus: """Representation of a UPS online status.""" def __init__(self, data_service: APCUPSdData, description: BinarySensorEntityDescription) -> None: """Initialize the APCUPSd binary device.""" <|body_0|> def update(self) -> None: """Get the status report...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OnlineStatus: """Representation of a UPS online status.""" def __init__(self, data_service: APCUPSdData, description: BinarySensorEntityDescription) -> None: """Initialize the APCUPSd binary device.""" if (serial_no := data_service.serial_no) is not None: self._attr_unique_id ...
the_stack_v2_python_sparse
homeassistant/components/apcupsd/binary_sensor.py
home-assistant/core
train
35,501
7e97ea6164f8126e8aeda62ee58122bc0718f4d2
[ "super(GroverFpGeneration, self).__init__()\nself.fingerprint_source = args.fingerprint_source\nself.iscuda = args.cuda\nself.grover = GROVEREmbedding(args)\nself.readout = Readout(rtype='mean', hidden_size=args.hidden_size)", "_, _, _, _, _, a_scope, b_scope, _ = batch\noutput = self.grover(batch)\nmol_atom_from...
<|body_start_0|> super(GroverFpGeneration, self).__init__() self.fingerprint_source = args.fingerprint_source self.iscuda = args.cuda self.grover = GROVEREmbedding(args) self.readout = Readout(rtype='mean', hidden_size=args.hidden_size) <|end_body_0|> <|body_start_1|> _,...
GroverFpGeneration class. It loads the pre-trained model and produce the fingerprints for input molecules.
GroverFpGeneration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroverFpGeneration: """GroverFpGeneration class. It loads the pre-trained model and produce the fingerprints for input molecules.""" def __init__(self, args): """Init function. :param args: the arguments.""" <|body_0|> def forward(self, batch, features_batch): ""...
stack_v2_sparse_classes_75kplus_train_071657
23,044
permissive
[ { "docstring": "Init function. :param args: the arguments.", "name": "__init__", "signature": "def __init__(self, args)" }, { "docstring": "The forward function. It takes graph batch and molecular feature batch as input and produce the fingerprints of this molecules. :param batch: :param feature...
2
stack_v2_sparse_classes_30k_train_009452
Implement the Python class `GroverFpGeneration` described below. Class description: GroverFpGeneration class. It loads the pre-trained model and produce the fingerprints for input molecules. Method signatures and docstrings: - def __init__(self, args): Init function. :param args: the arguments. - def forward(self, ba...
Implement the Python class `GroverFpGeneration` described below. Class description: GroverFpGeneration class. It loads the pre-trained model and produce the fingerprints for input molecules. Method signatures and docstrings: - def __init__(self, args): Init function. :param args: the arguments. - def forward(self, ba...
b62138429f592a97e3bfc58f5fde5e488714e281
<|skeleton|> class GroverFpGeneration: """GroverFpGeneration class. It loads the pre-trained model and produce the fingerprints for input molecules.""" def __init__(self, args): """Init function. :param args: the arguments.""" <|body_0|> def forward(self, batch, features_batch): ""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GroverFpGeneration: """GroverFpGeneration class. It loads the pre-trained model and produce the fingerprints for input molecules.""" def __init__(self, args): """Init function. :param args: the arguments.""" super(GroverFpGeneration, self).__init__() self.fingerprint_source = args...
the_stack_v2_python_sparse
embeddings/grover/grover/model/models.py
theislab/chemCPA
train
67
03696f2ef00cdf6bc3e1ef87e129dbbb5cb02939
[ "self.asteroids = []\nfor _ in range(100):\n self.asteroids.append(Asteroid.generate_random_asteroid())", "for _ in range(seconds):\n for asteroid in self.asteroids:\n asteroid.move()\n print(asteroid)\n sleep(1)" ]
<|body_start_0|> self.asteroids = [] for _ in range(100): self.asteroids.append(Asteroid.generate_random_asteroid()) <|end_body_0|> <|body_start_1|> for _ in range(seconds): for asteroid in self.asteroids: asteroid.move() print(asteroid) ...
The driver class which drives the simulation.
Controller
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Controller: """The driver class which drives the simulation.""" def __init__(self): """Initializes the controller by generating 100 random asteroids.""" <|body_0|> def simulate(self, seconds: int) -> None: """Simulates asteroids moving in a 3D space in a number o...
stack_v2_sparse_classes_75kplus_train_071658
1,086
no_license
[ { "docstring": "Initializes the controller by generating 100 random asteroids.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Simulates asteroids moving in a 3D space in a number of seconds. :param seconds: an int, number of seconds to run the simulation :return: None...
2
stack_v2_sparse_classes_30k_val_002283
Implement the Python class `Controller` described below. Class description: The driver class which drives the simulation. Method signatures and docstrings: - def __init__(self): Initializes the controller by generating 100 random asteroids. - def simulate(self, seconds: int) -> None: Simulates asteroids moving in a 3...
Implement the Python class `Controller` described below. Class description: The driver class which drives the simulation. Method signatures and docstrings: - def __init__(self): Initializes the controller by generating 100 random asteroids. - def simulate(self, seconds: int) -> None: Simulates asteroids moving in a 3...
e86956c69006f96221349fe9bd4925ad2255601e
<|skeleton|> class Controller: """The driver class which drives the simulation.""" def __init__(self): """Initializes the controller by generating 100 random asteroids.""" <|body_0|> def simulate(self, seconds: int) -> None: """Simulates asteroids moving in a 3D space in a number o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Controller: """The driver class which drives the simulation.""" def __init__(self): """Initializes the controller by generating 100 random asteroids.""" self.asteroids = [] for _ in range(100): self.asteroids.append(Asteroid.generate_random_asteroid()) def simulat...
the_stack_v2_python_sparse
lab-1-classy-asteroids-lizhiquan/lab1_driver.py
lizhiquan/learning-python
train
0
140f38f1a7fbaa36beeccd12364e62b50a5eaee4
[ "payload = jwt_payload_handler(obj)\ntoken = jwt_encode_handler(payload)\nreturn token", "password = validated_data.pop('password', None)\ninstance = self.Meta.model(**validated_data)\nif password is not None:\n instance.set_password(password)\ninstance.save()\nreturn instance" ]
<|body_start_0|> payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token <|end_body_0|> <|body_start_1|> password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance...
Serializer that represents a user registration.
UserSerializerWithToken
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserSerializerWithToken: """Serializer that represents a user registration.""" def get_token(self, obj): """Generates JWT. :return: string""" <|body_0|> def create(self, validated_data): """Handles the creation of user. :params validated_data: dict :return: strin...
stack_v2_sparse_classes_75kplus_train_071659
7,864
permissive
[ { "docstring": "Generates JWT. :return: string", "name": "get_token", "signature": "def get_token(self, obj)" }, { "docstring": "Handles the creation of user. :params validated_data: dict :return: string", "name": "create", "signature": "def create(self, validated_data)" } ]
2
null
Implement the Python class `UserSerializerWithToken` described below. Class description: Serializer that represents a user registration. Method signatures and docstrings: - def get_token(self, obj): Generates JWT. :return: string - def create(self, validated_data): Handles the creation of user. :params validated_data...
Implement the Python class `UserSerializerWithToken` described below. Class description: Serializer that represents a user registration. Method signatures and docstrings: - def get_token(self, obj): Generates JWT. :return: string - def create(self, validated_data): Handles the creation of user. :params validated_data...
753ec3b5a38f4f5d15bd451400b0374f7ffcdfa6
<|skeleton|> class UserSerializerWithToken: """Serializer that represents a user registration.""" def get_token(self, obj): """Generates JWT. :return: string""" <|body_0|> def create(self, validated_data): """Handles the creation of user. :params validated_data: dict :return: strin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserSerializerWithToken: """Serializer that represents a user registration.""" def get_token(self, obj): """Generates JWT. :return: string""" payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): ...
the_stack_v2_python_sparse
users/api/serializers.py
bangrobe/elmer
train
0
395894b682ece2b60e052c6f592624dfa651517f
[ "super().__init__(min_neg=min_neg, batch_size_per_image=batch_size_per_image, positive_fraction=positive_fraction, pool_size=pool_size)\nself._batch_size_per_image = batch_size_per_image\nlogger.info('Sampling hard negatives on a per batch basis')", "batch_size = len(target_labels)\nself.batch_size_per_image = se...
<|body_start_0|> super().__init__(min_neg=min_neg, batch_size_per_image=batch_size_per_image, positive_fraction=positive_fraction, pool_size=pool_size) self._batch_size_per_image = batch_size_per_image logger.info('Sampling hard negatives on a per batch basis') <|end_body_0|> <|body_start_1|> ...
Samples negatives and positives on a per batch basis (default sampler only does this on a per image basis) Note: :attr:`batch_size_per_image` is manipulated to sample the correct number of samples per batch, use :attr:`_batch_size_per_image` to get the number of anchors per image
HardNegativeSamplerBatched
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HardNegativeSamplerBatched: """Samples negatives and positives on a per batch basis (default sampler only does this on a per image basis) Note: :attr:`batch_size_per_image` is manipulated to sample the correct number of samples per batch, use :attr:`_batch_size_per_image` to get the number of anc...
stack_v2_sparse_classes_75kplus_train_071660
13,985
permissive
[ { "docstring": "Args: batch_size_per_image (int): number of elements to be selected per image positive_fraction (float): percentage of positive elements per batch pool_size (float): hard negatives are sampled from a pool of size: batch_size_per_image * (1 - positive_fraction) * pool_size", "name": "__init__...
2
stack_v2_sparse_classes_30k_train_026945
Implement the Python class `HardNegativeSamplerBatched` described below. Class description: Samples negatives and positives on a per batch basis (default sampler only does this on a per image basis) Note: :attr:`batch_size_per_image` is manipulated to sample the correct number of samples per batch, use :attr:`_batch_s...
Implement the Python class `HardNegativeSamplerBatched` described below. Class description: Samples negatives and positives on a per batch basis (default sampler only does this on a per image basis) Note: :attr:`batch_size_per_image` is manipulated to sample the correct number of samples per batch, use :attr:`_batch_s...
4f41faa7536dcef8fca7b647dcdca25360e5b58a
<|skeleton|> class HardNegativeSamplerBatched: """Samples negatives and positives on a per batch basis (default sampler only does this on a per image basis) Note: :attr:`batch_size_per_image` is manipulated to sample the correct number of samples per batch, use :attr:`_batch_size_per_image` to get the number of anc...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HardNegativeSamplerBatched: """Samples negatives and positives on a per batch basis (default sampler only does this on a per image basis) Note: :attr:`batch_size_per_image` is manipulated to sample the correct number of samples per batch, use :attr:`_batch_size_per_image` to get the number of anchors per imag...
the_stack_v2_python_sparse
nndet/core/boxes/sampler.py
dboun/nnDetection
train
1
fef0718cc414c04acfbe29ae1e5413ade5c204b6
[ "self.val_flag_list = []\nself.vals = set([])\nself.val_to_index = {}", "flag = False\nif val not in self.vals:\n flag = True\n self.vals.add(val)\n if self.val_to_index.get(val, -1) == -1:\n self.val_flag_list.append([val, 1])\n self.val_to_index[val] = len(self.val_flag_list) - 1\n els...
<|body_start_0|> self.val_flag_list = [] self.vals = set([]) self.val_to_index = {} <|end_body_0|> <|body_start_1|> flag = False if val not in self.vals: flag = True self.vals.add(val) if self.val_to_index.get(val, -1) == -1: s...
RandomizedSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomizedSet: def __init__(self): """Initialize your data structure here.""" <|body_0|> def insert(self, val: int) -> bool: """Inserts a value to the set. Returns true if the set did not already contain the specified element.""" <|body_1|> def remove(se...
stack_v2_sparse_classes_75kplus_train_071661
1,663
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element.", "name": "insert", "signature": "def insert(self, val: int) ...
4
stack_v2_sparse_classes_30k_train_013621
Implement the Python class `RandomizedSet` described below. Class description: Implement the RandomizedSet class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta...
Implement the Python class `RandomizedSet` described below. Class description: Implement the RandomizedSet class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta...
e4ceb275a6c9a56999289751f13e74548d9cd185
<|skeleton|> class RandomizedSet: def __init__(self): """Initialize your data structure here.""" <|body_0|> def insert(self, val: int) -> bool: """Inserts a value to the set. Returns true if the set did not already contain the specified element.""" <|body_1|> def remove(se...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RandomizedSet: def __init__(self): """Initialize your data structure here.""" self.val_flag_list = [] self.vals = set([]) self.val_to_index = {} def insert(self, val: int) -> bool: """Inserts a value to the set. Returns true if the set did not already contain the s...
the_stack_v2_python_sparse
380. Insert Delete GetRandom O(1).py
mh-rahman/Programming-Practice
train
3
fe0d5bdea9e7abdf781783893fd99c1acef4ac1d
[ "super(StochFCDecoder, self).__init__()\nself.num_layers = len(dec_layer_size)\nself.dec_layer_size = dec_layer_size\nself.pixel_max = pixel_max\nself.pixel_min = pixel_min\nfor layer in range(self.num_layers - 1):\n self.__setattr__('linear' + str(layer + 1), nn.Linear(self.dec_layer_size[layer], self.dec_layer...
<|body_start_0|> super(StochFCDecoder, self).__init__() self.num_layers = len(dec_layer_size) self.dec_layer_size = dec_layer_size self.pixel_max = pixel_max self.pixel_min = pixel_min for layer in range(self.num_layers - 1): self.__setattr__('linear' + str(la...
StochFCDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StochFCDecoder: def __init__(self, dec_layer_size, pixel_min, pixel_max): """Input Args: dec_size: Number of units in each layer of the decoder""" <|body_0|> def forward(self, input, noise, target_size): """target_size will have dim 0 as batch_size output should be s...
stack_v2_sparse_classes_75kplus_train_071662
10,873
no_license
[ { "docstring": "Input Args: dec_size: Number of units in each layer of the decoder", "name": "__init__", "signature": "def __init__(self, dec_layer_size, pixel_min, pixel_max)" }, { "docstring": "target_size will have dim 0 as batch_size output should be such that dim 1 is num_samples and all ot...
2
stack_v2_sparse_classes_30k_val_000837
Implement the Python class `StochFCDecoder` described below. Class description: Implement the StochFCDecoder class. Method signatures and docstrings: - def __init__(self, dec_layer_size, pixel_min, pixel_max): Input Args: dec_size: Number of units in each layer of the decoder - def forward(self, input, noise, target_...
Implement the Python class `StochFCDecoder` described below. Class description: Implement the StochFCDecoder class. Method signatures and docstrings: - def __init__(self, dec_layer_size, pixel_min, pixel_max): Input Args: dec_size: Number of units in each layer of the decoder - def forward(self, input, noise, target_...
ca6f291761d7559b957575c030f06ca6ae0017d2
<|skeleton|> class StochFCDecoder: def __init__(self, dec_layer_size, pixel_min, pixel_max): """Input Args: dec_size: Number of units in each layer of the decoder""" <|body_0|> def forward(self, input, noise, target_size): """target_size will have dim 0 as batch_size output should be s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StochFCDecoder: def __init__(self, dec_layer_size, pixel_min, pixel_max): """Input Args: dec_size: Number of units in each layer of the decoder""" super(StochFCDecoder, self).__init__() self.num_layers = len(dec_layer_size) self.dec_layer_size = dec_layer_size self.pixe...
the_stack_v2_python_sparse
prednet/stochastic/models/models.py
yaminibansal/pytorchprednet
train
0
dd9c3742066dce31de503978e5a2fc9637cdbbc7
[ "parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory)\nUnmarshaller._unmarshal_relationships(pkg_reader, package, parts)\nfor part in parts.values():\n part.after_unmarshal()\npackage.after_unmarshal()", "parts = {}\nfor partname, content_type, reltype, blob in pkg_reader.iter_sparts():\n ...
<|body_start_0|> parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory) Unmarshaller._unmarshal_relationships(pkg_reader, package, parts) for part in parts.values(): part.after_unmarshal() package.after_unmarshal() <|end_body_0|> <|body_start_1|> pa...
Hosts static methods for unmarshalling a package from a |PackageReader| instance.
Unmarshaller
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Unmarshaller: """Hosts static methods for unmarshalling a package from a |PackageReader| instance.""" def unmarshal(pkg_reader, package, part_factory): """Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part t...
stack_v2_sparse_classes_75kplus_train_071663
7,801
permissive
[ { "docstring": "Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part to *part_factory*. Package relationships are added to *pkg*.", "name": "unmarshal", "signature": "def unmarshal(pkg_reader, package, part_factory)" }, { ...
3
stack_v2_sparse_classes_30k_train_027941
Implement the Python class `Unmarshaller` described below. Class description: Hosts static methods for unmarshalling a package from a |PackageReader| instance. Method signatures and docstrings: - def unmarshal(pkg_reader, package, part_factory): Construct graph of parts and realized relationships based on the content...
Implement the Python class `Unmarshaller` described below. Class description: Hosts static methods for unmarshalling a package from a |PackageReader| instance. Method signatures and docstrings: - def unmarshal(pkg_reader, package, part_factory): Construct graph of parts and realized relationships based on the content...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class Unmarshaller: """Hosts static methods for unmarshalling a package from a |PackageReader| instance.""" def unmarshal(pkg_reader, package, part_factory): """Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Unmarshaller: """Hosts static methods for unmarshalling a package from a |PackageReader| instance.""" def unmarshal(pkg_reader, package, part_factory): """Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part to *part_facto...
the_stack_v2_python_sparse
Pdf_docx_pptx_xlsx_epub_png/source/docx/opc/package.py
ryfeus/lambda-packs
train
1,283
0b6b9fe093eda8c6aa22e7ba4f8f9f0fac416e14
[ "self.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.document_ids = document_ids\nself.entity_id = entity_id\nself.job_id = job_id\nself.job_instance_ids = job_instance_ids\nself.tag_ids = tag_ids\nself.tags = tags", "if dictionary is None:\n return None\ncluster_id = dicti...
<|body_start_0|> self.cluster_id = cluster_id self.cluster_incarnation_id = cluster_incarnation_id self.document_ids = document_ids self.entity_id = entity_id self.job_id = job_id self.job_instance_ids = job_instance_ids self.tag_ids = tag_ids self.tags = ...
Implementation of the 'TagsOperationParameters' model. TODO: type description here. Attributes: cluster_id (long|int): ClusterId is the Id of the cluster used for constructing JobUid. cluster_incarnation_id (long|int): ClusterIncarnationId is the incarnation Id of the cluster used for constructing JobUid. document_ids ...
TagsOperationParameters
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TagsOperationParameters: """Implementation of the 'TagsOperationParameters' model. TODO: type description here. Attributes: cluster_id (long|int): ClusterId is the Id of the cluster used for constructing JobUid. cluster_incarnation_id (long|int): ClusterIncarnationId is the incarnation Id of the ...
stack_v2_sparse_classes_75kplus_train_071664
3,511
permissive
[ { "docstring": "Constructor for the TagsOperationParameters class", "name": "__init__", "signature": "def __init__(self, cluster_id=None, cluster_incarnation_id=None, document_ids=None, entity_id=None, job_id=None, job_instance_ids=None, tag_ids=None, tags=None)" }, { "docstring": "Creates an in...
2
stack_v2_sparse_classes_30k_train_027627
Implement the Python class `TagsOperationParameters` described below. Class description: Implementation of the 'TagsOperationParameters' model. TODO: type description here. Attributes: cluster_id (long|int): ClusterId is the Id of the cluster used for constructing JobUid. cluster_incarnation_id (long|int): ClusterInca...
Implement the Python class `TagsOperationParameters` described below. Class description: Implementation of the 'TagsOperationParameters' model. TODO: type description here. Attributes: cluster_id (long|int): ClusterId is the Id of the cluster used for constructing JobUid. cluster_incarnation_id (long|int): ClusterInca...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class TagsOperationParameters: """Implementation of the 'TagsOperationParameters' model. TODO: type description here. Attributes: cluster_id (long|int): ClusterId is the Id of the cluster used for constructing JobUid. cluster_incarnation_id (long|int): ClusterIncarnationId is the incarnation Id of the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TagsOperationParameters: """Implementation of the 'TagsOperationParameters' model. TODO: type description here. Attributes: cluster_id (long|int): ClusterId is the Id of the cluster used for constructing JobUid. cluster_incarnation_id (long|int): ClusterIncarnationId is the incarnation Id of the cluster used ...
the_stack_v2_python_sparse
cohesity_management_sdk/models/tags_operation_parameters.py
cohesity/management-sdk-python
train
24
40e2651d98b08d59fadd5d303eb811d3ac6cb7c7
[ "gap = 0\nsibling = node + 1\nwhile node <= n:\n gap += min(n + 1, sibling) - node\n node *= 10\n sibling *= 10\nreturn gap", "node = 1\nsteps = 1\nwhile steps < k:\n gap = self.getGap(n, node)\n if steps + gap <= k:\n node += 1\n steps += gap\n else:\n node *= 10\n s...
<|body_start_0|> gap = 0 sibling = node + 1 while node <= n: gap += min(n + 1, sibling) - node node *= 10 sibling *= 10 return gap <|end_body_0|> <|body_start_1|> node = 1 steps = 1 while steps < k: gap = self.getGa...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getGap(self, n: int, node: int) -> int: """Compute how many nodes between node and its next sibling""" <|body_0|> def findKthNumber(self, n: int, k: int) -> int: """Similar to 386. Lexicographical Numbers This is essentially preorder traversal on 10-ary...
stack_v2_sparse_classes_75kplus_train_071665
1,647
no_license
[ { "docstring": "Compute how many nodes between node and its next sibling", "name": "getGap", "signature": "def getGap(self, n: int, node: int) -> int" }, { "docstring": "Similar to 386. Lexicographical Numbers This is essentially preorder traversal on 10-ary tree", "name": "findKthNumber", ...
2
stack_v2_sparse_classes_30k_train_008581
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getGap(self, n: int, node: int) -> int: Compute how many nodes between node and its next sibling - def findKthNumber(self, n: int, k: int) -> int: Similar to 386. Lexicograph...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getGap(self, n: int, node: int) -> int: Compute how many nodes between node and its next sibling - def findKthNumber(self, n: int, k: int) -> int: Similar to 386. Lexicograph...
ad2f5bd0aec3d2c2c77b7c18627c1dd8fe8c0653
<|skeleton|> class Solution: def getGap(self, n: int, node: int) -> int: """Compute how many nodes between node and its next sibling""" <|body_0|> def findKthNumber(self, n: int, k: int) -> int: """Similar to 386. Lexicographical Numbers This is essentially preorder traversal on 10-ary...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getGap(self, n: int, node: int) -> int: """Compute how many nodes between node and its next sibling""" gap = 0 sibling = node + 1 while node <= n: gap += min(n + 1, sibling) - node node *= 10 sibling *= 10 return gap ...
the_stack_v2_python_sparse
440 K-th Smallest in Lexicographical Order.py
jz33/LeetCodeSolutions
train
8
d069a3ccf993a139041e63561c54ec697db63e86
[ "dummy = ListNode(0)\ndummy.next = head\nprev = dummy\nwhile prev:\n prev = self.reverseKNodes(prev, k)\nreturn dummy.next", "node_k = prev\nfor i in range(k):\n if node_k is None:\n return\n node_k = node_k.next\nif node_k is None:\n return\nnode_k_plus_one = node_k.next\nprev_curr = prev\ncur...
<|body_start_0|> dummy = ListNode(0) dummy.next = head prev = dummy while prev: prev = self.reverseKNodes(prev, k) return dummy.next <|end_body_0|> <|body_start_1|> node_k = prev for i in range(k): if node_k is None: return...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseKGroup(self, head, k): """:type head: ListNode :type k: int :rtype: ListNode""" <|body_0|> def reverseKNodes(self, prev, k): """這裡專門只看 k 個點時 基本上就是普通的 reverse linked list 只是一次只反轉 k 個 prev -> (n1 -> n2 -> n3 -> ... -> nk) -> nk+1 會變成 prev -> (nk ->...
stack_v2_sparse_classes_75kplus_train_071666
3,808
no_license
[ { "docstring": ":type head: ListNode :type k: int :rtype: ListNode", "name": "reverseKGroup", "signature": "def reverseKGroup(self, head, k)" }, { "docstring": "這裡專門只看 k 個點時 基本上就是普通的 reverse linked list 只是一次只反轉 k 個 prev -> (n1 -> n2 -> n3 -> ... -> nk) -> nk+1 會變成 prev -> (nk -> nk-1 -> ... -> n...
2
stack_v2_sparse_classes_30k_train_000960
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode - def reverseKNodes(self, prev, k): 這裡專門只看 k 個點時 基本上就是普通的 reverse linked list 只是一次只反轉 k 個 pre...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode - def reverseKNodes(self, prev, k): 這裡專門只看 k 個點時 基本上就是普通的 reverse linked list 只是一次只反轉 k 個 pre...
01ee75be4ec9bbb080f170cb747f3fc443eb4d55
<|skeleton|> class Solution: def reverseKGroup(self, head, k): """:type head: ListNode :type k: int :rtype: ListNode""" <|body_0|> def reverseKNodes(self, prev, k): """這裡專門只看 k 個點時 基本上就是普通的 reverse linked list 只是一次只反轉 k 個 prev -> (n1 -> n2 -> n3 -> ... -> nk) -> nk+1 會變成 prev -> (nk ->...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseKGroup(self, head, k): """:type head: ListNode :type k: int :rtype: ListNode""" dummy = ListNode(0) dummy.next = head prev = dummy while prev: prev = self.reverseKNodes(prev, k) return dummy.next def reverseKNodes(self, prev...
the_stack_v2_python_sparse
python3/025_Reverse_Nodes_in_k-Group.py
ytatus94/Leetcode
train
0
a9e85d6d45aad138103d4343b93847a63de25530
[ "self.serializer_class = LikeSerializer\nimage_id = self.kwargs.get('image_id')\nimage = get_object_or_404(Image, pk=image_id)\nqueryset_list = image.like_set.all()\nreturn queryset_list", "self.permission_classes = [IsAuthenticated]\nself.serializer_class = CreateLikeSerializer\nimage_id = self.kwargs.get('image...
<|body_start_0|> self.serializer_class = LikeSerializer image_id = self.kwargs.get('image_id') image = get_object_or_404(Image, pk=image_id) queryset_list = image.like_set.all() return queryset_list <|end_body_0|> <|body_start_1|> self.permission_classes = [IsAuthenticat...
Класа која се користи за креирање лајка и за добављање листе свих лајкова репрезентованих у JSON формату
CreateGetLikesAPI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateGetLikesAPI: """Класа која се користи за креирање лајка и за добављање листе свих лајкова репрезентованих у JSON формату""" def get_queryset(self, *args, **kwargs): """Метода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet""" <...
stack_v2_sparse_classes_75kplus_train_071667
4,633
no_license
[ { "docstring": "Метода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet", "name": "get_queryset", "signature": "def get_queryset(self, *args, **kwargs)" }, { "docstring": "Метода помоћу које се врши креирање Окида се на HTTP POST метод :param request: us...
2
null
Implement the Python class `CreateGetLikesAPI` described below. Class description: Класа која се користи за креирање лајка и за добављање листе свих лајкова репрезентованих у JSON формату Method signatures and docstrings: - def get_queryset(self, *args, **kwargs): Метода помоћу које се добављају сви подаци :param arg...
Implement the Python class `CreateGetLikesAPI` described below. Class description: Класа која се користи за креирање лајка и за добављање листе свих лајкова репрезентованих у JSON формату Method signatures and docstrings: - def get_queryset(self, *args, **kwargs): Метода помоћу које се добављају сви подаци :param arg...
9b49cdfdcfbbc911cec23ed30ded30f6c4042522
<|skeleton|> class CreateGetLikesAPI: """Класа која се користи за креирање лајка и за добављање листе свих лајкова репрезентованих у JSON формату""" def get_queryset(self, *args, **kwargs): """Метода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet""" <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CreateGetLikesAPI: """Класа која се користи за креирање лајка и за добављање листе свих лајкова репрезентованих у JSON формату""" def get_queryset(self, *args, **kwargs): """Метода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet""" self.serialize...
the_stack_v2_python_sparse
src/likes/api/views.py
milosb793/django-gallery-api
train
0
cf13bafedbe5516251060631769c8455c54ec7de
[ "self.port_min = port_min\nself.port_max = port_max\nself.logger = logging.getLogger('PortUtil')\nself.list_ports = []", "rand = Random()\nnum = rand.randint(self.port_min, self.port_max)\nwhile num in self.list_ports:\n num = rand.randint(self.port_min, self.port_max)\nself.list_ports.append(num)\nreturn num"...
<|body_start_0|> self.port_min = port_min self.port_max = port_max self.logger = logging.getLogger('PortUtil') self.list_ports = [] <|end_body_0|> <|body_start_1|> rand = Random() num = rand.randint(self.port_min, self.port_max) while num in self.list_ports: ...
Base class to get the utility functions in your tests
PortUtil
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PortUtil: """Base class to get the utility functions in your tests""" def __init__(self, port_min=PORT_MIN, port_max=PORT_MAX): """Constructor 'port_min' and 'port_max' are the range of ports""" <|body_0|> def _get_random_port(self): """generates a random int bet...
stack_v2_sparse_classes_75kplus_train_071668
2,304
no_license
[ { "docstring": "Constructor 'port_min' and 'port_max' are the range of ports", "name": "__init__", "signature": "def __init__(self, port_min=PORT_MIN, port_max=PORT_MAX)" }, { "docstring": "generates a random int between port_min and port_max. @rtype: integer @return: returns a random port betwe...
3
null
Implement the Python class `PortUtil` described below. Class description: Base class to get the utility functions in your tests Method signatures and docstrings: - def __init__(self, port_min=PORT_MIN, port_max=PORT_MAX): Constructor 'port_min' and 'port_max' are the range of ports - def _get_random_port(self): gener...
Implement the Python class `PortUtil` described below. Class description: Base class to get the utility functions in your tests Method signatures and docstrings: - def __init__(self, port_min=PORT_MIN, port_max=PORT_MAX): Constructor 'port_min' and 'port_max' are the range of ports - def _get_random_port(self): gener...
1eaf2243449009cb83e0e25647f4d64cf0aa456f
<|skeleton|> class PortUtil: """Base class to get the utility functions in your tests""" def __init__(self, port_min=PORT_MIN, port_max=PORT_MAX): """Constructor 'port_min' and 'port_max' are the range of ports""" <|body_0|> def _get_random_port(self): """generates a random int bet...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PortUtil: """Base class to get the utility functions in your tests""" def __init__(self, port_min=PORT_MIN, port_max=PORT_MAX): """Constructor 'port_min' and 'port_max' are the range of ports""" self.port_min = port_min self.port_max = port_max self.logger = logging.getLog...
the_stack_v2_python_sparse
lib/sumotest/util/utilities.py
breakaway83/sumo-pytest
train
0
7b4371a41be00fc86b862d5445b703d32fdd3783
[ "self.searchterm = searchterm.lower()\nself.textkey = textkey\ntextsonly = (e['_source'].get(self.textkey, '') for e in documents)\nvectorizer.fit(textsonly)\nself.df1 = pd.DataFrame(columns=['Type', 'Publication Date', 'Tf-idf'])\nfor e in documents:\n X = vectorizer.transform([e['_source'].get(self.textkey, ''...
<|body_start_0|> self.searchterm = searchterm.lower() self.textkey = textkey textsonly = (e['_source'].get(self.textkey, '') for e in documents) vectorizer.fit(textsonly) self.df1 = pd.DataFrame(columns=['Type', 'Publication Date', 'Tf-idf']) for e in documents: ...
hype_tfidf
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class hype_tfidf: def fit(self, documents, searchterm, textkey): """Calculates Tf-idf score for each document and creates a dataframe Note: does not work with documents obtained through a generator (generators have no len) Parameters ---- documents: News articles stored as dicts in the Inca da...
stack_v2_sparse_classes_75kplus_train_071669
7,812
no_license
[ { "docstring": "Calculates Tf-idf score for each document and creates a dataframe Note: does not work with documents obtained through a generator (generators have no len) Parameters ---- documents: News articles stored as dicts in the Inca database searchterm: string Word or words (phrase) used to calculate the...
2
stack_v2_sparse_classes_30k_train_021940
Implement the Python class `hype_tfidf` described below. Class description: Implement the hype_tfidf class. Method signatures and docstrings: - def fit(self, documents, searchterm, textkey): Calculates Tf-idf score for each document and creates a dataframe Note: does not work with documents obtained through a generat...
Implement the Python class `hype_tfidf` described below. Class description: Implement the hype_tfidf class. Method signatures and docstrings: - def fit(self, documents, searchterm, textkey): Calculates Tf-idf score for each document and creates a dataframe Note: does not work with documents obtained through a generat...
b3532ca47d59013fe88731ee0a5fe95b6e8e40f1
<|skeleton|> class hype_tfidf: def fit(self, documents, searchterm, textkey): """Calculates Tf-idf score for each document and creates a dataframe Note: does not work with documents obtained through a generator (generators have no len) Parameters ---- documents: News articles stored as dicts in the Inca da...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class hype_tfidf: def fit(self, documents, searchterm, textkey): """Calculates Tf-idf score for each document and creates a dataframe Note: does not work with documents obtained through a generator (generators have no len) Parameters ---- documents: News articles stored as dicts in the Inca database searcht...
the_stack_v2_python_sparse
inca/analysis/hype_analysis.py
uvacw/inca
train
23
d3eff8dc0a267d363f7759037a727c4b04dc7553
[ "n = []\nwhile head != None:\n n.append(head.val)\n head = head.next\nreturn self.sortedArrayToBST(n)", "k = len(nums)\nif k == 0:\n return None\nif k == 1:\n return TreeNode(nums[0])\nq = k / 2\nNode = TreeNode(nums[q])\nif q == 0:\n Node.left = None\nelse:\n Node.left = self.sortedArrayToBST(n...
<|body_start_0|> n = [] while head != None: n.append(head.val) head = head.next return self.sortedArrayToBST(n) <|end_body_0|> <|body_start_1|> k = len(nums) if k == 0: return None if k == 1: return TreeNode(nums[0]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sortedListToBST(self, head): """:type head: ListNode :rtype: TreeNode""" <|body_0|> def sortedArrayToBST(self, nums): """:type nums: List[int] :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = [] while head !...
stack_v2_sparse_classes_75kplus_train_071670
1,041
no_license
[ { "docstring": ":type head: ListNode :rtype: TreeNode", "name": "sortedListToBST", "signature": "def sortedListToBST(self, head)" }, { "docstring": ":type nums: List[int] :rtype: TreeNode", "name": "sortedArrayToBST", "signature": "def sortedArrayToBST(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_012577
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode - def sortedArrayToBST(self, nums): :type nums: List[int] :rtype: TreeNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode - def sortedArrayToBST(self, nums): :type nums: List[int] :rtype: TreeNode <|skeleton|> class Solution: ...
16422c3297ff5911a3721dcf1a5b50d09187fbc5
<|skeleton|> class Solution: def sortedListToBST(self, head): """:type head: ListNode :rtype: TreeNode""" <|body_0|> def sortedArrayToBST(self, nums): """:type nums: List[int] :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def sortedListToBST(self, head): """:type head: ListNode :rtype: TreeNode""" n = [] while head != None: n.append(head.val) head = head.next return self.sortedArrayToBST(n) def sortedArrayToBST(self, nums): """:type nums: List[int] ...
the_stack_v2_python_sparse
109.py
Robert-MYM/LeetCode620
train
0
3a506072f1516227912b3d85df11c1590b4abed5
[ "self._reactor = reactor\nself._getThreadPool = reactor.getThreadPool if getThreadPool is None else getThreadPool\nself._getaddrinfo = getaddrinfo", "pool = self._getThreadPool()\naddressFamily = _typesToAF[_any if addressTypes is None else frozenset(addressTypes)]\nsocketType = _transportToSocket[transportSemant...
<|body_start_0|> self._reactor = reactor self._getThreadPool = reactor.getThreadPool if getThreadPool is None else getThreadPool self._getaddrinfo = getaddrinfo <|end_body_0|> <|body_start_1|> pool = self._getThreadPool() addressFamily = _typesToAF[_any if addressTypes is None e...
L{IHostnameResolver} implementation that resolves hostnames by calling L{getaddrinfo} in a thread.
GAIResolver
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GAIResolver: """L{IHostnameResolver} implementation that resolves hostnames by calling L{getaddrinfo} in a thread.""" def __init__(self, reactor, getThreadPool=None, getaddrinfo=getaddrinfo): """Create a L{GAIResolver}. @param reactor: the reactor to schedule result-delivery on @type...
stack_v2_sparse_classes_75kplus_train_071671
8,465
permissive
[ { "docstring": "Create a L{GAIResolver}. @param reactor: the reactor to schedule result-delivery on @type reactor: L{IReactorThreads} @param getThreadPool: a function to retrieve the thread pool to use for scheduling name resolutions. If not supplied, the use the given C{reactor}'s thread pool. @type getThreadP...
2
stack_v2_sparse_classes_30k_train_010793
Implement the Python class `GAIResolver` described below. Class description: L{IHostnameResolver} implementation that resolves hostnames by calling L{getaddrinfo} in a thread. Method signatures and docstrings: - def __init__(self, reactor, getThreadPool=None, getaddrinfo=getaddrinfo): Create a L{GAIResolver}. @param ...
Implement the Python class `GAIResolver` described below. Class description: L{IHostnameResolver} implementation that resolves hostnames by calling L{getaddrinfo} in a thread. Method signatures and docstrings: - def __init__(self, reactor, getThreadPool=None, getaddrinfo=getaddrinfo): Create a L{GAIResolver}. @param ...
5cee0a8c4180a3108538b4e4ce945a18726595a6
<|skeleton|> class GAIResolver: """L{IHostnameResolver} implementation that resolves hostnames by calling L{getaddrinfo} in a thread.""" def __init__(self, reactor, getThreadPool=None, getaddrinfo=getaddrinfo): """Create a L{GAIResolver}. @param reactor: the reactor to schedule result-delivery on @type...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GAIResolver: """L{IHostnameResolver} implementation that resolves hostnames by calling L{getaddrinfo} in a thread.""" def __init__(self, reactor, getThreadPool=None, getaddrinfo=getaddrinfo): """Create a L{GAIResolver}. @param reactor: the reactor to schedule result-delivery on @type reactor: L{I...
the_stack_v2_python_sparse
venv/Lib/site-packages/twisted/internet/_resolver.py
zoelesv/Smathchat
train
9
18feff12de5d7d40baaf70194e01a8fbae38a072
[ "cleaned_data = super(DescriptorAdmin, self).clean(*args, **kwargs)\nif self.instance.pk and self.instance.calculatorSoftware != 'manual':\n raise ValidationError('This descriptor is not a manual descriptor, and thus cannot be edited using the django admin', 'not_manual')\nreturn cleaned_data", "descriptor = s...
<|body_start_0|> cleaned_data = super(DescriptorAdmin, self).clean(*args, **kwargs) if self.instance.pk and self.instance.calculatorSoftware != 'manual': raise ValidationError('This descriptor is not a manual descriptor, and thus cannot be edited using the django admin', 'not_manual') ...
A mixin for behaviours common to all descriptor admin forms.
DescriptorAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DescriptorAdmin: """A mixin for behaviours common to all descriptor admin forms.""" def clean(self, *args, **kwargs): """Method is purely desingned to stop the overwriting of plugin descriptors.""" <|body_0|> def save(self, commit=True, *args, **kwargs): """Save ...
stack_v2_sparse_classes_75kplus_train_071672
3,231
no_license
[ { "docstring": "Method is purely desingned to stop the overwriting of plugin descriptors.", "name": "clean", "signature": "def clean(self, *args, **kwargs)" }, { "docstring": "Save the new descriptor, forcing it to be manual.", "name": "save", "signature": "def save(self, commit=True, *a...
2
null
Implement the Python class `DescriptorAdmin` described below. Class description: A mixin for behaviours common to all descriptor admin forms. Method signatures and docstrings: - def clean(self, *args, **kwargs): Method is purely desingned to stop the overwriting of plugin descriptors. - def save(self, commit=True, *a...
Implement the Python class `DescriptorAdmin` described below. Class description: A mixin for behaviours common to all descriptor admin forms. Method signatures and docstrings: - def clean(self, *args, **kwargs): Method is purely desingned to stop the overwriting of plugin descriptors. - def save(self, commit=True, *a...
eae2009eadf87ffd2378233f3e153d385f4654d2
<|skeleton|> class DescriptorAdmin: """A mixin for behaviours common to all descriptor admin forms.""" def clean(self, *args, **kwargs): """Method is purely desingned to stop the overwriting of plugin descriptors.""" <|body_0|> def save(self, commit=True, *args, **kwargs): """Save ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DescriptorAdmin: """A mixin for behaviours common to all descriptor admin forms.""" def clean(self, *args, **kwargs): """Method is purely desingned to stop the overwriting of plugin descriptors.""" cleaned_data = super(DescriptorAdmin, self).clean(*args, **kwargs) if self.instance...
the_stack_v2_python_sparse
DRP/forms/descriptor.py
zhaojhao/DRP
train
0
565556e3aa2d5aa33593ebf13e18d8a2043670b4
[ "data = tfds.load('ted_hrlr_translate/pt_to_en', as_supervised=True)\nself.data_train = data['train']\nself.data_valid = data['validation']\ntokenizer_pt, tokenizer_en = self.tokenize_dataset(self.data_train)\nself.tokenizer_pt = tokenizer_pt\nself.tokenizer_en = tokenizer_en", "encoder = tfds.deprecated.text.Sub...
<|body_start_0|> data = tfds.load('ted_hrlr_translate/pt_to_en', as_supervised=True) self.data_train = data['train'] self.data_valid = data['validation'] tokenizer_pt, tokenizer_en = self.tokenize_dataset(self.data_train) self.tokenizer_pt = tokenizer_pt self.tokenizer_en...
Class to load an prepare a dataset for machine translation
Dataset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset: """Class to load an prepare a dataset for machine translation""" def __init__(self): """Init""" <|body_0|> def tokenize_dataset(self, data): """Creates sub-word tokenizers for a dataset data: tf.data.Dataset whose examples are formatted as a table (pt, e...
stack_v2_sparse_classes_75kplus_train_071673
1,427
no_license
[ { "docstring": "Init", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Creates sub-word tokenizers for a dataset data: tf.data.Dataset whose examples are formatted as a table (pt, en) pt: tf.Tensor containing the Portuguese sentence en: tf.Tensor containing the English s...
2
stack_v2_sparse_classes_30k_train_041984
Implement the Python class `Dataset` described below. Class description: Class to load an prepare a dataset for machine translation Method signatures and docstrings: - def __init__(self): Init - def tokenize_dataset(self, data): Creates sub-word tokenizers for a dataset data: tf.data.Dataset whose examples are format...
Implement the Python class `Dataset` described below. Class description: Class to load an prepare a dataset for machine translation Method signatures and docstrings: - def __init__(self): Init - def tokenize_dataset(self, data): Creates sub-word tokenizers for a dataset data: tf.data.Dataset whose examples are format...
2757c8526290197d45a4de33cda71e686ddcbf1c
<|skeleton|> class Dataset: """Class to load an prepare a dataset for machine translation""" def __init__(self): """Init""" <|body_0|> def tokenize_dataset(self, data): """Creates sub-word tokenizers for a dataset data: tf.data.Dataset whose examples are formatted as a table (pt, e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Dataset: """Class to load an prepare a dataset for machine translation""" def __init__(self): """Init""" data = tfds.load('ted_hrlr_translate/pt_to_en', as_supervised=True) self.data_train = data['train'] self.data_valid = data['validation'] tokenizer_pt, tokenizer...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/0-dataset.py
95ktsmith/holbertonschool-machine_learning
train
0
9082c4db34b78862d8fe310fdc52ab21b705f106
[ "super().__init__(*args, **kwargs)\nif log_level is not None:\n self.log_level = log_level\nelse:\n self.log_level = logging.INFO\nself.log = self.setup_logger()", "formatter = ColoredFormatter('%(log_color)s[%(asctime)s.%(msecs)03d][%(levelname)-8s] %(name)-20s: %(reset)s%(white)s%(message)s', datefmt='%d-...
<|body_start_0|> super().__init__(*args, **kwargs) if log_level is not None: self.log_level = log_level else: self.log_level = logging.INFO self.log = self.setup_logger() <|end_body_0|> <|body_start_1|> formatter = ColoredFormatter('%(log_color)s[%(asctim...
Log class
Logger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Logger: """Log class""" def __init__(self, *args, log_level=None, **kwargs): """Initialisation method""" <|body_0|> def setup_logger(self): """Return a logger with a default ColoredFormatter.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super...
stack_v2_sparse_classes_75kplus_train_071674
1,672
permissive
[ { "docstring": "Initialisation method", "name": "__init__", "signature": "def __init__(self, *args, log_level=None, **kwargs)" }, { "docstring": "Return a logger with a default ColoredFormatter.", "name": "setup_logger", "signature": "def setup_logger(self)" } ]
2
stack_v2_sparse_classes_30k_train_025232
Implement the Python class `Logger` described below. Class description: Log class Method signatures and docstrings: - def __init__(self, *args, log_level=None, **kwargs): Initialisation method - def setup_logger(self): Return a logger with a default ColoredFormatter.
Implement the Python class `Logger` described below. Class description: Log class Method signatures and docstrings: - def __init__(self, *args, log_level=None, **kwargs): Initialisation method - def setup_logger(self): Return a logger with a default ColoredFormatter. <|skeleton|> class Logger: """Log class""" ...
836498b210d2f921e76292df8046cd79006b458a
<|skeleton|> class Logger: """Log class""" def __init__(self, *args, log_level=None, **kwargs): """Initialisation method""" <|body_0|> def setup_logger(self): """Return a logger with a default ColoredFormatter.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Logger: """Log class""" def __init__(self, *args, log_level=None, **kwargs): """Initialisation method""" super().__init__(*args, **kwargs) if log_level is not None: self.log_level = log_level else: self.log_level = logging.INFO self.log = se...
the_stack_v2_python_sparse
src/pyndf/logbook.py
Guillaume-Guardia/ndf-python
train
0
fdc8df03e965bad1ff26c194c2a80215b025f00c
[ "kwargs.setdefault('environment', {})\nkwargs.setdefault('id', uuid.uuid4())\nkwargs['environment']['RENGA_CONTEXT_ID'] = str(context.id)\nexecution = cls(context=context, **kwargs)\nreturn execution", "if isinstance(states, ExecutionStates):\n states = {states}\nif not isinstance(states, set):\n states = s...
<|body_start_0|> kwargs.setdefault('environment', {}) kwargs.setdefault('id', uuid.uuid4()) kwargs['environment']['RENGA_CONTEXT_ID'] = str(context.id) execution = cls(context=context, **kwargs) return execution <|end_body_0|> <|body_start_1|> if isinstance(states, Execu...
Represent an execution of a context. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps.
Execution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Execution: """Represent an execution of a context. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps.""" def from_context(cls, context, **kwargs): """Create a new execution for a given context.""" <|body_0|> def check_...
stack_v2_sparse_classes_75kplus_train_071675
4,144
permissive
[ { "docstring": "Create a new execution for a given context.", "name": "from_context", "signature": "def from_context(cls, context, **kwargs)" }, { "docstring": "Check whether the execution is in one of the specified states.", "name": "check_state", "signature": "def check_state(self, sta...
2
stack_v2_sparse_classes_30k_train_038854
Implement the Python class `Execution` described below. Class description: Represent an execution of a context. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps. Method signatures and docstrings: - def from_context(cls, context, **kwargs): Create a new execution f...
Implement the Python class `Execution` described below. Class description: Represent an execution of a context. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps. Method signatures and docstrings: - def from_context(cls, context, **kwargs): Create a new execution f...
ee0fb451c0525cedd547ca96b8c950424a704874
<|skeleton|> class Execution: """Represent an execution of a context. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps.""" def from_context(cls, context, **kwargs): """Create a new execution for a given context.""" <|body_0|> def check_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Execution: """Represent an execution of a context. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps.""" def from_context(cls, context, **kwargs): """Create a new execution for a given context.""" kwargs.setdefault('environment', {}) ...
the_stack_v2_python_sparse
renga_deployer/models.py
SwissDataScienceCenter/renga-deployer
train
1
4f7be8f18bc9f29a6f551b454cc733c0fe73aeb6
[ "head = validated_data['header']\nload = validated_data['payload']\nlat = load.get('latitude', DEFAULT_DEC)\nlng = load.get('longitude', DEFAULT_DEC)\nfinal_data = {'messageID': head.get('messageID', DEFAULT_STR), 'sensorID': head.get('sensorID', DEFAULT_STR), 'macAddress': head.get('macAddress', DEFAULT_STR), 'nam...
<|body_start_0|> head = validated_data['header'] load = validated_data['payload'] lat = load.get('latitude', DEFAULT_DEC) lng = load.get('longitude', DEFAULT_DEC) final_data = {'messageID': head.get('messageID', DEFAULT_STR), 'sensorID': head.get('sensorID', DEFAULT_STR), 'macAdd...
TrashCanSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrashCanSerializer: def create(self, validated_data): """Create and return a new `TrashCan` instance, given the validated data.""" <|body_0|> def update(self, instance, validated_data): """Update and return an existing `TrashCan` instance, given the validated data.""...
stack_v2_sparse_classes_75kplus_train_071676
2,605
no_license
[ { "docstring": "Create and return a new `TrashCan` instance, given the validated data.", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "Update and return an existing `TrashCan` instance, given the validated data.", "name": "update", "signature": "def...
2
stack_v2_sparse_classes_30k_train_005747
Implement the Python class `TrashCanSerializer` described below. Class description: Implement the TrashCanSerializer class. Method signatures and docstrings: - def create(self, validated_data): Create and return a new `TrashCan` instance, given the validated data. - def update(self, instance, validated_data): Update ...
Implement the Python class `TrashCanSerializer` described below. Class description: Implement the TrashCanSerializer class. Method signatures and docstrings: - def create(self, validated_data): Create and return a new `TrashCan` instance, given the validated data. - def update(self, instance, validated_data): Update ...
fbe9e5573bef8baebfbc72e82ce4ac0a5a23ee0c
<|skeleton|> class TrashCanSerializer: def create(self, validated_data): """Create and return a new `TrashCan` instance, given the validated data.""" <|body_0|> def update(self, instance, validated_data): """Update and return an existing `TrashCan` instance, given the validated data.""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TrashCanSerializer: def create(self, validated_data): """Create and return a new `TrashCan` instance, given the validated data.""" head = validated_data['header'] load = validated_data['payload'] lat = load.get('latitude', DEFAULT_DEC) lng = load.get('longitude', DEFAUL...
the_stack_v2_python_sparse
processing/serializers.py
MiDro/trashViz
train
0
93de3155ff88eea19d520f81876ce8459587683f
[ "n = len(nums)\nif n == 0:\n return 0\n\ndef g(m):\n window_sz = m\n total = sum(nums[:m])\n if total >= s:\n return True\n for i in range(1, n - window_sz + 1):\n total = total - nums[i - 1] + nums[i + window_sz - 1]\n if total >= s:\n return True\n return False\nl...
<|body_start_0|> n = len(nums) if n == 0: return 0 def g(m): window_sz = m total = sum(nums[:m]) if total >= s: return True for i in range(1, n - window_sz + 1): total = total - nums[i - 1] + nums[i + wi...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: """Binary Search on Window Size, Time: O(nlogn), Space: O(1)""" <|body_0|> def minSubArrayLen(self, s: int, nums: List[int]) -> int: """Sliding Window, Time: O(n), Space: O(1)""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_071677
1,801
no_license
[ { "docstring": "Binary Search on Window Size, Time: O(nlogn), Space: O(1)", "name": "minSubArrayLen", "signature": "def minSubArrayLen(self, s: int, nums: List[int]) -> int" }, { "docstring": "Sliding Window, Time: O(n), Space: O(1)", "name": "minSubArrayLen", "signature": "def minSubArr...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minSubArrayLen(self, s: int, nums: List[int]) -> int: Binary Search on Window Size, Time: O(nlogn), Space: O(1) - def minSubArrayLen(self, s: int, nums: List[int]) -> int: Sl...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minSubArrayLen(self, s: int, nums: List[int]) -> int: Binary Search on Window Size, Time: O(nlogn), Space: O(1) - def minSubArrayLen(self, s: int, nums: List[int]) -> int: Sl...
72136e3487d239f5b37e2d6393e034262a6bf599
<|skeleton|> class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: """Binary Search on Window Size, Time: O(nlogn), Space: O(1)""" <|body_0|> def minSubArrayLen(self, s: int, nums: List[int]) -> int: """Sliding Window, Time: O(n), Space: O(1)""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: """Binary Search on Window Size, Time: O(nlogn), Space: O(1)""" n = len(nums) if n == 0: return 0 def g(m): window_sz = m total = sum(nums[:m]) if total >= s: ...
the_stack_v2_python_sparse
python/209-Minimum Size Subarray Sum.py
cwza/leetcode
train
0
1a22ba5e6fcfa02a21d5f2862e9b24eec49b1aed
[ "m = len(s)\nresults = []\nself.dfs(m, [], 0, s, results)\nreturn results", "if ptr == m:\n results.append(parts[:])\n return\nfor ptr2 in range(ptr + 1, m + 1):\n if self.palindrome(s, ptr, ptr2):\n print(ptr, ptr2, s[ptr:ptr2])\n parts.append(s[ptr:ptr2])\n self.dfs(m, parts, ptr2,...
<|body_start_0|> m = len(s) results = [] self.dfs(m, [], 0, s, results) return results <|end_body_0|> <|body_start_1|> if ptr == m: results.append(parts[:]) return for ptr2 in range(ptr + 1, m + 1): if self.palindrome(s, ptr, ptr2): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def partition(self, s): """:type s: str :rtype: List[List[str]]""" <|body_0|> def dfs(self, m, parts, ptr, s, results): """parts: list of substrings of s ptr: starting index for next palindrome""" <|body_1|> def palindrome(self, s, start, end):...
stack_v2_sparse_classes_75kplus_train_071678
1,254
no_license
[ { "docstring": ":type s: str :rtype: List[List[str]]", "name": "partition", "signature": "def partition(self, s)" }, { "docstring": "parts: list of substrings of s ptr: starting index for next palindrome", "name": "dfs", "signature": "def dfs(self, m, parts, ptr, s, results)" }, { ...
3
stack_v2_sparse_classes_30k_test_000594
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def partition(self, s): :type s: str :rtype: List[List[str]] - def dfs(self, m, parts, ptr, s, results): parts: list of substrings of s ptr: starting index for next palindrome - ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def partition(self, s): :type s: str :rtype: List[List[str]] - def dfs(self, m, parts, ptr, s, results): parts: list of substrings of s ptr: starting index for next palindrome - ...
e00cf94c5b86c8cca27e3bee69ad21e727b7679b
<|skeleton|> class Solution: def partition(self, s): """:type s: str :rtype: List[List[str]]""" <|body_0|> def dfs(self, m, parts, ptr, s, results): """parts: list of substrings of s ptr: starting index for next palindrome""" <|body_1|> def palindrome(self, s, start, end):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def partition(self, s): """:type s: str :rtype: List[List[str]]""" m = len(s) results = [] self.dfs(m, [], 0, s, results) return results def dfs(self, m, parts, ptr, s, results): """parts: list of substrings of s ptr: starting index for next palin...
the_stack_v2_python_sparse
backtracking/prob131.py
binchen15/leet-python
train
1
879a2da3c2e64022ecd12cfb052768fb1eda012a
[ "kwargs = locals().copy()\nself._is_ray_client = ray.util.client.ray.is_connected()\nif _tuner_internal:\n if not self._is_ray_client:\n self._local_tuner = kwargs[_TUNER_INTERNAL]\n else:\n self._remote_tuner = kwargs[_TUNER_INTERNAL]\nelse:\n kwargs.pop(_TUNER_INTERNAL, None)\n kwargs.po...
<|body_start_0|> kwargs = locals().copy() self._is_ray_client = ray.util.client.ray.is_connected() if _tuner_internal: if not self._is_ray_client: self._local_tuner = kwargs[_TUNER_INTERNAL] else: self._remote_tuner = kwargs[_TUNER_INTERNAL...
Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. Args: trainable: The trainable to be tuned. param_space: Search space of the tuning job. One thing to note is that both preprocessor and dataset can be tuned here. tune_config: Tuning algorithm specific configs. Refer to ray.tune.tune_c...
Tuner
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tuner: """Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. Args: trainable: The trainable to be tuned. param_space: Search space of the tuning job. One thing to note is that both preprocessor and dataset can be tuned here. tune_config: Tuning algorithm specific ...
stack_v2_sparse_classes_75kplus_train_071679
7,825
permissive
[ { "docstring": "Configure and construct a tune run.", "name": "__init__", "signature": "def __init__(self, trainable: Optional[Union[str, Callable, Type[Trainable], Trainer]]=None, param_space: Optional[Dict[str, Any]]=None, tune_config: Optional[TuneConfig]=None, run_config: Optional[RunConfig]=None, _...
3
null
Implement the Python class `Tuner` described below. Class description: Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. Args: trainable: The trainable to be tuned. param_space: Search space of the tuning job. One thing to note is that both preprocessor and dataset can be tuned here. ...
Implement the Python class `Tuner` described below. Class description: Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. Args: trainable: The trainable to be tuned. param_space: Search space of the tuning job. One thing to note is that both preprocessor and dataset can be tuned here. ...
918d3601c6519d333f10910dc75eb549cbb82afa
<|skeleton|> class Tuner: """Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. Args: trainable: The trainable to be tuned. param_space: Search space of the tuning job. One thing to note is that both preprocessor and dataset can be tuned here. tune_config: Tuning algorithm specific ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Tuner: """Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. Args: trainable: The trainable to be tuned. param_space: Search space of the tuning job. One thing to note is that both preprocessor and dataset can be tuned here. tune_config: Tuning algorithm specific configs. Refe...
the_stack_v2_python_sparse
python/ray/tune/tuner.py
pdames/ray
train
1
83d1a74a776e03ecc4f71603960235fbd8a9f7c0
[ "self.ctx = TritonContext()\nself.ctx.setArchitecture(ARCH.X86_64)\ninst = Instruction()\ninst.setOpcode(b'd\\x8b\\x04%\\x98\\xdf\\xff\\xff')\ninst.setAddress(4194304)\nself.ctx.setConcreteRegisterValue(self.ctx.registers.fs, 140736859911936)\nself.ctx.processing(inst)\nself.assertTrue(inst.getLoadAccess())\nload, ...
<|body_start_0|> self.ctx = TritonContext() self.ctx.setArchitecture(ARCH.X86_64) inst = Instruction() inst.setOpcode(b'd\x8b\x04%\x98\xdf\xff\xff') inst.setAddress(4194304) self.ctx.setConcreteRegisterValue(self.ctx.registers.fs, 140736859911936) self.ctx.process...
Testing the LOAD access semantics.
TestLoadAccess
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestLoadAccess: """Testing the LOAD access semantics.""" def test_load_immediate_fs(self): """Check load from fs segment with immediate.""" <|body_0|> def test_load_indirect_fs(self): """Check load from fs with indirect address.""" <|body_1|> def tes...
stack_v2_sparse_classes_75kplus_train_071680
14,500
permissive
[ { "docstring": "Check load from fs segment with immediate.", "name": "test_load_immediate_fs", "signature": "def test_load_immediate_fs(self)" }, { "docstring": "Check load from fs with indirect address.", "name": "test_load_indirect_fs", "signature": "def test_load_indirect_fs(self)" ...
3
null
Implement the Python class `TestLoadAccess` described below. Class description: Testing the LOAD access semantics. Method signatures and docstrings: - def test_load_immediate_fs(self): Check load from fs segment with immediate. - def test_load_indirect_fs(self): Check load from fs with indirect address. - def test_lo...
Implement the Python class `TestLoadAccess` described below. Class description: Testing the LOAD access semantics. Method signatures and docstrings: - def test_load_immediate_fs(self): Check load from fs segment with immediate. - def test_load_indirect_fs(self): Check load from fs with indirect address. - def test_lo...
a61651ce331ac53ec09e1d8fef5eab744e98c9de
<|skeleton|> class TestLoadAccess: """Testing the LOAD access semantics.""" def test_load_immediate_fs(self): """Check load from fs segment with immediate.""" <|body_0|> def test_load_indirect_fs(self): """Check load from fs with indirect address.""" <|body_1|> def tes...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestLoadAccess: """Testing the LOAD access semantics.""" def test_load_immediate_fs(self): """Check load from fs segment with immediate.""" self.ctx = TritonContext() self.ctx.setArchitecture(ARCH.X86_64) inst = Instruction() inst.setOpcode(b'd\x8b\x04%\x98\xdf\xff...
the_stack_v2_python_sparse
src/testers/unittests/test_instruction.py
JonathanSalwan/Triton
train
3,163
a3e25659835662ba1fed59c182eb3e36f8a59f54
[ "retrieved_alignments = alignment_records.read_all(filter={'collab_id': collab_id, 'project_id': project_id})\nif retrieved_alignments:\n success_payload = payload_formatter.construct_success_payload(status=200, method='alignments.get', params=request.view_args, data=retrieved_alignments)\n logging.info(f\"Co...
<|body_start_0|> retrieved_alignments = alignment_records.read_all(filter={'collab_id': collab_id, 'project_id': project_id}) if retrieved_alignments: success_payload = payload_formatter.construct_success_payload(status=200, method='alignments.get', params=request.view_args, data=retrieved_a...
Using registered data tags, poll for metadata from worker nodes for multiple feature alignment to be used subsequently for FL training.
Alignments
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Alignments: """Using registered data tags, poll for metadata from worker nodes for multiple feature alignment to be used subsequently for FL training.""" def get(self, collab_id, project_id): """Retrieves all alignments for all registered data under a project""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_071681
12,411
permissive
[ { "docstring": "Retrieves all alignments for all registered data under a project", "name": "get", "signature": "def get(self, collab_id, project_id)" }, { "docstring": "Searches for all registered participant under project, and uses their registered data tags to trigger the RPC for polling parti...
2
stack_v2_sparse_classes_30k_train_049146
Implement the Python class `Alignments` described below. Class description: Using registered data tags, poll for metadata from worker nodes for multiple feature alignment to be used subsequently for FL training. Method signatures and docstrings: - def get(self, collab_id, project_id): Retrieves all alignments for all...
Implement the Python class `Alignments` described below. Class description: Using registered data tags, poll for metadata from worker nodes for multiple feature alignment to be used subsequently for FL training. Method signatures and docstrings: - def get(self, collab_id, project_id): Retrieves all alignments for all...
d7b45216e5d1854fe65213f06ae3f3bb6d99cab0
<|skeleton|> class Alignments: """Using registered data tags, poll for metadata from worker nodes for multiple feature alignment to be used subsequently for FL training.""" def get(self, collab_id, project_id): """Retrieves all alignments for all registered data under a project""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Alignments: """Using registered data tags, poll for metadata from worker nodes for multiple feature alignment to be used subsequently for FL training.""" def get(self, collab_id, project_id): """Retrieves all alignments for all registered data under a project""" retrieved_alignments = ali...
the_stack_v2_python_sparse
rest_rpc/training/alignments.py
markchc101/synergos_rest
train
0
7d4c7e388248769189a62cb934f9506a6d162cd7
[ "key = AmazonS3.getSettingWithTag('key_secret')\ncanonicalData = OrderedDict()\nfor k in sorted(data.keys()):\n canonicalData[urllib.quote(k, '~')] = urllib.quote(data[k], '~')\ncanonicalString = '&'.join(('{0}={1}'.format(k, v) for k, v in canonicalData.iteritems()))\nplaintext = '{0}\\n{1}\\n{2}\\n{3}'.format(...
<|body_start_0|> key = AmazonS3.getSettingWithTag('key_secret') canonicalData = OrderedDict() for k in sorted(data.keys()): canonicalData[urllib.quote(k, '~')] = urllib.quote(data[k], '~') canonicalString = '&'.join(('{0}={1}'.format(k, v) for k, v in canonicalData.iteritems(...
Helper method mix-in for Amazon Payments
AmazonFPS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AmazonFPS: """Helper method mix-in for Amazon Payments""" def generateSignature(self, httpVerb, host, uri, data): """Generate an Amazon FPS signature for an API request or button form. More information can be found at the following URL: http://docs.amazonwebservices.com/AmazonSimpleP...
stack_v2_sparse_classes_75kplus_train_071682
3,730
no_license
[ { "docstring": "Generate an Amazon FPS signature for an API request or button form. More information can be found at the following URL: http://docs.amazonwebservices.com/AmazonSimplePay/latest/ASPAdvancedUserGuide/Sig2CreateSignature.html", "name": "generateSignature", "signature": "def generateSignatur...
2
null
Implement the Python class `AmazonFPS` described below. Class description: Helper method mix-in for Amazon Payments Method signatures and docstrings: - def generateSignature(self, httpVerb, host, uri, data): Generate an Amazon FPS signature for an API request or button form. More information can be found at the follo...
Implement the Python class `AmazonFPS` described below. Class description: Helper method mix-in for Amazon Payments Method signatures and docstrings: - def generateSignature(self, httpVerb, host, uri, data): Generate an Amazon FPS signature for an API request or button form. More information can be found at the follo...
7a26153aec9d5cea3b864869634a306f86933b59
<|skeleton|> class AmazonFPS: """Helper method mix-in for Amazon Payments""" def generateSignature(self, httpVerb, host, uri, data): """Generate an Amazon FPS signature for an API request or button form. More information can be found at the following URL: http://docs.amazonwebservices.com/AmazonSimpleP...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AmazonFPS: """Helper method mix-in for Amazon Payments""" def generateSignature(self, httpVerb, host, uri, data): """Generate an Amazon FPS signature for an API request or button form. More information can be found at the following URL: http://docs.amazonwebservices.com/AmazonSimplePay/latest/ASP...
the_stack_v2_python_sparse
controllers/amazonaws.py
wurkhappy/wurkhappy
train
0
d51d5879cdd41d248855707242104df941ad7410
[ "self.data_type = data_type\nself.start_date = start_date\nself.end_date = end_date\nself.interval = interval\nself.possible_intervals = ('1min', '5min', '15min', '30min', '60min')\nself.possible_data_types = ('daily', 'daily_adjusted', 'intraday', 'monthly', 'monthly_adjusted', 'weekly', 'weekly_adjusted')\nif int...
<|body_start_0|> self.data_type = data_type self.start_date = start_date self.end_date = end_date self.interval = interval self.possible_intervals = ('1min', '5min', '15min', '30min', '60min') self.possible_data_types = ('daily', 'daily_adjusted', 'intraday', 'monthly', '...
Data Fetcher for retrieving stock data
DataFetcher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataFetcher: """Data Fetcher for retrieving stock data""" def __init__(self, ap_paramList, data_type, start_date=None, end_date=None, interval=None): """@param ap_paramList[stock_symbol_list]: AutoList of stock symbols @param data_type: Type of data to retrieve (daily, daily_adjusted...
stack_v2_sparse_classes_75kplus_train_071683
5,224
permissive
[ { "docstring": "@param ap_paramList[stock_symbol_list]: AutoList of stock symbols @param data_type: Type of data to retrieve (daily, daily_adjusted, intraday, monthly, monthly_adjusted, weekly, weekly_adjusted) @param start_date: Starting date @param end_date: Ending date @param interval: Interval for intraday ...
2
stack_v2_sparse_classes_30k_train_003238
Implement the Python class `DataFetcher` described below. Class description: Data Fetcher for retrieving stock data Method signatures and docstrings: - def __init__(self, ap_paramList, data_type, start_date=None, end_date=None, interval=None): @param ap_paramList[stock_symbol_list]: AutoList of stock symbols @param d...
Implement the Python class `DataFetcher` described below. Class description: Data Fetcher for retrieving stock data Method signatures and docstrings: - def __init__(self, ap_paramList, data_type, start_date=None, end_date=None, interval=None): @param ap_paramList[stock_symbol_list]: AutoList of stock symbols @param d...
935bfd54149abd9542fe38e77b7eabab48b1c3a1
<|skeleton|> class DataFetcher: """Data Fetcher for retrieving stock data""" def __init__(self, ap_paramList, data_type, start_date=None, end_date=None, interval=None): """@param ap_paramList[stock_symbol_list]: AutoList of stock symbols @param data_type: Type of data to retrieve (daily, daily_adjusted...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataFetcher: """Data Fetcher for retrieving stock data""" def __init__(self, ap_paramList, data_type, start_date=None, end_date=None, interval=None): """@param ap_paramList[stock_symbol_list]: AutoList of stock symbols @param data_type: Type of data to retrieve (daily, daily_adjusted, intraday, m...
the_stack_v2_python_sparse
skdaccess/finance/timeseries/stream.py
MITHaystack/scikit-dataaccess
train
41
30494a7b1a538396380a9897b4209b08a10edfaa
[ "try:\n ScfUser.objects.get(email=data)\nexcept:\n raise ParseError('User {} does not exist'.format(data))\nreturn data", "newPassword = data.get('newPassword')\nif newPassword and newPassword != data.get('newPasswordConfirm'):\n raise ParseError('newPassword did not match newPasswordConfirm')\nreturn da...
<|body_start_0|> try: ScfUser.objects.get(email=data) except: raise ParseError('User {} does not exist'.format(data)) return data <|end_body_0|> <|body_start_1|> newPassword = data.get('newPassword') if newPassword and newPassword != data.get('newPassword...
User reset password serializer
UserPasswordResetSerializer
[ "Apache-2.0", "GPL-3.0-only", "BSD-3-Clause", "AGPL-3.0-only", "GPL-1.0-or-later", "Python-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserPasswordResetSerializer: """User reset password serializer""" def validate_email(self, data): """check email is exist or not""" <|body_0|> def validate(self, data): """validate password""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: ...
stack_v2_sparse_classes_75kplus_train_071684
4,134
permissive
[ { "docstring": "check email is exist or not", "name": "validate_email", "signature": "def validate_email(self, data)" }, { "docstring": "validate password", "name": "validate", "signature": "def validate(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_037070
Implement the Python class `UserPasswordResetSerializer` described below. Class description: User reset password serializer Method signatures and docstrings: - def validate_email(self, data): check email is exist or not - def validate(self, data): validate password
Implement the Python class `UserPasswordResetSerializer` described below. Class description: User reset password serializer Method signatures and docstrings: - def validate_email(self, data): check email is exist or not - def validate(self, data): validate password <|skeleton|> class UserPasswordResetSerializer: ...
4df3f46e35eb8fcab796be27fc1cc7fa7ed561f3
<|skeleton|> class UserPasswordResetSerializer: """User reset password serializer""" def validate_email(self, data): """check email is exist or not""" <|body_0|> def validate(self, data): """validate password""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserPasswordResetSerializer: """User reset password serializer""" def validate_email(self, data): """check email is exist or not""" try: ScfUser.objects.get(email=data) except: raise ParseError('User {} does not exist'.format(data)) return data ...
the_stack_v2_python_sparse
SCRM/ums/serializers.py
aricent/secure-cloud-native-fabric
train
2
06b212b5d8632ba531937fd6278e238e153628eb
[ "self.log('logging日志信息:输入账号和密码')\nself.ITest.Itest_login_liucheng(self.Readusername(1), self.Readpassword(1))\nself.log('logging日志信息:对登录结果进行验证')\nself.assertEqual(self.ITest.login_success(), self.Readresult(1), '测试用例成功')\nself.log('logging日志信息:对登录成功进行截图')\ninsert_image(self.driver, 'success_info.png')", "self.log...
<|body_start_0|> self.log('logging日志信息:输入账号和密码') self.ITest.Itest_login_liucheng(self.Readusername(1), self.Readpassword(1)) self.log('logging日志信息:对登录结果进行验证') self.assertEqual(self.ITest.login_success(), self.Readresult(1), '测试用例成功') self.log('logging日志信息:对登录成功进行截图') inse...
Itest_Login
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Itest_Login: def test_Itest_success(self): """验证登录成功:账号和密码输入正确""" <|body_0|> def test_Itest_error2(self): """验证登录失败:账号正确密码为空""" <|body_1|> def test_Itest_error3(self): """验证登录失败:账号为空密码正确""" <|body_2|> def test_Itest_error4(self): ...
stack_v2_sparse_classes_75kplus_train_071685
3,295
no_license
[ { "docstring": "验证登录成功:账号和密码输入正确", "name": "test_Itest_success", "signature": "def test_Itest_success(self)" }, { "docstring": "验证登录失败:账号正确密码为空", "name": "test_Itest_error2", "signature": "def test_Itest_error2(self)" }, { "docstring": "验证登录失败:账号为空密码正确", "name": "test_Itest_e...
5
null
Implement the Python class `Itest_Login` described below. Class description: Implement the Itest_Login class. Method signatures and docstrings: - def test_Itest_success(self): 验证登录成功:账号和密码输入正确 - def test_Itest_error2(self): 验证登录失败:账号正确密码为空 - def test_Itest_error3(self): 验证登录失败:账号为空密码正确 - def test_Itest_error4(self): ...
Implement the Python class `Itest_Login` described below. Class description: Implement the Itest_Login class. Method signatures and docstrings: - def test_Itest_success(self): 验证登录成功:账号和密码输入正确 - def test_Itest_error2(self): 验证登录失败:账号正确密码为空 - def test_Itest_error3(self): 验证登录失败:账号为空密码正确 - def test_Itest_error4(self): ...
3b0a3232e3797190a6b90c1d7fa58bec63bdbb27
<|skeleton|> class Itest_Login: def test_Itest_success(self): """验证登录成功:账号和密码输入正确""" <|body_0|> def test_Itest_error2(self): """验证登录失败:账号正确密码为空""" <|body_1|> def test_Itest_error3(self): """验证登录失败:账号为空密码正确""" <|body_2|> def test_Itest_error4(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Itest_Login: def test_Itest_success(self): """验证登录成功:账号和密码输入正确""" self.log('logging日志信息:输入账号和密码') self.ITest.Itest_login_liucheng(self.Readusername(1), self.Readpassword(1)) self.log('logging日志信息:对登录结果进行验证') self.assertEqual(self.ITest.login_success(), self.Readresult(1...
the_stack_v2_python_sparse
testcase/Itest_login.py
kuangtao94/Appium
train
0
8409d138c9e86fa71bdf4bd6bb2bb38f844eda1f
[ "self._is_transient = is_transient\nself._max_attempts = max_attempts\nself._sleep = sleep", "failures = 0\nwhile True:\n try:\n return callback()\n except Exception as e:\n failures += 1\n if failures == self._max_attempts or not self._is_transient(e):\n raise\n tf.lo...
<|body_start_0|> self._is_transient = is_transient self._max_attempts = max_attempts self._sleep = sleep <|end_body_0|> <|body_start_1|> failures = 0 while True: try: return callback() except Exception as e: failures += 1 ...
Helper class for retrying things with exponential back-off.
Retrier
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Retrier: """Helper class for retrying things with exponential back-off.""" def __init__(self, is_transient, max_attempts=8, sleep=time.sleep): """Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_071686
16,613
permissive
[ { "docstring": "Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None", "name": "__init__", "signature": "def __init__(self, is_transient, max_attempts=8, sleep=time.sleep)" }, { "docstring": "Invokes callback, retrying on transient ex...
2
stack_v2_sparse_classes_30k_train_033631
Implement the Python class `Retrier` described below. Class description: Helper class for retrying things with exponential back-off. Method signatures and docstrings: - def __init__(self, is_transient, max_attempts=8, sleep=time.sleep): Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts:...
Implement the Python class `Retrier` described below. Class description: Helper class for retrying things with exponential back-off. Method signatures and docstrings: - def __init__(self, is_transient, max_attempts=8, sleep=time.sleep): Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts:...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class Retrier: """Helper class for retrying things with exponential back-off.""" def __init__(self, is_transient, max_attempts=8, sleep=time.sleep): """Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Retrier: """Helper class for retrying things with exponential back-off.""" def __init__(self, is_transient, max_attempts=8, sleep=time.sleep): """Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None""" self._is_transient = is_t...
the_stack_v2_python_sparse
Keras_tensorflow_nightly/source2.7/tensorboard/util.py
ryfeus/lambda-packs
train
1,283
09f752e069ef17491d8c03316db1bc01555285f7
[ "super().__init__()\nself.conv = nn.Conv2d(c_in, c_out, kernel_size=K, padding=K // 2, stride=1)\nself.dims = (c_out, b)\nM = np.prod(self.dims)\nself.out_layer = nn.Linear(M, n_neurons)\nif filters is not None:\n self.conv.weight = nn.Parameter(filters)\n self.conv.bias = nn.Parameter(torch.zeros((c_out,), d...
<|body_start_0|> super().__init__() self.conv = nn.Conv2d(c_in, c_out, kernel_size=K, padding=K // 2, stride=1) self.dims = (c_out, b) M = np.prod(self.dims) self.out_layer = nn.Linear(M, n_neurons) if filters is not None: self.conv.weight = nn.Parameter(filte...
Deep network with one convolutional layer + one fully connected layer Attributes: conv (nn.Conv1d): convolutional layer dims (tuple): shape of convolutional layer output out_layer (nn.Linear): linear layer
ConvFC
[ "CC-BY-4.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvFC: """Deep network with one convolutional layer + one fully connected layer Attributes: conv (nn.Conv1d): convolutional layer dims (tuple): shape of convolutional layer output out_layer (nn.Linear): linear layer""" def __init__(self, n_neurons, c_in=1, c_out=6, K=7, b=12 * 16, filters=N...
stack_v2_sparse_classes_75kplus_train_071687
2,340
permissive
[ { "docstring": "initialize layer Args: c_in: number of input stimulus channels c_out: number of convolutional channels K: size of each convolutional filter h: number of stimulus bins, n_bins", "name": "__init__", "signature": "def __init__(self, n_neurons, c_in=1, c_out=6, K=7, b=12 * 16, filters=None)"...
2
stack_v2_sparse_classes_30k_train_050577
Implement the Python class `ConvFC` described below. Class description: Deep network with one convolutional layer + one fully connected layer Attributes: conv (nn.Conv1d): convolutional layer dims (tuple): shape of convolutional layer output out_layer (nn.Linear): linear layer Method signatures and docstrings: - def ...
Implement the Python class `ConvFC` described below. Class description: Deep network with one convolutional layer + one fully connected layer Attributes: conv (nn.Conv1d): convolutional layer dims (tuple): shape of convolutional layer output out_layer (nn.Linear): linear layer Method signatures and docstrings: - def ...
3d638d00f02d9fd269fa2aff7d062558afdcb126
<|skeleton|> class ConvFC: """Deep network with one convolutional layer + one fully connected layer Attributes: conv (nn.Conv1d): convolutional layer dims (tuple): shape of convolutional layer output out_layer (nn.Linear): linear layer""" def __init__(self, n_neurons, c_in=1, c_out=6, K=7, b=12 * 16, filters=N...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConvFC: """Deep network with one convolutional layer + one fully connected layer Attributes: conv (nn.Conv1d): convolutional layer dims (tuple): shape of convolutional layer output out_layer (nn.Linear): linear layer""" def __init__(self, n_neurons, c_in=1, c_out=6, K=7, b=12 * 16, filters=None): ...
the_stack_v2_python_sparse
tutorials/W1D5_DeepLearning/solutions/W1D5_Tutorial4_Solution_5dffefa9.py
NeuromatchAcademy/course-content
train
2,678
46347a35f050d9aa088f1572b9c58eed0c0bd389
[ "initial = super().get_initial()\nfor req in POSSIBLE_REQS:\n try:\n reqSetting = RequiredFieldSetting.objects.get(name=req[0])\n initial[req[0]] = reqSetting.required\n except:\n pass\nreturn initial", "for req in POSSIBLE_REQS:\n try:\n reqSetting = RequiredFieldSetting.obje...
<|body_start_0|> initial = super().get_initial() for req in POSSIBLE_REQS: try: reqSetting = RequiredFieldSetting.objects.get(name=req[0]) initial[req[0]] = reqSetting.required except: pass return initial <|end_body_0|> <|b...
View to change what is required to submit a form
ChangeRequiredFields
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChangeRequiredFields: """View to change what is required to submit a form""" def get_initial(self): """Initializes form with current settings""" <|body_0|> def form_valid(self, form): """When form is valid, updates the settings for required fields to submit repor...
stack_v2_sparse_classes_75kplus_train_071688
25,501
no_license
[ { "docstring": "Initializes form with current settings", "name": "get_initial", "signature": "def get_initial(self)" }, { "docstring": "When form is valid, updates the settings for required fields to submit report", "name": "form_valid", "signature": "def form_valid(self, form)" } ]
2
stack_v2_sparse_classes_30k_train_014860
Implement the Python class `ChangeRequiredFields` described below. Class description: View to change what is required to submit a form Method signatures and docstrings: - def get_initial(self): Initializes form with current settings - def form_valid(self, form): When form is valid, updates the settings for required f...
Implement the Python class `ChangeRequiredFields` described below. Class description: View to change what is required to submit a form Method signatures and docstrings: - def get_initial(self): Initializes form with current settings - def form_valid(self, form): When form is valid, updates the settings for required f...
472a6fd487811002a60a7812ae2eef941e7182cc
<|skeleton|> class ChangeRequiredFields: """View to change what is required to submit a form""" def get_initial(self): """Initializes form with current settings""" <|body_0|> def form_valid(self, form): """When form is valid, updates the settings for required fields to submit repor...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChangeRequiredFields: """View to change what is required to submit a form""" def get_initial(self): """Initializes form with current settings""" initial = super().get_initial() for req in POSSIBLE_REQS: try: reqSetting = RequiredFieldSetting.objects.get...
the_stack_v2_python_sparse
AACForm/makeReports/views/AAC/aac_admin_views.py
jdboyd-github/AAC-Capstone
train
0
7323128f5d80a2a351d8506f7233b21cecb33fd2
[ "self.user_id = Option('user-id', 'The user id used when making authenticated requests to the QuantConnect API.', True, credentials_storage)\nself.api_token = Option('api-token', 'The API token used when making authenticated requests to the QuantConnect API.', True, credentials_storage)\nself.default_language = Cho...
<|body_start_0|> self.user_id = Option('user-id', 'The user id used when making authenticated requests to the QuantConnect API.', True, credentials_storage) self.api_token = Option('api-token', 'The API token used when making authenticated requests to the QuantConnect API.', True, credentials_storage) ...
The CLIConfigManager class contains all configurable CLI options.
CLIConfigManager
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CLIConfigManager: """The CLIConfigManager class contains all configurable CLI options.""" def __init__(self, general_storage: Storage, credentials_storage: Storage) -> None: """Creates a new CLIConfigManager instance. :param general_storage: the Storage instance for general, non-sens...
stack_v2_sparse_classes_75kplus_train_071689
1,980
permissive
[ { "docstring": "Creates a new CLIConfigManager instance. :param general_storage: the Storage instance for general, non-sensitive options :param credentials_storage: the Storage instance for credentials", "name": "__init__", "signature": "def __init__(self, general_storage: Storage, credentials_storage: ...
2
stack_v2_sparse_classes_30k_train_049987
Implement the Python class `CLIConfigManager` described below. Class description: The CLIConfigManager class contains all configurable CLI options. Method signatures and docstrings: - def __init__(self, general_storage: Storage, credentials_storage: Storage) -> None: Creates a new CLIConfigManager instance. :param ge...
Implement the Python class `CLIConfigManager` described below. Class description: The CLIConfigManager class contains all configurable CLI options. Method signatures and docstrings: - def __init__(self, general_storage: Storage, credentials_storage: Storage) -> None: Creates a new CLIConfigManager instance. :param ge...
88a191afadf7bfe766665fa67c552390cb2e3951
<|skeleton|> class CLIConfigManager: """The CLIConfigManager class contains all configurable CLI options.""" def __init__(self, general_storage: Storage, credentials_storage: Storage) -> None: """Creates a new CLIConfigManager instance. :param general_storage: the Storage instance for general, non-sens...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CLIConfigManager: """The CLIConfigManager class contains all configurable CLI options.""" def __init__(self, general_storage: Storage, credentials_storage: Storage) -> None: """Creates a new CLIConfigManager instance. :param general_storage: the Storage instance for general, non-sensitive options...
the_stack_v2_python_sparse
lean/components/cli_config_manager.py
valmac/lean-cli
train
0
c69c633ed0d4cc30bc8b89190e2c5e9ed0f706b4
[ "self.rtol = rtol\nself.atol = atol\nsuper(WeightedGraphMatcher, self).__init__(G1, G2)", "G1_adj = self.G1.adj\nG2_adj = self.G2.adj\ncore_1 = self.core_1\nrtol, atol = (self.rtol, self.atol)\nfor neighbor in G1_adj[G1_node]:\n if neighbor is G1_node:\n if not close(G1_adj[G1_node][G1_node].get('weight...
<|body_start_0|> self.rtol = rtol self.atol = atol super(WeightedGraphMatcher, self).__init__(G1, G2) <|end_body_0|> <|body_start_1|> G1_adj = self.G1.adj G2_adj = self.G2.adj core_1 = self.core_1 rtol, atol = (self.rtol, self.atol) for neighbor in G1_adj...
Implementation of VF2 algorithm for undirected, weighted graphs.
WeightedGraphMatcher
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeightedGraphMatcher: """Implementation of VF2 algorithm for undirected, weighted graphs.""" def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): """Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, opti...
stack_v2_sparse_classes_75kplus_train_071690
9,804
permissive
[ { "docstring": "Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, optional The relative tolerance used to compare weights. atol : float, optional The absolute tolerance used to compare weights.", "name": "__init__", "signa...
2
stack_v2_sparse_classes_30k_train_042065
Implement the Python class `WeightedGraphMatcher` described below. Class description: Implementation of VF2 algorithm for undirected, weighted graphs. Method signatures and docstrings: - def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instan...
Implement the Python class `WeightedGraphMatcher` described below. Class description: Implementation of VF2 algorithm for undirected, weighted graphs. Method signatures and docstrings: - def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instan...
de0cdb26248f6d0d8bea594124c1dd7a155d406d
<|skeleton|> class WeightedGraphMatcher: """Implementation of VF2 algorithm for undirected, weighted graphs.""" def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): """Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, opti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WeightedGraphMatcher: """Implementation of VF2 algorithm for undirected, weighted graphs.""" def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): """Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, optional The rela...
the_stack_v2_python_sparse
Source/lib/CrossPlatform/networkx/algorithms/isomorphism/vf2weighted.py
JaneliaSciComp/Neuroptikon
train
9
232df1b07995329430a3df7898d5e762ea03eb3c
[ "try:\n state = self.add_model_schema.load(request.json)\n key = CreateExplorePermalinkCommand(state=state).run()\n http_origin = request.headers.environ.get('HTTP_ORIGIN')\n url = f'{http_origin}/superset/explore/p/{key}/'\n return self.response(201, key=key, url=url)\nexcept ValidationError as ex:\...
<|body_start_0|> try: state = self.add_model_schema.load(request.json) key = CreateExplorePermalinkCommand(state=state).run() http_origin = request.headers.environ.get('HTTP_ORIGIN') url = f'{http_origin}/superset/explore/p/{key}/' return self.response...
ExplorePermalinkRestApi
[ "Apache-2.0", "OFL-1.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExplorePermalinkRestApi: def post(self) -> Response: """Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: ...
stack_v2_sparse_classes_75kplus_train_071691
6,288
permissive
[ { "docstring": "Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: The permanent link was stored successfully. content: application...
2
stack_v2_sparse_classes_30k_train_005226
Implement the Python class `ExplorePermalinkRestApi` described below. Class description: Implement the ExplorePermalinkRestApi class. Method signatures and docstrings: - def post(self) -> Response: Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content:...
Implement the Python class `ExplorePermalinkRestApi` described below. Class description: Implement the ExplorePermalinkRestApi class. Method signatures and docstrings: - def post(self) -> Response: Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content:...
0945d4a2f46667aebb9b93d0d7685215627ad237
<|skeleton|> class ExplorePermalinkRestApi: def post(self) -> Response: """Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExplorePermalinkRestApi: def post(self) -> Response: """Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: The permanent ...
the_stack_v2_python_sparse
superset/explore/permalink/api.py
apache-superset/incubator-superset
train
21
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_75kplus_train_071692
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_031958
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_75kplus
data/stack_v2_sparse_classes_30k
75,829
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
226e75a07eddb8b4bec9ba3492deea18b7e3179e
[ "choice = input('Choose either (A.)Rock, (B.)Paper, or (C.)Scissors:')\nif choice == 'a' or choice == 'A':\n user_move = 'Rock'\nelif choice == 'b' or choice == 'B':\n user_move = 'Paper'\nelif choice == 'c' or choice == 'C':\n user_move = 'Scissors'\nelse:\n print('Invalid selection, please select eith...
<|body_start_0|> choice = input('Choose either (A.)Rock, (B.)Paper, or (C.)Scissors:') if choice == 'a' or choice == 'A': user_move = 'Rock' elif choice == 'b' or choice == 'B': user_move = 'Paper' elif choice == 'c' or choice == 'C': user_move = 'Scis...
RPC
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RPC: def start(self): """Description: This method takes user input and has error checking. Args: None. Returns: user_move""" <|body_0|> def compare(self, user_move): """Description: This method prints the choice of user and computer. It also calculates who wins each ...
stack_v2_sparse_classes_75kplus_train_071693
2,496
permissive
[ { "docstring": "Description: This method takes user input and has error checking. Args: None. Returns: user_move", "name": "start", "signature": "def start(self)" }, { "docstring": "Description: This method prints the choice of user and computer. It also calculates who wins each hand. Args: user...
2
stack_v2_sparse_classes_30k_train_031502
Implement the Python class `RPC` described below. Class description: Implement the RPC class. Method signatures and docstrings: - def start(self): Description: This method takes user input and has error checking. Args: None. Returns: user_move - def compare(self, user_move): Description: This method prints the choice...
Implement the Python class `RPC` described below. Class description: Implement the RPC class. Method signatures and docstrings: - def start(self): Description: This method takes user input and has error checking. Args: None. Returns: user_move - def compare(self, user_move): Description: This method prints the choice...
df46c8bb8e4c8ba6d34898cd13cdb0348eb4e74d
<|skeleton|> class RPC: def start(self): """Description: This method takes user input and has error checking. Args: None. Returns: user_move""" <|body_0|> def compare(self, user_move): """Description: This method prints the choice of user and computer. It also calculates who wins each ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RPC: def start(self): """Description: This method takes user input and has error checking. Args: None. Returns: user_move""" choice = input('Choose either (A.)Rock, (B.)Paper, or (C.)Scissors:') if choice == 'a' or choice == 'A': user_move = 'Rock' elif choice == 'b...
the_stack_v2_python_sparse
rock_paper_scissors.py
tangowithfoxtrot/beginner_project_solutions
train
0
898844c574a735ddd0b2c73f92daf849c700c4e1
[ "adm = ApplikationsAdministration()\nverbund = adm.get_anwenderverbund_by_id(id)\nif verbund is not None:\n mitglieder_id = adm.mitglieder_zum_anwenderverbund_ausgeben(verbund)\n benutze_objekte = []\n for i in mitglieder_id:\n benutze_objekt = adm.get_benutzer_by_id(i)\n benutze_objekte.appe...
<|body_start_0|> adm = ApplikationsAdministration() verbund = adm.get_anwenderverbund_by_id(id) if verbund is not None: mitglieder_id = adm.mitglieder_zum_anwenderverbund_ausgeben(verbund) benutze_objekte = [] for i in mitglieder_id: benutze_ob...
AnwenderverbundRelatedBenutzerOperations
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnwenderverbundRelatedBenutzerOperations: def get(self, id): """Auslesen aller Mitglieder in einem durch Id definierten Anwenderverbund""" <|body_0|> def post(self, id): """Hinzufügen eines Benutzers in einen Anwenderverbund""" <|body_1|> def delete(self...
stack_v2_sparse_classes_75kplus_train_071694
23,456
no_license
[ { "docstring": "Auslesen aller Mitglieder in einem durch Id definierten Anwenderverbund", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Hinzufügen eines Benutzers in einen Anwenderverbund", "name": "post", "signature": "def post(self, id)" }, { "docstring": "...
3
stack_v2_sparse_classes_30k_test_000608
Implement the Python class `AnwenderverbundRelatedBenutzerOperations` described below. Class description: Implement the AnwenderverbundRelatedBenutzerOperations class. Method signatures and docstrings: - def get(self, id): Auslesen aller Mitglieder in einem durch Id definierten Anwenderverbund - def post(self, id): H...
Implement the Python class `AnwenderverbundRelatedBenutzerOperations` described below. Class description: Implement the AnwenderverbundRelatedBenutzerOperations class. Method signatures and docstrings: - def get(self, id): Auslesen aller Mitglieder in einem durch Id definierten Anwenderverbund - def post(self, id): H...
d4a2b196f21a5379188cb78b31c59d69f739964f
<|skeleton|> class AnwenderverbundRelatedBenutzerOperations: def get(self, id): """Auslesen aller Mitglieder in einem durch Id definierten Anwenderverbund""" <|body_0|> def post(self, id): """Hinzufügen eines Benutzers in einen Anwenderverbund""" <|body_1|> def delete(self...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AnwenderverbundRelatedBenutzerOperations: def get(self, id): """Auslesen aller Mitglieder in einem durch Id definierten Anwenderverbund""" adm = ApplikationsAdministration() verbund = adm.get_anwenderverbund_by_id(id) if verbund is not None: mitglieder_id = adm.mitg...
the_stack_v2_python_sparse
src/main.py
SvenjaHolzinger/SoftwarePraktikum
train
0
23f2eab990678193820b6ab9c59e95a85d49fb65
[ "if id and id not in ['self', 'unreviewed']:\n try:\n video = Video.objects.get(uuid=id)\n except Video.DoesNotExist:\n return Response(build_resp(COMMON_URL_ERROR))\n serializer = VideoSerializer(video)\n return Response(build_resp(serializer.data))\nstatus = [VideoStatus.PENDING_APPROVAL...
<|body_start_0|> if id and id not in ['self', 'unreviewed']: try: video = Video.objects.get(uuid=id) except Video.DoesNotExist: return Response(build_resp(COMMON_URL_ERROR)) serializer = VideoSerializer(video) return Response(build_...
VideoView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VideoView: def get(self, request, id=None): """Get videos or single video information. list: return paged video entries with filters of request get params. filters: * author ( user id, special value: self, if null the api will return a list without self video. ) * query ( any text in glo...
stack_v2_sparse_classes_75kplus_train_071695
17,168
no_license
[ { "docstring": "Get videos or single video information. list: return paged video entries with filters of request get params. filters: * author ( user id, special value: self, if null the api will return a list without self video. ) * query ( any text in gloss label ) * categories ( comma separated numbers, cate...
2
stack_v2_sparse_classes_30k_train_045351
Implement the Python class `VideoView` described below. Class description: Implement the VideoView class. Method signatures and docstrings: - def get(self, request, id=None): Get videos or single video information. list: return paged video entries with filters of request get params. filters: * author ( user id, speci...
Implement the Python class `VideoView` described below. Class description: Implement the VideoView class. Method signatures and docstrings: - def get(self, request, id=None): Get videos or single video information. list: return paged video entries with filters of request get params. filters: * author ( user id, speci...
f127b4642115a25c3f27c8a75f73015bfbd9a21d
<|skeleton|> class VideoView: def get(self, request, id=None): """Get videos or single video information. list: return paged video entries with filters of request get params. filters: * author ( user id, special value: self, if null the api will return a list without self video. ) * query ( any text in glo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VideoView: def get(self, request, id=None): """Get videos or single video information. list: return paged video entries with filters of request get params. filters: * author ( user id, special value: self, if null the api will return a list without self video. ) * query ( any text in gloss label ) * c...
the_stack_v2_python_sparse
cslt/api_views.py
cslt-china/backend
train
0
ed41bfc5515008d62eee2b4e11ec55f39c8710c4
[ "query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nform = ClientForm()\nlist_client = None\nif query:\n list_client = Client.objects.filter(Q(name__icontains=query) | Q(phone__icontains=query) | Q(email__icontains=query))\nelse:\n list_client = Client.objects.all()\npage = request.GET.get(...
<|body_start_0|> query = request.GET.get('q') sort = request.GET.get('sort', 'name') form = ClientForm() list_client = None if query: list_client = Client.objects.filter(Q(name__icontains=query) | Q(phone__icontains=query) | Q(email__icontains=query)) else: ...
Clase para crear un servidor
NewClientView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NewClientView: """Clase para crear un servidor""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|> <|body_start_0|> query = request.GET.g...
stack_v2_sparse_classes_75kplus_train_071696
22,221
no_license
[ { "docstring": "Método get", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Método post", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_015036
Implement the Python class `NewClientView` described below. Class description: Clase para crear un servidor Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post
Implement the Python class `NewClientView` described below. Class description: Clase para crear un servidor Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post <|skeleton|> class NewClientView: """Clase para crear un serv...
e28e2d968372609ad396c42fb572a00c2410a117
<|skeleton|> class NewClientView: """Clase para crear un servidor""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NewClientView: """Clase para crear un servidor""" def get(self, request, *args, **kwargs): """Método get""" query = request.GET.get('q') sort = request.GET.get('sort', 'name') form = ClientForm() list_client = None if query: list_client = Client...
the_stack_v2_python_sparse
list/views.py
damaos/server_list2
train
0
4909c750b1d561336fa7b7ae8b4b65e5dacd27f4
[ "if not p and (not q):\n return True\nif not p or not q:\n return False\ncurr_is_same = p.val == q.val\nleft_is_same = self.isSameTree(p.left, q.left)\nright_is_same = self.isSameTree(p.right, q.right)\nreturn curr_is_same and left_is_same and right_is_same", "stack = deque([(p, q)])\nwhile stack:\n node...
<|body_start_0|> if not p and (not q): return True if not p or not q: return False curr_is_same = p.val == q.val left_is_same = self.isSameTree(p.left, q.left) right_is_same = self.isSameTree(p.right, q.right) return curr_is_same and left_is_same a...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: """Recursive DFS Time complexity: O(min(p, q)) == O(n) Space complexity: O(min(p, q)) == O(n)""" <|body_0|> def isSameTreeIterativeDFS(self, p: Optional[TreeNode], q: Optional[TreeNode]) ->...
stack_v2_sparse_classes_75kplus_train_071697
2,240
permissive
[ { "docstring": "Recursive DFS Time complexity: O(min(p, q)) == O(n) Space complexity: O(min(p, q)) == O(n)", "name": "isSameTree", "signature": "def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool" }, { "docstring": "Iterative DFS Time complexity: O(min(p, q)) == O(n) Spac...
3
stack_v2_sparse_classes_30k_train_001153
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: Recursive DFS Time complexity: O(min(p, q)) == O(n) Space complexity: O(min(p, q)) == O(n) - def isSam...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: Recursive DFS Time complexity: O(min(p, q)) == O(n) Space complexity: O(min(p, q)) == O(n) - def isSam...
32b0878f63e5edd19a1fbe13bfa4c518a4261e23
<|skeleton|> class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: """Recursive DFS Time complexity: O(min(p, q)) == O(n) Space complexity: O(min(p, q)) == O(n)""" <|body_0|> def isSameTreeIterativeDFS(self, p: Optional[TreeNode], q: Optional[TreeNode]) ->...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: """Recursive DFS Time complexity: O(min(p, q)) == O(n) Space complexity: O(min(p, q)) == O(n)""" if not p and (not q): return True if not p or not q: return False curr_...
the_stack_v2_python_sparse
leetcode/Trees/100. Same Tree.py
danielfsousa/algorithms-solutions
train
2
e0504bbc0ea453cbaae46550972f27050aad3a05
[ "colors[origin] = 0\nqueue = deque()\nqueue.append(origin)\nwhile queue:\n node = queue.popleft()\n nodeColor = colors[node]\n for neighbor in graph[node]:\n if colors[neighbor] is None:\n colors[neighbor] = 1 - nodeColor\n queue.append(neighbor)\n elif nodeColor + color...
<|body_start_0|> colors[origin] = 0 queue = deque() queue.append(origin) while queue: node = queue.popleft() nodeColor = colors[node] for neighbor in graph[node]: if colors[neighbor] is None: colors[neighbor] = 1 - n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mark(self, origin: int, graph: List[List[int]], colors: List[int]) -> bool: """BFS mark graph in 2 colors""" <|body_0|> def isBipartite(self, graph: List[List[int]]) -> bool: """The idea is to mark vertices with 2 colors. If 2 vertices on same edge are ...
stack_v2_sparse_classes_75kplus_train_071698
2,707
no_license
[ { "docstring": "BFS mark graph in 2 colors", "name": "mark", "signature": "def mark(self, origin: int, graph: List[List[int]], colors: List[int]) -> bool" }, { "docstring": "The idea is to mark vertices with 2 colors. If 2 vertices on same edge are in same color, then the graph is not Bipartite"...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mark(self, origin: int, graph: List[List[int]], colors: List[int]) -> bool: BFS mark graph in 2 colors - def isBipartite(self, graph: List[List[int]]) -> bool: The idea is to...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mark(self, origin: int, graph: List[List[int]], colors: List[int]) -> bool: BFS mark graph in 2 colors - def isBipartite(self, graph: List[List[int]]) -> bool: The idea is to...
ad2f5bd0aec3d2c2c77b7c18627c1dd8fe8c0653
<|skeleton|> class Solution: def mark(self, origin: int, graph: List[List[int]], colors: List[int]) -> bool: """BFS mark graph in 2 colors""" <|body_0|> def isBipartite(self, graph: List[List[int]]) -> bool: """The idea is to mark vertices with 2 colors. If 2 vertices on same edge are ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def mark(self, origin: int, graph: List[List[int]], colors: List[int]) -> bool: """BFS mark graph in 2 colors""" colors[origin] = 0 queue = deque() queue.append(origin) while queue: node = queue.popleft() nodeColor = colors[node] ...
the_stack_v2_python_sparse
785 Is Graph Bipartite?.py
jz33/LeetCodeSolutions
train
8
faa4852ead83c1ec64ef76edb96889633eb64ad4
[ "super().__init__(*args, **kwargs)\nfor field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'", "user = super().save(commit=False)\nuser.set_password(self.cleaned_data['password'])\nif commit:\n user.save()\nreturn user" ]
<|body_start_0|> super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' <|end_body_0|> <|body_start_1|> user = super().save(commit=False) user.set_password(self.cleaned_data['password']) if commit: ...
Форма для регистрации пользователей
MyRegisterForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyRegisterForm: """Форма для регистрации пользователей""" def __init__(self, *args, **kwargs): """Переопределяем метод init для формы, чтобы задать нужные классы""" <|body_0|> def save(self, commit=True): """переопределяем Save чтобы правильно сохранять пароли по...
stack_v2_sparse_classes_75kplus_train_071699
4,125
no_license
[ { "docstring": "Переопределяем метод init для формы, чтобы задать нужные классы", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "переопределяем Save чтобы правильно сохранять пароли пользователей", "name": "save", "signature": "def save(self, co...
2
null
Implement the Python class `MyRegisterForm` described below. Class description: Форма для регистрации пользователей Method signatures and docstrings: - def __init__(self, *args, **kwargs): Переопределяем метод init для формы, чтобы задать нужные классы - def save(self, commit=True): переопределяем Save чтобы правильн...
Implement the Python class `MyRegisterForm` described below. Class description: Форма для регистрации пользователей Method signatures and docstrings: - def __init__(self, *args, **kwargs): Переопределяем метод init для формы, чтобы задать нужные классы - def save(self, commit=True): переопределяем Save чтобы правильн...
2242d925b08b450bca927e2b5a59a13725e37d33
<|skeleton|> class MyRegisterForm: """Форма для регистрации пользователей""" def __init__(self, *args, **kwargs): """Переопределяем метод init для формы, чтобы задать нужные классы""" <|body_0|> def save(self, commit=True): """переопределяем Save чтобы правильно сохранять пароли по...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyRegisterForm: """Форма для регистрации пользователей""" def __init__(self, *args, **kwargs): """Переопределяем метод init для формы, чтобы задать нужные классы""" super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = '...
the_stack_v2_python_sparse
myproject/regabitur/forms.py
Pauuukin/abiturient
train
0